Production-Grade LLM Inference: Optimizing Latency, Throughput, and Cost

    Production LLM inference is judged under sustained, variable traffic and strict SLOs—not one-off demos. This article frames the serving path as an end-to-end system (admission through KV cache, scheduling, and observability), then covers measurable goals, operator fusion and shape stability, communication/parallelism, memory and paging, prefill vs. decode scheduling, quality and rollout, and a practical optimization order.

    Production LLM inference is not “a demo that runs once.” It must hold tail latency, throughput, and unit cost under continuous traffic, bursty concurrency, and strict service objectives. Lab setups with a fixed batch size, fixed sequence length, and average latency rarely match real load: request lengths vary, prompts often repeat, output length is unknown, and peaks alternate with troughs. Treat inference as a full pipeline—not a stack of isolated kernels. That pipeline typically includes request admission, tokenization and validation, scheduling and queuing, prefill, token-by-token decode, KV-cache management, collective communication, result return, plus monitoring, rate limiting, and fault isolation.

    Define goals before choosing optimizations

    Write goals as measurable constraints first; otherwise engineering time is spent on the wrong axis. Common goals fall into three classes.

    Interactive latency. For chat, completion, and agent tool calls, users care about time to first token (TTFT) and inter-token latency. TTFT is driven by prefill compute, queue wait, and cache hits. Token interval is driven by decode memory bandwidth, batching, and communication.

    Throughput. Offline labeling, batch summarization, and overnight index builds care about tokens or requests completed per unit time. Higher queue time is acceptable if a larger effective batch raises accelerator utilization.

    Economics. Accelerators, host memory, network, and storage all cost money. The goal is not to starve every resource, but to raise effective token yield under the SLO while cutting idle time, fragmentation, and duplicate compute.

    These goals conflict. Larger batches raise throughput but lengthen queues and TTFT. Aggressive low precision can ease bandwidth but hurt quality on some tasks. Cache reuse cuts prefill but consumes device memory. Production systems should configure policy by traffic type rather than chase a single “best” parameter set.

    Operators: fusion, precision, and stable shapes

    The hot path is concentrated: attention, FFN, normalization, and sampling dominate device time. Operator work should cut memory round-trips, raise parallelism, and make shape changes predictable.

    Fusion is the most general lever: merge elementwise ops, normalization, and matmul so intermediate tensors do not land as often. Fusion must stay correct and maintainable—numeric range, masks, variable-length sequences, and edge cases need paired tests. A speedup on one sequence length is not enough.

    Precision should differ by stage. Weights, activations, and KV cache need not share a format. Prefill is more compute-dense; decode is more bandwidth-bound; cache footprint often caps concurrency. Lowering cache precision usually frees more concurrency than lowering all compute precision, but quality must be checked on business samples—not only perplexity or a single benchmark.

    Dynamic shapes are the production default. Recompiling or re-selecting kernels per request makes tail latency unstable. Bucket common lengths, send extremes down a slow path, and cache compiled or tuned kernel configs. Revisit bucket boundaries from the real length distribution so most requests are not stuck on bucket edges with wasted padding.

    Illustrative kernel selection (hardware-neutral):

    1. def pick_kernel(seq_bucket, batch, dtype, has_mask):
    2. key = (seq_bucket, batch, dtype, has_mask)
    3. if key in kernel_cache:
    4. return kernel_cache[key]
    5. kernel = autotune_offline(key) # offline autotune; online is lookup only
    6. kernel_cache[key] = kernel
    7. return kernel

    The online path should only look up and run. Keep autotune offline or in a canary so peak traffic does not search kernels and inject jitter into user requests.

    Communication and parallelism: hide latency, do not add sync points

    When a model does not fit on one GPU, or extra GPUs are used for concurrency, tensor, pipeline, or expert parallelism appears. Benefit depends on whether compute covers communication. A sync after every layer adds communication delay to every token and hurts interactive traffic first.

    Useful patterns: overlap collectives with unrelated compute; reduce small messages (inference should merge activation shards and necessary all-gathers—not gradient/activation exchange from training); keep communication buffers stable to avoid runtime reallocations; evaluate cross-node bandwidth and jitter separately instead of extrapolating from single-node multi-GPU results.

    Pipeline parallelism is sensitive to bubbles. Prefill is one long compute; decode is many short steps. Splitting stages only by parameter count leaves short stages waiting. Split by measured time, and allow different parallel strategies for prefill and decode. Expert-routed models also face imbalance: hot experts stall the whole step. Use capacity factor, overflow policy, and monitoring rather than assuming balanced routing.

    Memory: KV cache, paging, and fragmentation

    Each generated token rereads historical K/V. As concurrency grows, cache often becomes the bottleneck before FLOPs. Memory management is a core serving module, not a side optimization.

    Reserving a contiguous max-length slab is simple but wasteful—most requests never hit the cap. Paged or blocked cache allocates fixed-size blocks on demand and raises concurrency. The cost is address mapping and kernels that handle non-contiguous blocks. Blocks that are too small raise management overhead; too large raise internal waste. Tune against the real length distribution.

    Prefix reuse reduces duplicate prefill. System prompts, templates, and shared multi-turn prefixes belong in a shared cache. Isolation and invalidation matter: tenants must not share private context; template version changes must invalidate old entries; under memory pressure, eviction must be explicit (LRU, prefix heat, or business priority).

    Host memory can extend device memory: cold cache off-device, hot cache on-device. Swap must overlap the decode pipeline or every token pays a synchronous copy. Bound paging storms: if the working set exceeds device memory and access has little locality, expansion does not pay off.

    Fragmentation matters on long-lived processes. Allocators that slice only in arrival order leave unmergeable holes. Use periodic compaction, generational allocation, or separate pools per length bucket. Soak-test before release and watch free-block count and largest contiguous block for a sustained drop.

    Scheduling: treat prefill and decode as two job types

    Prefill processes the full prompt: compute-heavy, relatively bursty. Decode is stepwise: light per step, many steps, cache-resident. Mixing them in one batch lets long prompts stall short in-flight generations and hurts interactive tails. Never mixing them can leave the device idle between decode steps.

    Continuous batching frees slots as sequences finish and admits new work, avoiding static batches that wait for the slowest request. On top of that, split queues: reserve a stable time slice for decode to protect token interval; put prefill on a preemptible or splittable queue, and chunk very long prompts so the device can yield.

    Expose at least: max concurrent sequences, per-batch token budget, prefill priority, queue timeout, and per-tenant quota. On timeout, fail fast or degrade—do not queue forever. Rate limits should distinguish protecting the system from dropping work that could finish: delay retryable offline jobs; return a clear busy signal early for interactive traffic so upstream can retry or fail over.

    A simplified loop:

    1. loop:
    2. admit_new_requests(quota, free_cache_blocks)
    3. batch_decode = pick_decode(running, token_budget)
    4. batch_prefill = pick_prefill(waiting, remaining_budget)
    5. run(batch_prefill) # may be split across steps with yield
    6. run(batch_decode)
    7. release_finished()
    8. record_latency_and_cache()

    The point is budget and yield, not a specific runtime. Production loops must also handle cancel, timeout, and partial failure so abandoned requests do not keep holding cache after compute finishes.

    Quality, stability, and release

    Latency that destroys answer quality is not a successful optimization. After changing fusion, precision, sampling, or cache layout, compare business metrics on a fixed sample set and keep a small online holdout. Sampling parameters, stop conditions, and system prompts are part of service quality and should be versioned with kernels so issues are reproducible.

    Observability should cover queue wait, prefill time, decode step time, cache hit rate, device memory watermark, communication time share, and error codes. Averages are not enough; tails reflect interactive experience. When tails rise, distinguish queueing, compile, communication, paging, and a few ultra-long requests.

    Roll out with canaries: compare outputs and resource curves on shadow traffic, then raise the share. Every optimization should be independently disableable. Do not ship fusion, cache precision, bucketing, and schedule budgets as one irreversible blob. Rehearse rollback, including cache-format changes that would prevent old processes from starting.

    Capacity-plan from real distributions, not the product of peak parameters. Collect prompt length, generation length, prefix reuse rate, and arrival process to estimate cache-block demand and batch shapes. Leave headroom for bursts and failover. With multiple replicas, load balancing should prefer sending reusable prefixes to replicas that already hold that cache without overheating one replica—affinity versus balance, driven by metrics rather than a one-shot rule.

    Suggested implementation order

    A more reliable order: measure metrics and length distributions first; then remove obvious memory waste and static-batch idle time; then bucketing, kernel lookup, and continuous batching; then precision, fusion, and communication overlap; last, cross-node and complex parallelism. Each step needs a control experiment and an exit criterion. If a change only works on synthetic benches and vanishes on mixed traffic, stop promoting it and revisit load assumptions.

    Production inference is stable resource efficiency on an uncertain request stream. Operators, communication, memory, and scheduling must be designed together. Faster kernels alone do not fix cache fragmentation or queue head-of-line blocking; more hardware does not hide duplicate prefill or unobservable tails. Clear goals, load, and rollback paths turn one-off tuning into repeatable engineering.