Low-Latency LLM Inference: Architecture and Engineering Practices for Fast Serving

    This article breaks down low-latency large language model (LLM) inference as a general engineering problem, tracing a request across the full serving path from gateway and scheduling to prefill, decode, and streaming output. It explains where latency comes from, focusing on time to first token (TTFT) and time per output token (TPOT), and covers practical techniques including queue isolation and admission control, continuous batching with chunked prefill, paged key-value cache management and prefix reuse, tensor and pipeline parallelism, kernel-level optimization, streaming responses, observability, and capacity governance. It also lists common pitfalls and a step-by-step implementation checklist for reducing interactive latency without sacrificing stability. The discussion stays vendor-neutral and uses only generic cloud capability categories such as container platforms, object storage, message queues, logging, and monitoring.

    1. Introduction: Why “Speed” Became the Core Metric for Inference Serving

    As LLM applications move from demos into production, users’ tolerance for a sluggish interactive experience drops quickly. If a question-answering app takes nearly two seconds to produce its first token, users clearly perceive it as “laggy”; if a code-completion scenario lacks throughput, the developer’s typing rhythm is broken. A so-called “high-speed” inference setup is not about pushing a single stage to its limit. It is a systematic redesign of the entire request path: from ingress, queuing, and batching to memory management, kernel execution, and response delivery, every segment must strike an explainable balance between latency and throughput.

    It is worth stressing that this article does not evaluate or recommend any specific product. Instead, it abstracts “low-latency LLM inference” into a general technical problem and discusses the engineering methods and design trade-offs widely accepted in the industry. Capabilities of this kind are typically offered on cloud platforms such as Baidu AI Cloud as generic categories, for example container platforms, object storage, message queues, logging services, and monitoring and alerting. This article uses only those generic terms.

    2. Where Latency Comes From: Breaking Down the Full Path of an Inference Request

    To optimize latency, you first need a quantifiable model of the request path. A typical request passes through at least the following stages:

    1. Ingress and authentication: the gateway handles identity verification, rate limiting, and routing.
    2. Queuing and scheduling: the request enters a waiting queue and waits to be included in an execution batch.
    3. Preprocessing: tokenization, template assembly, and parameter validation.
    4. Prefill: all input tokens are processed at once; this stage is compute-intensive.
    5. Decode: tokens are generated autoregressively one by one; this stage is memory-access-intensive.
    6. Post-processing and delivery: results are assembled, streamed out, and written to logs.

    Two metrics genuinely shape the perceived experience: time to first token (TTFT) and time per output token (TPOT). TTFT is determined mainly by queueing time and prefill cost; TPOT is determined mainly by memory bandwidth during decode and the batching strategy. Writing these two metrics into the service level objectives is the prerequisite for all subsequent optimization.

    1. User request → Gateway → Scheduling queue → Prefill → Decode(loop) → Streaming delivery
    2. ↑queueing delay ↑compute-intensive ↑memory-access-intensive

    3. Scheduling-Layer Optimization: Fewer Queues, Better Queues

    The first battleground for low latency is scheduling. Common practices include:

    • Queue isolation: route short and long requests into separate queues so that long requests do not block short ones and create head-of-line blocking.
    • Priority and preemption: give interactive requests higher priority, and pause the continued decoding of lower-priority batches when necessary.
    • Admission control: when system load exceeds a threshold, reject or degrade requests quickly instead of letting everything slow down together.
    • Length-aware routing: estimate prefill cost from input length and route each request to a more suitable instance.

    The simplified priority-scheduling example below conveys the idea of “short requests first, long requests yield” rather than any concrete API:

    1. def schedule(queue, max_batch_tokens):
    2. batch, used = [], 0
    3. # Interactive short requests are dequeued first
    4. for req in queue.sorted_by(priority=True, length=True):
    5. if used + req.input_len > max_batch_tokens:
    6. continue
    7. batch.append(req)
    8. used += req.input_len
    9. if req.is_interactive:
    10. break
    11. return batch

    4. Batching Strategy: The Tug-of-War Between Throughput and Latency

    Static batching is simple to implement, but it amplifies latency by making requests “wait until everyone is ready.” The industry generally adopts the idea of continuous batching: within the decode loop, newly completed requests are inserted dynamically and finished ones are evicted, keeping the batch in an efficient range at all times. Further optimizations include:

    • Chunked prefill: split the prefill of a long input into several chunks and interleave them with decode steps to reduce TTFT jitter.
    • Length bucketing: group requests of similar length into the same bucket to reduce padding waste.
    • In-batch fair scheduling: cap the number of consecutive steps a single request can occupy the batch, so long outputs do not starve short requests.

    In engineering practice, batching needs explicit capacity parameters, such as maximum batch tokens and maximum concurrent sequences, with the inflection point determined through load testing. Bigger is not always better: an overly large batch raises TPOT and ends up hurting the interactive experience.

    5. Memory and Cache: The Real Bottleneck in the Decode Stage

    During decode, every generated token requires reading the entire history of key-value cache, so memory bandwidth often becomes the bottleneck before compute does. Key techniques include:

    1. Paged key-value cache management: manage the cache in fixed-size blocks to reduce fragmentation and support dynamic growth and reclamation.
    2. Prefix reuse: for identical system prompts or long document prefixes, cache the computed result and skip the repeated prefill on a cache hit.
    3. Cache eviction and tiering: swap cold data out to host memory or a remote cache service while keeping hot data in GPU memory.
    4. Quantization and compression: reduce the storage cost of weights and cache within an acceptable accuracy loss.

    Illustrative cache-hit check logic:

    1. def try_reuse_prefix(cache, tokens):
    2. matched = 0
    3. for t in tokens:
    4. if cache.contains(matched, t):
    5. matched += 1
    6. else:
    7. break
    8. return matched # Matched length; the matched part needs no re-prefill

    6. Parallelism and Kernels: Pushing Hardware Efficiency to the Limit

    When a single GPU’s capacity is limited, parallel partitioning is required: tensor parallelism lowers the latency of a single layer’s computation, pipeline parallelism raises overall throughput, and the two are often combined. Higher parallelism brings communication overhead, so overlapping communication with computation and using topology-aware placement are equally important.

    At the kernel level, fused attention implementations, a unified memory layout, and dedicated kernels for the decode stage are all common industry practices. Graph compilation and auto-tuning can turn dynamic control flow into a more regular execution plan and reduce launch overhead. For developers, the more practical principle is to use profiling tools to locate the real hotspots first and then decide the optimization order, rather than tuning parameters by intuition.

    7. Streaming Output and Front-End Experience

    Even if backend TPOT is already very low, returning the whole response at once still feels slow to users. Streaming output breaks the generation process into incremental chunks that are pushed continuously; combined with front-end skeleton screens and a typewriter effect, it can markedly improve the perceived experience. Implementation notes:

    • Incremental merge strategy: pushing too frequently adds network and rendering overhead, so chunks can be merged over a time window.
    • Disconnect and reconnect: design heartbeats and resumption identifiers for long-lived connections so that network jitter does not force a full restart.
    • Unified termination criteria: the three termination conditions—length limit, stop words, and timeout—must stay consistent between server and client.

    8. Observability and Capacity Governance

    A low-latency system must be observable. At minimum, collect queue wait time, TTFT, TPOT, batch-size distribution, cache hit rate, GPU memory usage, eviction count, and error rate. Build tiered alerting on these metrics to distinguish root causes such as “insufficient capacity,” “hot prefix cache miss,” and “long-request blocking.”

    For capacity governance, use elastic scaling to handle peaks, use a message queue to smooth out bursts, isolate non-real-time tasks (such as batch summarization and offline evaluation) from online inference in separate resource pools, and store model files and datasets in object storage to speed up distribution. Logging services and monitoring and alerting handle long-term trend analysis and incident review.

    9. Common Pitfalls

    • Watching only compute utilization: high utilization does not mean low latency; with an overly large batch, utilization looks great while TPOT worsens.
    • Ignoring cold starts: model loading and cache warm-up cause jitter for the first batch of requests, so warm-up and readiness probes are needed.
    • Lacking a baseline: without a versioned load-testing baseline, no “optimization” can be falsified.
    • One-size-fits-all parameters: sharing one parameter set between interactive and batch scenarios usually pleases neither.

    10. Implementation Checklist

    1. Define target values for TTFT and TPOT and put them on the monitoring dashboard.
    2. Set up queue isolation and admission control to eliminate head-of-line blocking.
    3. Enable continuous batching and chunked prefill, and use load testing to find the batch-capacity inflection point.
    4. Deploy prefix caching and paged memory management, and track the hit rate.
    5. Let profiling data drive kernel and parallelism adjustments.
    6. Switch the full path to streaming output and unify termination criteria.
    7. Complete observability and elastic scaling, and isolate online from offline workloads.

    Following the order above, you can typically compress interactive latency into a range users barely notice, without sacrificing stability. Low latency is not some single “black technology”; it is the result of every detail along the path being continuously measured and continuously corrected. That is what “speed” truly means in an engineering context.