LLM Inference Optimization: Engineering Paths to Low-Latency Token Generation

    This article breaks down the core engineering techniques behind fast LLM inference, focusing on single-request generation latency rather than model size. It defines the key metrics teams should measure, including TTFT, TPOT, end-to-end latency, throughput, and tail latency, and explains why decoding is constrained by memory bandwidth instead of compute. You will learn how KV cache paging, continuous batching, chunked prefill, speculative decoding, quantization, and parallelism trade off against one another, how to assemble them into a layered low-latency serving architecture, and which evaluation pitfalls distort benchmark results. The goal is a practical path from latency budgets to a reproducible high-throughput decoding system.

    1. Background: Why Generation Speed Became a Core Metric

    In a demo at an industry technical conference, the model that drew the most attention was not the one with the largest parameter count. It was a lightweight model that streamed output continuously in milliseconds: a small game’s source code scrolling in real time on screen, while the tokens-per-second counter in the top-right corner climbed into four digits.

    The scene was striking because it turned the hardest metric in LLM engineering — single-request generation latency — into something visible to the naked eye.

    For developers, capability gains arrive gradually, but a broken interaction experience shows up suddenly. Once time to first byte (TTFT) exceeds one second, or once streaming output visibly stutters, users immediately perceive “slowness” — yet they rarely credit a model with being “smarter.” Inference-side optimization is therefore not ancillary work; it is one of the main lines that determines whether a product is usable.

    This article does not revolve around any specific vendor’s product. Instead, it unpacks the general engineering capability behind demos like that one: how high-throughput decoding is achieved, and how you can reproduce a similar experience in your own system.

    2. Turning “Fast” into Measurable Metrics

    Before discussing speedups, you need a shared set of measurements; otherwise optimization loses focus. The industry typically tracks these quantities:

    • TTFT (Time To First Token): time from request dispatch to receiving the first token, determined mainly by the prefill stage and strongly correlated with input length and compute parallelism.
    • TPOT / ITL (Time Per Output Token / Inter-Token Latency): the average interval per token during decoding, which decides whether output “flows smoothly.”
    • End-to-end latency: TTFT plus output length multiplied by TPOT — the wait users actually feel.
    • Throughput (tokens/s or requests/s): total system output per unit time, which determines unit cost.
    • Tail latency (P95/P99): the number capacity planning actually depends on; averages tend to hide queuing and jitter.

    A common mistake is optimizing throughput alone. Raising batch size does amortize the cost of reading weights, but it degrades each request’s TPOT, which makes interactive products feel laggy. The right approach is to first set the business budget for TTFT and TPOT, then work backward to the batching strategy and parallelism configuration.

    3. The Real Decode-Stage Bottleneck: Memory Access, Not Compute

    Autoregressive decoding generates only one token per step, so matrix operations degenerate into matrix-vector products with extremely low arithmetic intensity. The limiting factor here is usually the bandwidth for moving weights and the KV cache from GPU memory to the compute units, not the floating-point peak. This judgment drives a series of optimization directions:

    1. Reduce the data moved per step: weight quantization (INT8/INT4 are common approaches), KV cache quantization.
    2. Increase data reuse: pack multiple requests into one batch so a single read serves several sequences — the basic motivation for continuous batching.
    3. Reduce the number of decoding steps: ideas such as speculative decoding and parallel sampling verify multiple candidate tokens in one forward pass.
    4. Compress context length: the KV cache grows linearly with sequence length, making long context a dual source of latency and memory pressure.

    A schematic decode loop (pseudocode, expressing control flow only):

    1. # Simplified illustration: real systems add paged cache, continuous batching, and operator fusion
    2. kv_cache = allocate_cache(max_seq_len, num_layers, num_kv_heads, head_dim)
    3. def generate(prompt_ids, max_new_tokens, cache_slots):
    4. prefill_and_fill(kv_cache, prompt_ids, cache_slots) # compute-bound, determines TTFT
    5. token = sample_next(prompt_ids, kv_cache)
    6. yield token # return first byte as early as possible
    7. for _ in range(max_new_tokens - 1):
    8. token = decode_one_step(token, kv_cache, cache_slots) # memory-bound, determines TPOT
    9. yield token

    4. Six General Acceleration Techniques and Their Trade-offs

    4.1 Paging and Reusing the KV Cache

    Splitting the cache into fixed-size blocks allocated on demand significantly reduces fragmentation and enables prefix sharing. For scenarios with a fixed system prompt or multi-turn conversations that share history, prefix caching can cut TTFT by an order of magnitude. On the engineering side, you need well-designed cache eviction and reference counting to avoid block leaks.

    4.2 Continuous Batching and Scheduling

    Traditional static batching must wait for the whole batch to finish before admitting new requests, causing severe head-of-line blocking. Continuous batching schedules at iteration granularity: completed sequences leave immediately and new requests are inserted immediately. The scheduler must balance free memory, maximum batch size, and fairness at the same time, usually with a priority queue so long requests do not starve short ones.

    4.3 Chunked Prefill

    Prefilling a long input in one shot occupies compute for a long time and stalls requests that are currently decoding. Splitting a long prefill into small chunks and interleaving them with decode steps keeps TPOT smoother, at the cost of slightly higher TTFT. This is a typical “latency fairness” trade-off.

    4.4 Speculative Decoding

    A small draft model or lightweight heuristic guesses several consecutive tokens, then the main model verifies them in parallel in a single pass; accepted tokens are adopted directly. The hit rate depends on draft quality, and the gains are most visible in memory-bound scenarios. The implementation difficulty lies in monitoring the acceptance rate and handling rollback logic.

    4.5 Quantization and Sparsification

    Weight quantization directly reduces the bytes moved, and KV quantization eases long-context pressure. Watch for accuracy regressions, especially on numerically sensitive tasks; it is advisable to build a tiered evaluation set and run the same regression suite before and after quantization.

    4.6 Parallelism Strategies

    Tensor parallelism lowers per-GPU memory pressure but introduces communication overhead; pipeline parallelism improves overall utilization but may increase single-request latency. Interactive serving usually prioritizes TPOT first, then considers scaling out.

    5. Reference Architecture: A Low-Latency Generation Pipeline

    A deployable layered design looks like this:

    • Access layer: authentication, rate limiting, and lightweight routing based on input length and estimated output length.
    • Scheduling layer: continuous batching + chunked prefill + priority queue, exposing queue depth and wait-time metrics.
    • Inference layer: quantized weights, paged KV cache, prefix reuse, with speculative decoding enabled when needed.
    • State and data layer: session history in low-latency storage, long text and artifacts in object storage, asynchronous paths decoupled with a message queue.
    • Observability layer: a logging service collects TTFT/TPOT histograms, alerting thresholds are set on P99 and error rate, and distributed tracing pinpoints which layer the queuing happens in.
    • Elasticity layer: a container platform hosts stateless replicas, scaling on queue depth rather than CPU utilization.

    Schematic server-side metric instrumentation:

    1. # Illustrates instrumentation structure only; no specific platform API is involved
    2. metrics.observe("ttft_seconds", ttft, labels={"route": route_name})
    3. metrics.observe("tpot_seconds", tpot, labels={"model_size": size_class})
    4. metrics.increment("queue_wait_total", labels={"priority": priority})

    6. Evaluation Methods and Common Pitfalls

    • Fix randomness before comparing: inconsistent temperature and sampling strategies make A/B comparisons meaningless.
    • Separate cold start from steady state: the first request includes cache and weight-loading overhead and should be measured separately.
    • Load test with the real length distribution: uniformly distributed lengths severely underestimate long-context pressure.
    • Look at histograms, not averages: P99 determines scaling thresholds and timeout settings.
    • Measure end to end, not just operators: networking, serialization, and streaming chunking all contribute meaningful latency.

    7. Conclusion

    The impression of “thousands of tokens per second” comes from a coordinated set of optimizations: quantization and cache paging at the memory level, continuous batching and chunked prefill at the scheduling level, speculative decoding at the algorithm level, plus an observability system centered on P99. For a team, the pragmatic path is to constrain the design with TTFT and TPOT budgets first, then introduce the techniques above one by one with dual regression testing on accuracy and latency. If you need elastic capacity and full-pipeline observability, you can build on general capabilities such as the container platform, object storage, message queue, and log monitoring offered by Baidu AI Cloud, leaving the optimization focus on the model and the scheduler themselves.