Optimizing Time to First Token in Inference Engines: A Practical Guide
This article breaks down how to reduce P90 Time To First Token (TTFT) in self-built inference engines, using a real benchmark where latency dropped from about 12 seconds to 0.48 seconds. It covers why TTFT matters for interactive coding assistants, how prefill and repeated context computation create delays, and a three-layer optimization approach built on prefix caching, scheduling and batching, and GPU memory capacity planning. A practical checklist is included for teams building or tuning their own inference services.
1. Background: Where the User’s Wait for the “First Word” Comes From
In real-world use of an AI coding assistant, a single code fix is rarely one round of conversation. It is usually multiple back-and-forth turns: paste in the source code and the error, apply the suggested change, rerun, and paste the new logs back in. After each submission, the user is left waiting until the first word appears in the chat box.
In a benchmark on “agents that can build agents,” a research team had a coding-capable agent implement an inference engine from scratch within roughly a dozen hours, under a constrained network environment, using given base server code and limited compute. The engine had to receive requests, schedule GPUs, run the model, and return generated results. The researchers then validated it by replaying real coding sessions: with the same model, the same hardware, and the same batch of 16 concurrent sessions, they compared the first-token performance of the self-built engine against a mature industry solution.
The result was striking: the mature solution had a P90 time to first token of about 12 seconds, while the self-built engine was about 0.48 seconds. Once output began, the two were nearly identical in generation speed, with median throughput of about 124 and 125 tokens per second respectively. This shows the gap is not in the “generation phase” at all, but almost entirely concentrated “before the engine opens its mouth.”
2. Metric Definition: What P90 Time to First Token Actually Measures
Time To First Token (TTFT) is the time from when a request is sent to when the model outputs its first token. P90 means sorting all requests by this time and taking the 90th percentile: 90% of requests begin responding within that time.
P90 is chosen over the average because the interactive experience is determined by “the slowest batch of users.” An average gets dragged down by a large number of short requests, hiding the reality that long-context requests are repeatedly pushed back in the queue. For a coding assistant, where a single input can easily reach tens of thousands of tokens, P90 is the metric that best matches the actual user experience.
3. Root Cause Breakdown: Prefill and Repeated Context Computation
The stage before the model processes the input and produces the first token is called prefill. It is a compute-intensive operation whose cost is roughly linear in the number of input tokens. In the replayed coding sessions, the median input per turn was about 89,000 tokens, because the source code, errors, and solution discussions from previous turns are all resent together.
The key insight is that the beginning of the current request overlaps heavily with the previous turn. The user may have only added one line this time, such as “move the button a bit to the right,” but if the server recomputes the entire history from scratch, it pays the compute cost again for nearly the same 89,000 tokens.
From this, the optimization path naturally splits into three layers:
- Reuse already-computed results to avoid repeated prefill;
- Keep new requests from queuing behind long ones, improving scheduling;
- Improve GPU memory and batching efficiency so the same compute serves more concurrency.
4. Layer One: Using Prefix Cache Correctly
Prefix Cache keeps the intermediate token states that have already been computed (the KV Cache). When a new request hits the same prefix, it reuses them directly and only computes the newly added part.
Three points matter in engineering:
- The prefix must match token by token exactly; any single change invalidates everything after it;
- The cache has a capacity limit and needs an eviction policy, typically least-recently-used or reference-count-based reclamation;
- In multi-turn sessions, put stable content (system prompts, long-term code context that rarely changes) at the front and volatile content at the back.
An illustrative way to organize a request:
[System prompt][Long-term project context][History turns][New instruction this turn]└──────── Reusable prefix ────────┘└── Recomputed each turn ──┘
Once the hit rate improves, the prefill time for long-context requests drops significantly. This is the main source of pushing the 12-second range down to sub-second.
5. Layer Two: Scheduling and Batching Strategy
Even with a high cache hit rate, P90 will still degrade if scheduling is poor. Common problems include: new requests blocked by long requests, batching windows that are too large and cause queuing, and insufficient GPU memory triggering frequent swapping.
General practices that can be applied:
- Separate the scheduling priority of prefill and decode so a long prefill does not monopolize the device;
- Use continuous batching so requests can enter and leave the batch dynamically at the token level;
- Set queue limits and timeouts to prevent individual requests from waiting indefinitely;
- Apply chunked prefill to very long inputs, splitting one long block into multiple short operations.
6. Layer Three: GPU Memory and Concurrency Capacity Planning
KV Cache usage is proportional to context length and concurrency. When capacity planning is insufficient, the system repeatedly trades off between “cache reuse” and “concurrency capacity,” showing up as latency jitter. In practice, first collect the input length distribution, cache hit rate, and queue duration through monitoring and logging, then set the concurrency limit and cache quota accordingly, rather than guessing numbers based on experience.
7. An Actionable Optimization Checklist
- Make P90 time to first token the core acceptance metric, and observe generation speed at the same time to avoid fixing one at the expense of the other;
- Use real session replay for benchmarking, with an input length distribution that closely matches production;
- Prioritize building prefix caching, and constrain the order in which prompts and context are organized;
- Optimize scheduling by separating prefill from decode and controlling the batching window;
- Build a capacity model, and drive scaling with monitoring and alerts;
- Build the above capabilities on a general container platform, object storage, and a logging and monitoring system to ensure reproducibility and observability.
8. Conclusion
Going from 12 seconds to half a second is essentially not any single-point trick, but eliminating “repeated computation,” straightening out “queuing,” and getting the “capacity” math right. For developers, this methodology transfers directly to any self-built inference service: first quantify the tail behavior of time to first token, then locate layer by layer whether the problem is caching, scheduling, or capacity, and the “instant response” users perceive becomes an engineering result that can be reproduced.
