High-Throughput LLM Inference: Engineering Practices and Optimization

    This article breaks down the engineering practices behind high-throughput LLM inference, covering how to define key metrics such as TTFT, TPS, system throughput, and tail latency; how to estimate cluster capacity from token usage; and four general techniques for improving generation speed, including continuous batching with chunked prefill, KV cache management and reuse, speculative decoding, and quantization. It also addresses streaming output for frontend experience, observability and load testing, and common pitfalls, showing how to balance stable token output, controlled tail latency, and reasonable unit cost under high concurrency.

    1. What Call-Volume Rankings Reveal About Real Inference Pressure

    Public technical communities often publish rankings of model call volume. In the past week, for example, a lightweight model version entered the top three by cumulative token usage in the trillions, behind only two other versions in the same family. The value of this kind of information for engineering teams is not the ranking itself, but the fact it reveals: lightweight, low-latency model versions are handling the vast majority of real traffic.

    The reason is straightforward. In real business scenarios, most requests are not complex tasks that require long chains of reasoning. They are high-frequency calls with short inputs and short outputs, such as intent recognition, field extraction, text rewriting, code completion, and customer service Q&A. These requests are relatively tolerant of per-request quality, but extremely sensitive to time to first token (TTFT) and tokens per second (TPS). As a result, a model family typically forms a layered structure: the flagship version handles difficult problems, while the lightweight version handles scale. The engineering task is to route traffic to the appropriate layer and keep each layer running in its cost-optimal range.

    It is worth emphasizing that any claim such as “providing tens of tokens per second during peak hours” must be understood in a specific context: input length, output length, concurrency, batching strategy, quantization precision, and hardware model can all significantly change measured results. This article therefore does not cite any unconfirmed proprietary performance numbers. Instead, it presents a method you can measure yourself.

    2. Throughput and Latency: Define the Metrics First

    Before discussing high throughput, avoid a common confusion: high throughput does not equal a good user experience.

    • Time to first token (TTFT): the time from sending a request to receiving the first token, determined mainly by queueing time and the prefill stage.
    • Output rate (TPS): the average per-user generation speed during the decode stage, which determines whether the “typewriter effect” is smooth.
    • System throughput: the total number of tokens produced by the entire cluster per unit of time, strongly correlated with batch size, memory bandwidth, and scheduling efficiency.
    • Tail latency (P95/P99): the real constraint for capacity planning. Good averages combined with collapsing tail latency are a common source of production incidents.

    These four factors constrain one another. Increasing the batch size raises system throughput but degrades per-request queueing and TTFT. Setting the output length limit too high allows long-tail requests to occupy memory and slow everyone down. The essence of high-throughput inference is therefore to maximize system throughput under tail-latency constraints, rather than to chase a single peak number.

    3. Capacity Planning: Work Backward from Call Volume to Resource Requirements

    Given statistics such as “how many trillions of tokens per week,” you can perform a rough but highly practical conversion to estimate cluster size.

    Let the total number of tokens in the statistical period be T, with an input ratio of α. The average request size and request count can be approximated as follows:

    1. # Capacity estimation example: for order-of-magnitude estimation only, not any vendor's billing rules
    2. def estimate(total_tokens, input_ratio=0.6, avg_input=800, qps_peak_ratio=3.0):
    3. input_tokens = total_tokens * input_ratio
    4. output_tokens = total_tokens - input_tokens
    5. requests = input_tokens / avg_input # approximate total number of requests
    6. avg_output = output_tokens / requests # average output length
    7. return requests, avg_output
    8. # The peak factor scales "weekly average" up to "peak per-second" load; empirically 2-4x
    9. def peak_qps(requests_per_week, qps_peak_ratio=3.0):
    10. return requests_per_week / 604800 * qps_peak_ratio

    There are three key conclusions. First, the ratio of input to output determines where the bottleneck lies: long inputs concentrate compute pressure on prefill, while long outputs make memory bandwidth and the KV cache the bottleneck. Second, weekly average data must be multiplied by a peak factor to be meaningful for engineering; purchasing capacity based on averages will inevitably collapse at peak times. Third, the average request length is only a starting point. What really matters is the quantiles of the length distribution, and long-tail requests need a separate isolation channel.

    4. Four General Techniques for Improving Generation Speed

    4.1 Continuous Batching and Chunked Prefill

    Traditional static batching requires all requests in a batch to start and finish together, so short requests get held back by long ones. Continuous batching schedules at the token level: as soon as one request finishes generating, it immediately yields to a new request, typically improving memory utilization and system throughput by an order of magnitude. Combined with chunked prefill, which splits an extra-long input into several chunks and interleaves them with decode steps, you can effectively flatten TTFT spikes.

    4.2 KV Cache Management and Reuse

    The KV cache is the main consumer of memory, and its usage grows linearly with “concurrency × sequence length.” Common engineering practices include reusing prefix caches for system prompts and long document prefixes, skipping repeated prefill on a cache hit; retaining session-level caches for multi-turn conversations; and using paged cache management for extra-long contexts to reduce fragmentation.

    1. Request -> Normalization (strip irrelevant whitespace / unify template)
    2. -> Prefix hash lookup (reuse KV on hit)
    3. -> Chunked prefill for the uncached portion
    4. -> Enter the continuous batching queue for decoding

    4.3 Speculative Decoding and Parallel Sampling

    Speculative decoding uses a small draft model to guess several consecutive tokens, then has the main model verify them all in parallel in a single pass. If accepted, it advances multiple steps directly. It delivers clear gains in output rate with almost no loss in quality, at the cost of implementation complexity and draft model overhead. For pattern-heavy scenarios such as code completion, the gains are often more pronounced.

    4.4 Quantization and Memory Optimization

    Using lower-bit weights and cache quantization within an acceptable quality loss allows greater concurrency with the same memory. When putting this into practice, you must build your own evaluation set for before-and-after comparisons rather than copying others’ conclusions. Be especially cautious with numerically sensitive tasks such as financial calculations and legal clause citations.

    5. Streaming Output and Frontend Experience

    High TPS must ultimately translate into smoothness that users can perceive. It is recommended to use incremental transfer to push tokens segment by segment, with the frontend rendering at a controlled pace:

    1. // Example: consume an incremental text stream and render with frame throttling to avoid per-token reflow
    2. const reader = response.body.getReader();
    3. const decoder = new TextDecoder();
    4. let buffer = "", lastPaint = 0;
    5. while (true) {
    6. const { done, value } = await reader.read();
    7. if (done) break;
    8. buffer += decoder.decode(value, { stream: true });
    9. const now = performance.now();
    10. if (now - lastPaint > 33) { render(buffer); lastPaint = now; } // ~30fps
    11. }
    12. render(buffer);

    Two additional details help: first, transmit tool calls and structured output on separate channels from the main text to avoid frontend parsing jitter; second, set output length and timeout limits to prevent a single long-tail request from occupying a connection for a long time.

    6. Observability and Load Testing

    There is no optimization without measurement. At a minimum, collect TTFT P50/P95/P99, the distribution of per-user TPS, batch size and queueing time, cache hit rate, the proportion of truncated requests, and failure and retry rates. Load tests should simulate the real length distribution rather than using only short samples:

    1. # Load-test traffic should approximate the real distribution, with stepped ramp-up to peak
    2. scenarios = [
    3. {"name": "Short Q&A", "in": 200, "out": 100, "ratio": 0.7},
    4. {"name": "Long summary", "in": 6000, "out": 500, "ratio": 0.2},
    5. {"name": "Code completion", "in": 1500, "out": 200, "ratio": 0.1},
    6. ]
    7. # Apply stepped load and watch for the P99 and error-rate inflection point, which is the current capacity limit

    If you build your own inference service, you can rely on a general-purpose container platform for elastic scaling, object storage for models and datasets, a message queue for request peak shaving, and logging and monitoring with alerting to close the loop. If you use a managed model service, focus on checking rate-limiting policies, context limits, and rate-limit response semantics, and make retries use exponential backoff with jitter to avoid retry storms.

    7. Common Pitfalls

    • Looking only at average TPS: averages hide the long tail, and almost all user complaints come from P99.
    • No output length limit: a few extra-long generations occupy the cache for a long time and drag down the entire batch.
    • Poorly designed prefix cache keys: putting timestamps or random IDs into the system prompt means the cache never hits.
    • Retries without backoff: rate limiting plus retries at peak times is equivalent to a self-inflicted attack.
    • Using one model for everything: route by task difficulty in layers, and let the lightweight version handle scale traffic.

    8. Summary

    The real lesson from call-volume rankings is that competitiveness in high-concurrency scenarios comes from balancing three things: stable tokens per second, controlled tail latency, and reasonable unit cost. Define the metrics clearly, plan capacity using the real length distribution, build on continuous batching and prefix caching, improve efficiency with speculative decoding and quantization, and close the loop with streaming rendering and observability. This allows you to reliably deliver a smooth generation experience during peak hours. This approach can be built on top of general-purpose capabilities such as container platforms, object storage, and monitoring and alerting on Baidu AI Cloud, forming a reproducible and measurable inference engineering system.