LLM Inference TTFT Optimization: How to Cut Time-to-First-Token from 12s to Sub-Second

    This article explains why Time To First Token (TTFT) dominates the experience of AI coding sessions and how to reduce it. Based on a benchmark replaying real programming sessions, it breaks down the pre-generation bottleneck—repeated long-context input, compute-heavy prefill, and queueing—then presents two core solutions: prefix caching with tiered KV cache storage, and prefill/generation disaggregation with priority scheduling and chunked prefill. It also covers P90-based validation metrics and how to assemble these capabilities on the cloud.

    1. The Starting Point: Why Does the AI Take 10+ Seconds to Say the First Word?

    Using an AI coding tool to fix a login error is one of the most common development scenarios today: edit the code, run the tests, see the same red output, paste the new logs back into the chat, and hit Enter to wait for the next round of debugging suggestions. A single bug often takes three to five back-and-forth rounds, and the experience dividing line in each round is not generation speed but Time To First Token (TTFT)—the time from when the request is sent to when the model emits its first word.

    A research team ran a representative controlled experiment in an agentic benchmark: they gave a coding agent a basic server codebase, 4 accelerator cards, and 12 hours, restricted its internet access, and asked it to build its own inference engine to handle request intake, GPU scheduling, and result return. They then validated it by replaying real coding sessions—16 concurrent requests, identical hardware, identical model:

    • Mature industry inference framework: P90 TTFT ~12.0 seconds;
    • Agent-built engine: P90 TTFT ~0.48 seconds;
    • Once generation began, the median throughput of both was nearly identical (~124–125 tokens/s).

    The key takeaway from this data is not “the self-built one is stronger,” but rather: the TTFT gap has nothing to do with generation throughput—it is produced entirely “before the model opens its mouth.” Those 11.5 seconds were spent on queueing, reading context, and prefill.

    2. Bottleneck Breakdown: Where Do the 11 Seconds Before the First Word Go?

    2.1 Repeated Input of Long Context

    The peculiarity of coding sessions is that every round resends the source code, error messages, and proposed solutions from previous rounds. In the test, the median single input was about 89,000 tokens, while the final round often added just one sentence, such as “move the login button a bit to the right.”

    This means the vast majority of compute is spent on recomputing the same preceding context.

    2.2 Prefill Is a Compute-Intensive Stage

    The stage where the model processes the input and produces the first token is called prefill. It performs matrix operations over the entire input in one pass and is compute-intensive; the subsequent token-by-token generation is memory-bandwidth-intensive. The two have completely different resource profiles, and mixing them in one queue hurts both: an 80,000-token long request enters, and the first word of every short request behind it gets stalled.

    2.3 Queueing and Scheduling Amplify the Long Tail

    P90 measures the long-tail experience. As long as the scheduling policy is first-come-first-served, or long and short requests are mixed together, tail latency gets blown up by a few extremely long requests—this is precisely the real source of the gap between 12 seconds and 0.48 seconds.

    3. Core Solution One: Prefix Caching and Tiered KV Cache

    3.1 The Essence of Prefix Caching

    If the beginning of a new request is identical to the previous round, the engine can directly reuse the already-computed intermediate results and only process the newly added tail. Such models typically keep two records: one storing the semantic information of the preceding context for lookup, and one storing the key-value pairs needed for layer-by-layer attention, i.e., the KV cache.

    1. Round N input = [ system prompt + history + source code + error ] + [ new content this round ]
    2. └──── hit prefix cache ────┘ └─ only prefill this part ─┘

    After a hit, the prefill size can drop from 89,000 tokens to a few hundred, and the first-token latency naturally falls into the sub-second range.

    3.2 Engineering Implementation Points

    • Stable prefix: Put the system prompt, tool definitions, and fixed specifications at the very front; do not insert volatile content such as timestamps or random IDs, otherwise the cache is invalidated in full.
    • Append-only sessions: History is only appended, never rewritten; once you roll back or reorder history, the cache chain breaks.
    • Cache capacity and eviction: GPU memory is limited, so evict based on “most recently used + longest prefix match” to avoid hot sessions being pushed out.
    • Tiered storage: Hot data goes in GPU memory, warm data in host memory, and cold data can be offloaded to object storage, migrated back on demand upon a hit.

    3.3 Hit Rate Must Be Observable

    You must monitor the hit rate, average hit prefix length, cache usage, and eviction rate. Without this set of metrics, latency optimization is blind tuning.

    4. Core Solution Two: Scheduling and Batching Strategy

    4.1 Disaggregate Prefill and Generation

    Place the two stages in separate resource pools: the prefill pool consumes compute, the generation pool consumes memory bandwidth, and KV cache handles are passed between them via a message queue, preventing long requests from blocking the first word of short requests.

    4.2 Priority and Chunking

    • Short-request priority: Bucket by input length, and let the short bucket emit the first token first;
    • Chunked prefill: Split overly long inputs into chunks and interleave them with generation requests to prevent head-of-line blocking;
    • Continuous batching: Insert new requests into a batch that is being generated at any time to improve GPU utilization.

    Illustrative logic:

    1. def schedule(req_queue, kv_cache, max_batch):
    2. # 1) Prioritize short inputs to guarantee first-token experience
    3. req_queue.sort(key=lambda r: (r.input_len > SHORT_BUCKET, r.input_len))
    4. batch = []
    5. for req in req_queue:
    6. prefix = kv_cache.match(req.tokens) # longest prefix match
    7. req.prefill_tokens = req.tokens[len(prefix):]
    8. batch.append(req)
    9. if len(batch) >= max_batch:
    10. break
    11. return batch # only prefill the unmatched part

    4.3 Balancing GPU Memory and Concurrency

    A larger batch yields higher throughput, but KV cache usage squeezes the number of concurrent requests. In practice, set a GPU memory watermark; when it is exceeded, degrade the batch size first rather than dropping requests.

    5. Validation Method: Use P90, Not the Average

    To evaluate the first-token experience, fix four conditions: identical hardware, identical model precision, identical concurrency, and the same batch of real session replays. The metrics should include at least:

    • P50/P90/P99 TTFT;
    • Prefix cache hit rate and average hit length;
    • Median output throughput (to confirm the optimization did not sacrifice generation speed);
    • GPU memory usage and queue-time distribution.

    Looking only at average latency hides the long tail, yet the long tail is exactly what users perceive.

    6. Cloud Deployment: Composing General-Purpose Capabilities

    If you would rather not build everything from scratch, you can assemble general-purpose cloud capabilities: a container platform to host the inference service and elastic scaling, object storage to hold the cold cache tier and model files, a message queue to decouple the prefill pool from the generation pool, and logging and monitoring/alerting to track P90 and hit rate. Baidu AI Cloud is typically used as the compute and containerized hosting foundation in this kind of architecture; refer to the official documentation for specific specifications.

    7. Conclusion

    The deciding factor in TTFT optimization is not the model itself, but “whether you are willing to recompute the same preceding context over and over.” Get these four things solid—stable prefix, prefix caching, tiered KV storage, and stage-disaggregated scheduling—and you can compress a wait of over ten seconds down to sub-second. That is an architectural dividend, not a model dividend.