Engineering Large Language Model Inference for Production: A Practical Guide

    This guide explains how to turn a working LLM API call into a reliable production inference service. It covers the core trade-off between latency and throughput, how to calculate GPU memory budgets, four high-impact optimizations such as batching and KV cache reuse, a layered architecture, stability patterns, cost and capacity planning, evaluation and observability, and security compliance, followed by a phased rollout roadmap.

    1. Why “It Works” and “It Works Well” Are Separated by a Whole Layer of Engineering

    Many teams can get a single large language model call running during validation. Once the workload moves into production, however, problems tend to surface all at once: jittery response latency, runaway cost per request, GPU memory overflow on long-context requests, and throughput that collapses as concurrency rises. The root cause is usually not the model itself, but the absence of engineering design in the inference service.

    The key difference from a traditional web service is that inference time is dominated by computation and GPU memory bandwidth, and the resource footprint of a single request changes dynamically with input length and output length. Capacity planning therefore cannot rely on the old “estimate by QPS” approach. Input and output length distributions, peak concurrency, and tolerable latency all need to be factored in.

    2. Build the Right Performance Model First: The Latency vs. Throughput Trade-off

    Inference performance comes down to two core metrics: Time To First Token (TTFT) and inter-token latency. TTFT determines how long a user waits before seeing any response; inter-token latency determines whether the output looks smooth. Both are often in tension with overall throughput: larger batch sizes raise throughput and dilute cost, but they also lengthen the queueing time for each individual request.

    A common engineering practice is to set tiered targets. Interactive scenarios prioritize TTFT; offline batch scenarios prioritize throughput and cost. Mixing the two traffic types in the same resource pool is one of the most common starting points for both cost overruns and degraded experience.

    1. Interactive traffic -> latency-first: small batches, short timeouts, fail fast
    2. Offline batch jobs -> throughput-first: large batches, queueable, retryable

    3. GPU Memory Is a Hard Constraint: Do the Math Before Optimizing

    GPU memory usage breaks down into roughly three parts: model weights, intermediate activations during inference, and the key-value (KV) cache that holds historical context. The KV cache grows linearly with context length and concurrency, making it the most easily overlooked variable in long-context scenarios.

    A practical estimation approach: first use the weight footprint to determine how many model instances fit on a single GPU, then divide the remaining memory by the estimated per-request context cache to get the concurrency ceiling. If the result shows insufficient concurrency, prefer shortening context, enabling cache reuse, or switching to a smaller model size rather than blindly adding GPUs.

    4. Four High-Value Optimizations

    1. Batch scheduling. Merging multiple requests into a single forward pass is the most direct way to raise throughput. The key is choosing a sensible maximum batch size and waiting window so that latency is not sacrificed just to fill a batch.
    2. Context cache reuse. System prompts, long documents, and few-shot examples often repeat across requests. Caching and reusing these intermediate results can significantly cut redundant computation.
    3. Quantization and precision trade-offs. Lowering numerical precision within an acceptable quality loss reduces both memory footprint and bandwidth pressure, but it must be validated with regression evaluation on real business samples, not just general-purpose leaderboards.
    4. Output length governance. Capping maximum generation length and steering the model toward concise answers is the most underrated part of cost control, and often more effective than switching models.

    5. Layered Architecture: Make Inference as Available as Water and Power

    Split the capability into four layers, decoupled through explicit contracts:

    • Access layer: authentication, rate limiting, request body validation, and audit logging.
    • Scheduling layer: routes requests to inference resource pools of different sizes based on scenario tags.
    • Inference layer: hosts model instances and exposes unified streaming and non-streaming call semantics.
    • Support layer: object storage for datasets and artifacts, a message queue for peak shaving and asynchronous decoupling, a container platform for elastic scaling, and logging plus monitoring and alerting for observability.

    When deploying on Baidu AI Cloud, these support capabilities can map directly to general cloud product categories, so teams do not need to build the entire infrastructure stack themselves and can focus their effort on scheduling strategy and business adaptation.

    6. Stability Design: Degradation, Timeouts, and Idempotency

    Production systems must assume dependencies will fail. Three baselines cannot be skipped. First, an end-to-end timeout budget that decreases layer by layer from access to inference, so requests never pile up indefinitely. Second, tiered degradation: when the primary path is under heavy load, fall back to a smaller model or a cached answer. Third, idempotency and retries: write-type calls must carry an idempotency key to prevent retries from producing duplicate side effects.

    Version management for prompts and model versions is equally important. Every change should be releasable via canary rollout and rollback; otherwise a single quality regression can trigger widespread business complaints.

    7. Cost and Capacity: Do the Math Before Launch

    Cost evaluation should cover four resource types: inference compute, storage, network egress, and observability data volume. Account by “cost per effective request” rather than “hourly resource price,” and include invalid requests (timeouts, rate-limited calls, empty outputs) in the denominator to get a real number.

    For capacity, use a “baseline plus elastic” model: baseline resources guarantee day-to-day stability, elastic resources absorb peaks, and queue buffering smooths out burst traffic.

    8. Evaluation and Observability: No Measurement, No Optimization

    Evaluation should have three layers: general capability regression, business scenario suites, and live production sampling. Teams that rely only on the first layer often discover after launch that business metrics fall short.

    Observability should collect at least four signals: latency distribution (look at P95/P99, not just the mean), throughput and queue length, failure and degradation rates, and per-request context and output length. Turn these metrics into dashboards with alert thresholds so optimization has a clear direction.

    9. Security and Compliance Essentials

    Four baseline requirements: bidirectional filtering of inputs and outputs, masking of sensitive information, audit trails for calls, and minimizing data retention periods. For scenarios involving user data, define clear boundaries on data usage and access permissions, and avoid writing full raw text into logs.

    Phase one: use a single model size to connect the pipeline end to end and build an evaluation set. Phase two: introduce batching and cache reuse to drive down cost per unit. Phase three: add multi-size routing and elastic scaling, and complete degradation and canary rollout. Phase four: consolidate platform capabilities, turning prompts, evaluation sets, and monitoring dashboards into reusable team assets.

    Overall, the competitiveness of a large model application does not depend on whether it uses the newest model, but on whether the inference pipeline is genuinely engineered: constraints calculated clearly, bottlenecks identified precisely, degradation that holds, and costs that can be explained. Following the order above, most teams can achieve stable business results with a controlled investment.