High-Speed LLM Inference: Engineering Practices and Performance Optimization

    This article breaks down high-speed inference for large language models into two separate metrics—time to first token (TTFT) and output token rate—and explains why both are required for real-time, interactive experiences. It covers the serving techniques that make flagship model quality compatible with high throughput, including continuous batching, chunked prefill, prefix and KV cache reuse, and optimized decoding kernels with quantization. You will also find a portable architecture built on general cloud service categories, guidance for designing controlled benchmark experiments, and a list of common pitfalls such as ignoring tail latency, poor cache key design, and missing cancellation logic. The focus is on reproducible, self-measured results rather than vendor claims.

    1. The Problem: Why “Fast” Long Meant “Small”

    For a long time, the industry has operated under a near-default trade-off: if you want low latency and high throughput, you accept a smaller parameter count; if you want complex reasoning and code generation, you accept long waits. This trade-off is not a law of physics. It is the result of engineering implementations lagging behind. When output speed is only a few dozen tokens per second, generating a complete page with navigation, cards, and charts takes minutes, and the “change one line, see the result” experience of interactive programming simply cannot work.

    Converting the time scale makes it more intuitive. A human blink takes about 0.3 seconds. At an output rate of 400 tokens per second, that interval produces roughly 120 tokens—about a small, complete function body. Once the rate reaches this level, model output shifts from a “batch job” to a “real-time stream.” The frontend can render while it receives, and the user’s perception shifts from waiting to synchronization. This is the real value of high-speed inference: it changes the interaction paradigm, not just benchmark scores.

    2. Two Metrics That Must Be Separate: TTFT and Output Rate

    When engineers discuss “fast,” they need to split it into at least two orthogonal metrics.

    • Time to first token (TTFT): the time from sending the request to receiving the first token, which determines “whether it feels stuck.” In interactive experiences, a TTFT above 1 second is noticeably laggy.
    • Output rate (tok/s): the number of tokens generated per second after the first token, which determines “whether the stream keeps up with reading and rendering.”

    The two are constrained by different stages. TTFT is mainly determined by the compute volume of the prefill stage, queue wait time, and scheduling overhead. Output rate is affected by memory bandwidth during decoding, in-batch concurrency, and kernel efficiency. Conflating the two produces the classic problem where “average latency looks fine, but the typewriter effect stutters.” The practical recommendation is to define SLAs separately—for example, TTFT P95 below 1 second and output rate P10 above a given threshold—so that long-tail requests do not drag down the overall experience.

    3. Why Flagship Capability Can Also Be Fast: Scheduling and Caching Are Key

    Model capability is mainly determined by parameter count and training quality, while speed is mainly determined by the serving stack. Decoupling the two is what makes “having both” possible. There are four core techniques.

    1) Continuous batching. Traditional static batching must wait for the slowest request to finish before releasing resources, so short requests are held hostage by long ones. Continuous batching dynamically swaps requests in and out at token granularity, keeping the GPU at high utilization. In practice, this typically delivers several-fold throughput improvements.

    2) Chunked prefill. Splitting the prefill of a long prompt into small chunks and interleaving them with decoding steps prevents one long input from inflating the TTFT of all other requests. This is the key to pushing P95 TTFT into the sub-second range.

    3) Prefix caching and KV cache reuse. System prompts, tool definitions, and code context often repeat within a session. Reusing their KV significantly reduces repeated computation. The hit rate depends on session structure and cache capacity, so you need to monitor the hit rate rather than only looking at average latency.

    4) Decoding kernels and quantization strategy. Efficient attention kernels, operator fusion, weight quantization, and speculative decoding can increase effective output per unit of bandwidth with almost no loss of capability. Note that quantization and speculative decoding come at a cost, and you must validate that any capability regression stays within an acceptable range using an offline evaluation set.

    An illustrative piece of server-side streaming response logic (pseudocode, expressing control flow only):

    1. # Pseudocode: streaming output with backpressure control
    2. async def stream_chat(req):
    3. cache_key = build_prefix_key(req.system, req.tools)
    4. async with scheduler.slot(ttft_budget_ms=800) as slot:
    5. async for delta in engine.decode(req, prefix_cache=cache_key):
    6. if not client_alive():
    7. slot.cancel() # release resources promptly to avoid wasted occupancy
    8. break
    9. yield to_sse(delta) # push token by token for incremental frontend rendering

    The most easily overlooked engineering detail is cancellation and backpressure. If a slot is not released immediately after the client disconnects, a high-speed service ends up saturated by invalid requests, and measured throughput drops off a cliff.

    4. A Practical Architecture: Building a High-Speed Inference Service on General Cloud Capabilities

    Without relying on any proprietary interfaces, you can assemble a complete solution from general cloud product categories used across the industry.

    • A container platform hosts the inference runtime and scales horizontally based on queue length;
    • Object storage holds model weights and version artifacts, paired with an image registry for canary releases;
    • A message queue smooths request peaks and separates priorities, isolating interactive requests from offline batch jobs;
    • A logging service collects token-level telemetry, with alerting triggered by dual thresholds on TTFT and output rate;
    • A load-testing and evaluation pipeline runs daily regressions to prevent “speed gains that quietly cause capability regression” from shipping.

    On Baidu AI Cloud, the above capabilities are offered as general categories, so teams can combine them according to their own scale and avoid tight coupling to a single runtime.

    5. Validating Results: How to Design a Trustworthy Comparison Experiment

    When comparing different configurations, always control variables: the same model version, the same prompt set, and the same input length distribution. It is recommended to construct three task types: short Q&A (to observe TTFT), long-form generation (to observe output rate stability), and interactive code generation (to observe end-to-end task completion time).

    An example of a reproducible observation table structure:

    Metric Definition Suggested Threshold
    TTFT P95 95th percentile of first-token latency < 1s
    Output Rate P10 10th percentile of decoding rate Not below the target value
    Task Completion Time End-to-end time to produce a usable result < 1min for interactive scenarios
    Cache Hit Rate Prefix reuse ratio Based on the business baseline

    It is worth emphasizing that any specific numbers must come from your own load tests, not from external marketing claims. Demonstrating that “the same task, different configurations, and end-to-end time differing by several times” is more convincing than a single benchmark point.

    6. Common Pitfalls

    • Looking only at average latency and ignoring the long tail, so most requests feel acceptable while a few are completely stuck;
    • Poor cache key design (putting timestamps or random IDs into the prefix), driving the hit rate to zero;
    • Unbounded maximum output length, where long-tail requests occupy slots for extended periods;
    • Missing cancellation logic, so disconnected requests keep consuming compute;
    • Skipping capability regression after speedups, resulting in hidden quality regression.

    7. Conclusion

    High throughput and flagship capability are not opposites. Define SLAs separately for TTFT and output rate, build the serving stack with continuous batching, chunked prefill, cache reuse, and efficient decoding, then use general cloud capabilities to close the loop on elasticity and observability. Only then do interactive AI programming and real-time generation truly become usable. When rolling out, rely on your own load-test data, start with a small canary, and gradually increase traffic.