How Inference Engines Cut “Before-First-Token” Time: Prefill and Prefix Caching Optimization
A comparison of inference engines shows that P90 time to first token can differ by more than 20× even when the model, GPU hardware, and generation speed are nearly identical. The key factors are prefill computation, prefix-cache reuse, memory management, and scheduling strategies for long, repetitive multi-turn sessions. This article explains where TTFT goes and presents general engineering practices for reducing it.
A Significant Gap: Why Similar Inference Engines Can Have 20× Different TTFT
1. The Starting Point: Waiting During Multi-Turn Conversations
Developers who use AI coding assistants have likely experienced this pattern: you ask the model to fix a login error, apply its suggested code changes, and rerun the tests—only to see the same red error messages in the terminal. You paste the new logs into the conversation, press Enter, and wait while the model processes a large amount of context before its response gradually appears.
Fixing a single bug may require several such iterations, with a period of “dead time” between each one. In inference serving, this waiting period is measured as time to first token (TTFT): the total time from when a request is sent until the model produces the first token of its response.
In a recent public agent benchmark, researchers observed a striking difference:
- Using the same model, the same GPU hardware, and the same replay of 16 concurrent real-world coding sessions, a mainstream open-source inference framework achieved a P90 TTFT of approximately 12 seconds.
- An inference engine written from scratch by an AI agent in a constrained environment—roughly 12 hours, no internet access, and only basic server code and GPUs—reduced the same metric to approximately 0.48 seconds.
More importantly, once generation began, the two engines had nearly identical output speeds. Their median generation rates were both around 124–125 tokens per second. In other words, nearly all of the gap occurred before the model started responding.
2. Understanding the Metric: Why P90 Matters
The average latency of individual requests can be distorted by a small number of unusually fast requests. A more useful measure is a percentile. Sort all TTFT values from lowest to highest, and the value at the 90th percentile is the P90 TTFT.
In practical terms, P90 indicates the time within which 90% of requests begin producing a response.
For an interactive coding assistant, P90 TTFT has a direct impact on user experience. A 12-second delay is long enough for users to switch back to their editor and inspect code. With a delay of half a second, the first character may appear almost immediately after they press Enter.
3. Where the Time Goes: The Prefill Pipeline
The path from request submission to the first output token generally includes the following stages:
- Networking and scheduling: The request enters the engine, waits if necessary, and is assigned to a GPU.
- Prefill: The model performs a forward pass over the complete input prompt. It processes the attention and transformation operations for every input token and produces the KV cache.
- Decode startup: Once prefill is complete, autoregressive decoding begins and produces the first output token.
In replayed multi-turn coding sessions, each request contains more than the latest instruction, such as “move the login button slightly to the right.” It also carries the previous conversation history, source-code fragments, and error logs.
With 16 concurrent sessions, the median input length in the benchmark was close to 90,000 tokens. Prefill must process all of these tokens before generation can begin, making it the primary contributor to TTFT.
Coding sessions are also highly repetitive. The prefix of each request is almost identical to the previous request; only a small amount of new content is appended at the end.
4. The Key Optimization: Prefix Caching
This is where one of the most important inference-engine optimizations comes into play: prefix caching, often discussed as part of prompt caching.
If the beginning of a new request matches a prefix processed previously, the engine can reuse the corresponding KV cache. It only computes the newly added portion, then combines the cached and incremental results to continue inference.
The KV cache is not a single file. In common multi-head or multi-query attention architectures, every layer and attention head maintains its own sets of key and value tensors. Together, these form a cache structure that continues to grow as the context expands.
The cache contains, among other things:
- KV blocks that preserve contextual information: These allow the model to refer back to representations formed from earlier content during later decoding.
- Intermediate states that are updated as tokens are read: For example, sliding-window attention mechanisms may maintain running statistics that are updated according to specific rules, much like a ledger balance changes as new entries are added.
The key to cache reuse is prefix matching. Because autoregressive models are causal, the representation of token i depends only on the tokens before it. Therefore, if two requests share the same prefix token by token, the KV values for that prefix can be reused completely.
In practice, engines commonly use hash indexes at block granularity. The content is divided into blocks, hashes are generated and indexed, and incoming requests are matched progressively along their block sequences. The search stops after finding the longest common prefix.
5. Why the Mainstream Framework Did Not Capture the Full Benefit
Mainstream inference frameworks support prefix caching, yet they still produced a P90 TTFT of around 12 seconds in this type of evaluation. Common performance bottlenecks include the following:
- Cache-hit configuration and scheduling policies: Under concurrent load, an overly aggressive eviction policy or an inefficient GPU-memory budget may remove historical prefixes from the cache. Each round then has to recompute the entire prompt.
- Scheduling order: If long prefill requests are not handled with chunked scheduling and appropriate priorities, a 90,000-token request can occupy compute resources for an extended period. This increases TTFT for other requests waiting in the queue.
- Coordination between cache management and inference kernels: Block-table maintenance, paged GPU-memory management, incremental prefill, and chunked prefill must work together efficiently. Even when a cache hit occurs, poorly coordinated data copying and reconstruction can introduce substantial overhead.
The lightweight engine in the benchmark appears to have focused its design on these areas. It treated cache hits as a first-class concern and organized scheduling, memory allocation, and kernels around the repetitive-prefix characteristics of multi-turn sessions.
As a result, most of the 90,000-token input could be served from the cache, leaving only a small amount of incremental computation. The scheduler also avoided allowing long requests to block the entire workload.
6. General Principles for Reducing TTFT
Abstracting away the specific products and benchmark results, the comparison suggests a set of broadly applicable inference-engineering practices:
- Design for the workload shape: Multi-turn conversations and agent loops naturally produce long shared prefixes followed by short incremental updates. Engines should optimize for this pattern instead of focusing only on peak general-purpose throughput.
- Use block-level cache indexing: Build content-addressable indexes around fixed-size KV blocks so that shared prefixes of different lengths can be reused.
- Manage GPU memory at fine granularity: Use paged or pooled KV-memory management to reduce fragmentation and reserve an appropriate portion of memory for cached prefixes.
- Apply chunked prefill and preemptive scheduling: Split very long prefill operations into smaller chunks and allow short requests to be scheduled ahead of them. This helps reduce tail latency rather than merely improving the average.
- Separate the two optimization dimensions: TTFT is primarily affected by prefill and caching, while throughput depends more on decode batching and operator efficiency. These require different strategies and should be evaluated with separate metrics.
7. Conclusion
The difference between 12 seconds and half a second is not the result of a mysterious algorithm. It is the combined effect of a series of engineering decisions: understanding the workload shape, maximizing cache reuse, and preventing long requests from overwhelming the scheduler.
For teams operating their own inference services, P90 TTFT should be treated as a core metric alongside throughput. The fact that an AI agent was able to produce a competent inference engine also highlights a broader point: many inference-serving optimizations do not require cutting-edge research. They require established engineering principles to be implemented carefully and consistently.
