Engineering Challenges and Best Practices for LLM Inference in Production

    This article explains why LLM inference becomes the main bottleneck when moving from prototypes to production, and how to address it. It defines four key constraints—GPU memory, compute throughput, latency, and unit cost—and walks through practical techniques: quantization and compression order, batching and scheduling, prefix and semantic caching, queue-based elasticity, and observability-driven cost governance. Engineers will find measurement guidance, pseudocode, and capacity-planning formulas for delivering stable inference under limited compute.

    1. From New Capability to New Productivity: Why Inference Engineering Becomes the Bottleneck

    Over the past two years, rapid advances in large model capabilities have moved many applications from proof of concept into real business use. But when teams prepare to move a model into production, they often run into an awkward reality: a demo needs only a single call, while production must handle concurrency spikes, long-tail requests, cost budgets, and stability targets all at once. Seemingly unrelated topics—robot collaboration, disputes over AI messaging, security debt in legacy systems, micro-pore materials research—all point to the same engineering problem: for any frontier capability to create value, it must cross the systems-engineering gap of the “last mile.”

    Inference serving is where that gap shows up most acutely. It is constrained by four variables at once—GPU memory capacity, compute throughput, response latency, and unit cost. Ignore any one of them, and production will amplify it into an incident.

    2. Four Constraint Variables: Get the Metrics Right First

    Before optimizing anything, teams must agree on how things are measured; otherwise optimization efforts work against each other.

    • GPU memory capacity: determines the model size and maximum concurrency batch a single device can hold. It is a hard constraint.
    • Compute throughput: the total tokens processed per unit of time; it sets cluster size and the cost baseline.
    • Response latency: usually split into time to first token and inter-token output interval. The first affects perceived responsiveness; the second affects the long-text experience.
    • Unit cost: the combined cost per thousand tokens or per ten thousand requests, including compute, storage, and operations.

    Together these form an extended “impossible triangle”: raising batch size usually improves throughput and spreads cost, but pushes up time to first token; compressing the model reduces memory usage but may cost accuracy. The essence of engineering decisions is finding an acceptable tradeoff against a clear business SLO.

    3. Memory and Accuracy: A Practical Order for Quantization and Compression

    Running out of GPU memory is the most common first wall. In practice, move from lower risk to higher risk:

    1. Start with weight quantization, converting floating-point weights to a low-bit representation, which usually reduces static memory usage significantly.
    2. Then evaluate the gains from quantizing activations and the KV cache; these depend heavily on batch size and context length.
    3. Only then consider structured pruning or distillation, since both require re-validating accuracy regressions.

    Illustrative quantization configuration pseudocode:

    1. # Illustrative flow only; not tied to any specific implementation
    2. config = {
    3. "weight_bits": 8, # reduce weight precision first
    4. "kv_cache_bits": 8, # evaluate further based on context length
    5. "calib_samples": 512, # calibration set must cover the real distribution
    6. }
    7. model = quantize(model, config)
    8. report = evaluate(model, eval_set) # always keep an accuracy regression report
    9. assert report.delta < THRESHOLD

    The key engineering discipline: any compression must ship with a reproducible evaluation report, and the evaluation set must reflect the real business distribution rather than a generic public one.

    4. Throughput and Scheduling: Batching Is the Highest-Leverage Move

    Within memory limits, batching is the most direct way to raise throughput. Static batching is simple to implement but adds latency while waiting to fill a batch. Continuous batching inserts and removes requests dynamically at the request level, improving utilization substantially, at the cost of more complex scheduling logic and careful preemption and rollback strategies.

    A simplified scheduling loop looks like this:

    1. while serving:
    2. batch = scheduler.form_batch(max_tokens=BUDGET)
    3. outputs = engine.step(batch)
    4. scheduler.retire_finished(outputs)
    5. metrics.observe(batch.size, outputs.latency)

    Three engineering points matter: first, set a token budget rather than batching by request count alone, so long requests cannot crowd out others; second, reserve a high-priority queue for interactive requests, physically isolated from offline batch jobs; third, feed scheduling metrics into monitoring and alerting to close the loop.

    5. Caching and Reuse: The Underrated Cost Optimization

    In real workloads, request repetition is often higher than expected. System prompts, retrieved context snippets for RAG, and common question prefixes all have reuse value. Prefix caching computes an identical prefix only once; semantic caching can return historical results directly within a controlled similarity threshold. When deploying, always set invalidation policies and similarity thresholds, and keep a manual off switch to prevent wrong hits from polluting business results.

    6. Elasticity and Capacity: Use Queues to Flatten Peaks, Metrics to Scale

    Traffic naturally has peaks and troughs. Decouple the ingress layer from the inference layer, use a message queue to absorb bursts, and scale the inference layer automatically on two signals: queue backlog and time to first token. Cold starts are the main enemy of elastic scaling, so keep a minimum number of always-on replicas and pre-warm commonly used model weights. A rough capacity estimate:

    1. replicas ≈ peak QPS × avg output tokens × per-token latency / per-replica concurrency / target utilization

    Target utilization should not be maxed out; leave headroom to absorb long-tail jitter.

    7. Observability and Cost Governance

    No measurement, no optimization. Collect at least four categories of data: latency distribution (watch percentiles, not averages), throughput and batch utilization, GPU memory and cache hit rate, and failure and degradation counts. For cost governance, build usage billing attributed to each business line, turning token consumption into an attributable, optimizable metric instead of a month-end surprise.

    8. Conclusion

    There is no silver bullet for LLM inference engineering—only tradeoffs under constraints. Unify your metrics, make compression and batching rollback-safe processes, build caching and elasticity into the standard architecture, and move observability forward. Teams that do this can deliver reliably with limited compute. For more complete managed training and inference capabilities, Baidu AI Cloud offers product categories such as general container platforms, object storage, log services, and monitoring and alerting, which can be used to build the engineering loop described above.