Reducing Time to First Token from 12 Seconds to 0.5 Seconds: Inference Engine Optimization
A benchmark comparison reported a reduction in P90 time to first token from roughly 12 seconds to 0.5 seconds, with almost no change in generation speed. This article examines how long conversational prompts, prefill processing, prefix caching, and scheduling policies affect inference latency, and outlines practical optimizations for interactive coding workloads.
1. The Overlooked Cost: Waiting After You Press Enter
A typical AI-assisted debugging workflow involves several rounds of interaction. You paste an error log into a chat window, receive a suggested fix, make the change, and run the code again. The terminal still shows the same error. You paste the updated log, press Enter, and wait.
That pause may seem brief in isolation, but it accounts for a substantial share of the interaction. A fix often takes three to five exchanges. If each round requires more than ten seconds before the first token appears, the user’s attention has already shifted from the conversation back to the editor.
More importantly, first-token latency determines whether the interaction feels like a conversation. Once the delay exceeds a second or two, the experience starts to feel less like talking and more like submitting a job.
2. Why Measure P90 Time to First Token?
Mean latency alone is a poor measure of inference-service responsiveness. Long-tailed request lengths, fluctuating concurrency, and differences in cache hits can all make averages misleading. Percentiles provide a clearer view of the experience across requests.
The key metrics are:
- TTFT (Time to First Token): The time from sending a request to receiving the model’s first output token. It directly measures the period when the user sees no response.
- TPOT (Time per Output Token) / generation rate: The interval between tokens after generation starts, or its corresponding throughput measure. This determines how smoothly the response appears.
- P90: The 90th percentile of TTFT values. A P90 of one second means that 90% of requests begin receiving a response within one second.
P90 captures slower experiences better than P50, which represents the median. Interactive programming is particularly sensitive to these slower requests.
3. A Benchmark Comparison Worth Examining
A preprint on agent capabilities, jointly submitted by a university and a research institution, included an inference-engine development task.
The agent received starter server code, four accelerator cards, and a 12-hour time limit. It could not search the internet for reference material. Using AI coding tools, it had to build an inference engine that handled incoming requests, GPU scheduling, and response delivery.
The evaluation went beyond code review. The evaluators replayed the same real coding conversations at 16-way concurrency through two engines running on identical hardware with the same model. The publicly reported results were:
| Metric | Established inference engine | Agent-built inference engine |
|---|---|---|
| P90 time to first token | Approximately 12.03 seconds | Approximately 0.478 seconds |
| Median generation rate | 125.0 tokens/s | 124.2 tokens/s |
The second row is especially important. Once generation began, the engines performed at nearly the same speed. The difference was therefore concentrated before the first token, rather than in hardware capacity or decoding throughput.
4. What Happens Before the First Token: Prefill
Large language model inference has two main stages:
- Prefill processes the input prompt and builds the context state.
- Decode generates output autoregressively, one token at a time.
For long-input workloads like this one, prefill is a dominant contributor to TTFT.
In the replayed coding sessions, each request included accumulated source code, error logs, and previously attempted fixes. At 16-way concurrency, the median input length reached 89,000 tokens.
That is a substantial prefill workload. The intermediate cost of attention processing grows rapidly with sequence length. Users never see this work, but they experience its full cost as waiting time.
The underlying problem is straightforward: a user might add only one sentence, such as “Move the login button slightly to the right,” while the system processes the entire 89,000-token history again.
5. Prefix Caching: Reuse Instead of Recomputation
If a new request begins with exactly the same tokens as an earlier request, the engine can reuse the previously computed state and process only the new suffix. This is prefix caching.
The reusable material consists of intermediate state produced while the model processed the earlier context. Conceptually, the engine needs to preserve:
- Context state: Information from earlier tokens that subsequent tokens can refer to.
- Position and length bookkeeping: Records updated as more tokens are processed, allowing the engine to verify that the cached prefix is correctly aligned.
Cache matching must verify the prefix block by block. The following code illustrates the matching flow:
def match_prefix(cache, tokens, block=256):"""Compare blocks and return the longest reusable prefix length."""reuse = 0for i in range(0, len(tokens), block):chunk = tokens[i:i + block]if cache.get(hash(chunk)) is None:breakreuse += len(chunk)return reuse# After a cache hit, run prefill only on the uncached suffix.cached = match_prefix(cache, tokens)prefill_tokens = tokens[cached:] # 89,000 tokens -> potentially only a few dozen
When the shared prefix is reusable, an 89,000-token input can require fresh prefill computation for only a few dozen tokens. This reduction in repeated work explains how latency can fall from roughly 12 seconds to less than a second.
6. Why Can an Established Engine Be Slower?
A feature-rich, general-purpose engine does not necessarily perform best on every specialized workload. Several design choices can increase first-token latency:
- Scheduling priorities: Engines optimized for throughput may favor batching, requiring new requests to wait for a batch-formation window.
- Chunked prefill trade-offs: Splitting long prefills into chunks can improve fairness and protect GPU memory, but interleaving other requests between chunks can increase TTFT for an individual request.
- Cache-management policies: Block granularity, eviction policies, and prefix-alignment rules can reduce cache hits when they do not fit a workload with long, shared prefixes.
- Generality overhead: Multitenant isolation, complex routing, and compatibility checks can add fixed overhead to the critical path.
The specialized engine’s advantage was not necessarily a better underlying algorithm. It came from aggressively tailoring the implementation to a particular workload.
7. A Practical Optimization Checklist
1. Measure realistic workloads first
Replay actual conversations rather than relying only on synthetic short prompts. Report P50, P90, and P99 latency instead of just the mean.
2. Maximize prefix-cache reuse
Keep system prompts and conversation-history ordering stable. Place frequently changing content toward the end of the prompt. Avoid inserting timestamps or random IDs at the beginning.
3. Limit batching delays
For interactive workloads, prioritize low-latency queues and set an upper bound on how long requests can wait before being scheduled.
4. Tune block and chunk sizes
Oversized prefill chunks can hurt TTFT, while overly small units can reduce cache reuse and compute utilization. Test the relevant sizes at the target query rate rather than assuming one setting works for every workload.
5. Tier KV state and memory
Keep frequently reused prefixes in GPU memory. When capacity is insufficient, move cached state to host memory or a remote cache, trading data-transfer bandwidth for a higher cache hit rate.
6. Use session-affinity routing
Route requests from the same session to the same engine instance so that routing decisions do not scatter reusable cached state across instances.
7. Monitor continuously
Track three signals together through monitoring and alerting:
- TTFT percentiles
- Cache hit rate
- Queueing time
For cloud deployments, container platforms can host engine instances and support scaling. Object storage can retain replay datasets and benchmark reports. Logging, monitoring, and alerting services can provide operational visibility, while message queues can help smooth traffic bursts.
These are general infrastructure capabilities, separate from the inference engine’s implementation.
8. Conclusion
For this long-context, highly repetitive workload, first-token latency was primarily a problem of redundant computation and scheduling priorities—not raw compute capacity.
When median inputs reach tens of thousands of tokens and successive requests share most of their context, prefix-cache reuse becomes a decisive lever for responsiveness.
The benchmark’s practical lesson is to examine workload fit before reaching for faster hardware. Check whether the engine’s caching and scheduling policies match the requests it actually serves.
Reducing P90 TTFT from roughly 12 seconds to 0.5 seconds was not about generating tokens faster. It was about avoiding repeated processing of what the user had already said.
