AI Engineering in Practice: A Guide to LLM Cost Optimization and Compute Scheduling

    As AI systems move from demos to production, engineering quality increasingly determines whether they can operate sustainably. This guide covers three practical areas: optimizing LLM API costs, controlling cloud compute resources, and designing AI connectors. It explains semantic caching, asynchronous processing, model routing, elastic scaling, GPU sharing, distributed training, and communication protocol selection, with starting parameters that should be validated against real workload data.

    Recent developments across the AI industry highlight several issues that engineering teams need to address. The extension of API discounts by an LLM platform reflects the cost pressure faced by application developers. Even well-funded AI companies still need to manage substantial compute bills. Other companies are introducing multiple creative connectors that allow LLMs to work directly with design, image, and audio software.

    These developments point to the same underlying challenge: as AI moves from demonstrations to production, engineering quality in cost control, resource scheduling, and system integration determines whether a project can operate sustainably.

    This article examines three areas and provides practical starting points. All values are initial recommendations and should be adjusted based on workload-specific evaluation data.

    1. Optimizing LLM API Costs

    1.1 Semantic Caching

    When users submit many similar questions, sending every request directly to an LLM can create unnecessary costs. Semantic caching converts a user query into an embedding, searches a cache for previous questions and answers, and returns the cached answer directly when the similarity exceeds a defined threshold.

    Three areas require particular attention during implementation.

    • Similarity threshold: Start by testing a cosine similarity threshold of around 0.92. A threshold that is too low may incorrectly match questions with different intents, while a threshold that is too high may result in a low cache hit rate. Use real user queries to measure the false-match rate before finalizing the threshold.
    • Cache expiration: Assign a TTL, or time to live, to each cache entry. For content involving prices, inventory, or policies, the TTL can range from several minutes to several hours. Stable encyclopedic information may be cached for several days. When the model or prompt version changes, clear the cache namespace associated with that version.
    • Cold starts and fallback behavior: If the cache service fails or vector retrieval takes too long—for example, more than 100 milliseconds—forward the request directly to the LLM. A cache failure should not become a business outage. A newly deployed cache can initially run in shadow mode, recording potential hits without returning cached answers. Once the false-match rate is confirmed to be acceptable, the cache can be enabled for production responses.

    1.2 Asynchronous Concurrency and Streaming

    Streaming output can reduce time to first byte (TTFB), allowing users to see the beginning of a response sooner and reducing perceived waiting time.

    Non-real-time workloads, such as batch text processing, generally do not require streaming. These tasks should be placed in a message queue and consumed by asynchronous workers under rate limits. A queue spreads burst traffic across different time windows and helps prevent requests from exceeding API concurrency or tokens-per-minute limits.

    When a worker receives a rate-limit response, such as HTTP status code 429, it should retry using exponential backoff and enforce a maximum retry count. Tasks that exceed the retry limit should be moved to a dead-letter queue for manual handling.

    1.3 Model Routing and Fallback

    Not every task requires a flagship model. A routing gateway can first classify the request intent:

    • Intent recognition, field extraction, and keyword classification can be handled by smaller or open-source models.
    • Complex reasoning and long-form generation can be sent to a flagship model.

    Before deploying a routing policy, complete three steps.

    1. Build an evaluation set. Collect several hundred labeled samples for each task type and compare the accuracy of the smaller model with that of the flagship model. A task should be downgraded only when the smaller model meets the business accuracy requirements.
    2. Set a confidence threshold. If the smaller model produces a confidence score below a threshold—for example, 0.7—automatically escalate the request to the flagship model for reprocessing.
    3. Release gradually. Initially route 5% of traffic through the new policy. Monitor accuracy, latency, and cost per request. If the metrics remain stable, gradually increase the percentage to 100%. The routing gateway should also support a one-click rollback to a configuration that sends all traffic to the flagship model.

    2. Cloud Compute Scheduling and Cost Control

    2.1 Elastic Scaling with a Container Platform

    Inference services can be deployed on a general-purpose cloud container platform and scaled with a Horizontal Pod Autoscaler (HPA). For GPU inference, scaling decisions should not rely only on CPU utilization. More suitable custom metrics include:

    • Requests per second (QPS)
    • Request queue depth
    • GPU utilization

    These metrics typically need to be exposed through Prometheus and a corresponding metrics adapter so that the HPA can use them.

    The following settings provide reasonable starting points:

    • Set the minimum replica count to maintain baseline capacity. For example, use two instances to reduce the impact of cold starts on initial requests.
    • Scale out when the queue exceeds a defined threshold, such as more than 10 queued requests per instance.
    • Scale in when GPU utilization remains below 30% and QPS falls below half of the baseline.
    • Use a stabilization window of approximately 5 to 10 minutes for scale-in operations to prevent frequent instance startup and shutdown.

    GPU instances take time to start. Scaling thresholds should therefore leave sufficient headroom rather than waiting until the queue is already full.

    2.2 GPU Sharing: MIG and Time-Sliced Sharing

    These two technologies address different requirements and should be selected separately.

    • MIG (Multi-Instance GPU) provides spatial partitioning. At the hardware level, it divides one GPU into multiple independent instances, each with dedicated memory and compute resources. It offers strong memory isolation and is suitable for multi-tenant workloads or services that are sensitive to interference. However, the partition sizes are fixed, and MIG is available only on supported GPU models.
    • Time-sliced sharing provides temporal sharing. Multiple processes take turns using the same GPU. This approach is flexible and works well for small models and low-concurrency services. However, processes do not have isolated GPU memory. A process that consumes all available memory can affect other processes, and latency variation is generally higher.

    A practical selection rule is:

    • Choose MIG when isolation or stable latency is important.
    • Choose time-sliced sharing when models are small, sharing is acceptable, and configuration flexibility is the priority.

    Regardless of the chosen approach, validate P99 latency for a single instance under load testing.

    2.3 Communication Optimization for Distributed Training

    Training cost depends not only on the number of GPUs. Communication overhead between nodes can also increase total training time.

    Mixed-precision training can reduce memory usage and computational requirements. Gradient accumulation can increase the effective batch size without requiring more memory on each GPU and can reduce the number of parameter synchronization operations. High-speed network interconnects, together with framework settings that overlap communication and computation, can further reduce synchronization wait time.

    Before training at scale, measure the linear speedup of a small cluster. If the speedup declines significantly as more nodes are added, investigate the network and communication topology before adding more GPUs.

    3. Technical Architecture for AI Connectors

    3.1 Choosing a Communication Protocol

    Connectors commonly run as plugins inside host applications and need to communicate bidirectionally with local or cloud-based inference services. Two common options are WebSocket and gRPC.

    • WebSocket: WebSocket is relatively simple to implement and is supported by browsers and many host environments. It is suitable for streaming output and pushing event notifications. Its main drawback is that the message format must be defined and maintained separately.
    • gRPC: Built on HTTP/2 and Protocol Buffers, gRPC provides clearly defined interfaces and type safety. It is well suited to server-to-server communication. In browsers and some plugin environments, it usually requires a gateway or additional adaptation.

    If the host is a desktop application or browser extension and the main requirement is event delivery, WebSocket is generally simpler. For server-to-server calls, gRPC is usually more appropriate.

    Regardless of the selected protocol, define the following three rules:

    • Timeouts: Set a timeout for every tool call, such as 5 seconds. After the timeout, return a clear error instead of waiting indefinitely.
    • Retries and idempotency: Retry only idempotent operations.