LLM Inference Latency Optimization: An Engineering Path to Low-Latency Generation

    This article breaks down large language model inference latency into measurable metrics, explains why autoregressive decoding is bound by memory bandwidth rather than compute, and walks through six general optimization techniques—continuous batching, KV cache management, speculative decoding, quantization, compilation and kernel optimization, and output length control. It also covers tiered deployment across model sizes, a four-step rollout plan, and acceptance criteria based on tail latency and rollback readiness.

    1. Why Generation Speed Became an Engineering Focus

    During a technical conference demo, a cloud vendor showed off a new generation of large models: decoding speed several times that of comparable solutions in a general environment, with further gains on a dedicated agent development platform. The on-stage example generated game code in real time and pushed the tokens-per-second counter in the corner of the screen into the thousands. Notably, the launch did not center on the absence of a flagship model with a larger parameter count; the narrative focused on inference efficiency and developer experience.

    That signal means far more to engineering teams than a higher benchmark score. As model capabilities converge, what really shapes product experience is the latency curve: whether users are willing to wait, whether agents can run multiple autonomous turns in a row, and whether the unit cost of batch offline jobs can be pushed down. So this article discusses no specific product. Instead, it abstracts the topic into a general engineering problem: how to systematically reduce LLM inference latency and raise decoding throughput.

    2. Define the Metrics First: Latency Is Not a Single Number

    Most performance debates reach contradictory conclusions because they mix different metrics together. A rigorous measurement splits into at least four:

    • Time to first token (TTFT): time from request dispatch to the first token received, driven mainly by the prefill stage and strongly correlated with input length and peak compute.
    • Time per output token (TPOT): average time per step in the decode stage, which determines whether the typewriter effect feels smooth.
    • End-to-end latency: total duration, equal to TTFT plus output length multiplied by TPOT.
    • Throughput and cost: total output tokens per second, cost per million tokens, and the concurrency that can be sustained under a latency constraint.

    A common misjudgment is looking only at end-to-end latency. For interactive applications, users perceive stutter once TTFT exceeds a few hundred milliseconds; for agent-style long chains of tasks, unstable TPOT causes tool-call timeouts and retry storms. An illustrative set of formulas:

    1. End-to-end latency ≈ TTFT + output tokens × TPOT
    2. Effective throughput = concurrency × per-stream output rate
    3. Unit cost = per-GPU cost / effective throughput

    3. Why Decoding Is Slow: Memory Bandwidth, Not Compute

    Before understanding optimization techniques, you have to understand where the bottleneck sits. Prefill can process the entire input in parallel and is compute-intensive. Autoregressive decoding, by contrast, produces one token per step and must move all model weights and the ever-growing key-value cache from GPU memory to the compute units, which makes it memory-access-intensive. This explains a counterintuitive phenomenon: doubling compute often yields limited gains in decoding speed.

    Three practical principles follow. First, reducing the amount of data moved per step is the main line of speedup, and quantization and cache compression both serve it. Second, raising parallelism so a single memory access serves more requests is the main line of total throughput, and continuous batching serves it. Third, reducing the number of steps themselves—producing multiple tokens in one forward pass—is what speculative decoding serves.

    4. Six General Optimization Techniques and Their Trade-offs

    4.1 Continuous Batching and Scheduling

    Static batching requires the whole batch to start and finish together, so short requests get held back by long ones. Continuous batching swaps requests in and out dynamically at the token level: whoever finishes leaves, and the free slot is filled immediately. In practice you also need priority queues and timeout control so long-output requests do not crowd out interactive traffic:

    1. # Pseudocode: scheduling skeleton for continuous batching
    2. while queue or running:
    3. while can_admit() and queue:
    4. running.append(queue.pop(priority=INTERACTIVE))
    5. for req in running:
    6. token = model.decode_step(req.kv_cache) # one memory access serves the whole batch
    7. emit(req, token)
    8. if req.finished or req.exceeded_budget:
    9. running.remove(req) # release cache immediately and backfill

    4.2 Key-Value Cache Management

    The cache grows linearly with context and is the main source of memory pressure in long sessions. A common approach is paged management, which cuts the cache into fixed-size blocks allocated on demand to reduce fragmentation. Combine that with prefix reuse so requests sharing the same system prompt or document hit the same cache blocks, and prefill can skip the repeated computation. For very long contexts, evaluate compression strategies such as sliding windows or sinking attention onto a small set of key tokens; the cost is possible loss of remote information.

    4.3 Speculative Decoding

    A lightweight draft model guesses several tokens in a row, then the main model verifies them in a single parallel forward pass. Correct guesses are accepted directly; wrong ones roll back to the point of divergence. The benefit depends entirely on the acceptance rate: the closer the draft distribution is to the main model, the more obvious the speedup, while a low acceptance rate adds overhead instead. Draft model selection and guess length both need tuning against your actual business corpus.

    4.4 Quantization and Low Precision

    Compressing weights from high precision to 8 bits or lower directly reduces the bytes moved per step, which pays off significantly for memory-access-bound decoding. The trade-off is precision loss: for format-sensitive tasks such as code generation and structured extraction, build a small regression set and compare version by version rather than relying only on general benchmark scores. Weight quantization is usually safer than activation quantization, which is more sensitive to outliers.

    4.5 Compilation and Operator Optimization

    Operator fusion, custom attention kernels, and graph compilation targeting specific hardware cut kernel launch overhead and round trips of intermediate tensors. These optimizations do not change model semantics, so they are low-risk and high-reward, and should generally land before any lossy compression technique.

    4.6 Output Length Governance

    The most easily overlooked optimization is not letting the model ramble. Constraining output structure through prompts, setting a reasonable maximum generation length, and returning the reasoning process separately from the final answer can substantially shorten decoding steps without losing usable information. In agent scenarios, also summarize tool results before feeding them back into the context to suppress cache growth.

    5. Tiered Deployment: Match Latency Budgets to Model Sizes

    In practice, a single model rarely covers all traffic. A workable approach routes requests by difficulty and latency budget: high-concurrency, low-complexity intent recognition and format conversion go to a small, fast model; tasks needing multi-step reasoning and long-context understanding go to a larger model; cost-sensitive offline batch jobs run asynchronously on a high-throughput configuration, never competing with online traffic for resources. Routing rules can start with heuristic thresholds and gradually be replaced by a lightweight classifier.

    On the cloud, the reusable general capabilities include container platforms for elastic replicas and rolling upgrades, object storage for model weights and datasets, message queues for smoothing and retrying offline jobs, and logging plus monitoring and alerting systems that collect TTFT, TPOT, and error rates with tiered alerts. Baidu AI Cloud offers the same category of general infrastructure capabilities in these scenarios; the specific selection should be decided by load testing against your own traffic characteristics.

    6. Rollout Path and Acceptance Criteria

    Move forward in four steps, letting data decide whether to continue at each one:

    1. Establish a baseline. Fix the dataset and load-test scripts, record the four metrics—TTFT, TPOT, throughput, unit cost—and define separate SLOs for interactive and offline paths.
    2. Do the lossless optimizations first. Operator compilation, continuous batching, cache paging, and prefix reuse go live in sequence and typically already deliver meaningful gains.
    3. Then evaluate lossy optimizations. Quantization and cache compression must be validated for quality on the business regression set, with an acceptable quality-degradation threshold defined.
    4. Finally introduce speculative decoding and model routing, tuning continuously based on acceptance rate and routing accuracy.

    For acceptance, avoid looking only at averages; focus on P95/P99 percentiles and long-tail timeout rates. Also keep a one-click rollback switch so any optimization can revert to the previous version without changing business code. Once this measurement and tuning loop is in place, the gains from model iteration can be converted reliably into experience improvements users actually perceive, instead of staying as peak numbers on a demo stage.