Time to First Token Optimization: Cutting Agent TTFT from 12 Seconds to Under 1 Second
This article examines Time To First Token (TTFT), the latency metric that determines whether an AI coding agent feels responsive, and explains why P90 TTFT matters more than averages. Using a public benchmark that compared a mature inference setup with an agent-built inference engine under identical hardware and 16-way concurrency, it shows how prefill of roughly 89,000 median input tokens creates the delay, and how prefix caching and KV state reuse remove the repeated computation. It closes with a practical optimization checklist covering stable prefixes, cache capacity, chunked prefill, separate latency targets, and realistic load testing.
1. The Overlooked Metric: Time to First Token
When developers work with AI coding tools, the rhythm is usually “submit, wait, read the suggestion, submit again.” Fixing a login error often takes three or four rounds: paste the source code, paste the logs, try a fix, paste new logs. Each round is separated by a blank stretch of waiting, and the length of that stretch almost decides whether the tool feels smooth or painful.
The industry metric for that blank stretch is Time To First Token (TTFT): the time from sending a request to the model emitting its first token. Averages alone can be misleading, because tail requests hurt the experience the most. In practice, engineers rely on P90 TTFT instead — sort all request wait times, and the value at the 90th percentile means nine out of ten requests start responding within that time.
A public technical evaluation offered a representative comparison: under identical hardware and model conditions, replaying the same batch of 16 concurrent real coding sessions, a mature inference setup had a P90 TTFT of about 12 seconds, while an inference engine written by an agent came in at about 0.48 seconds. More importantly, once both started generating, output speed was nearly identical (medians of roughly 124.2 and 125.0 tokens per second).
This data pinpoints the problem clearly: the gap is not in how fast the model speaks, but in the dozen-plus seconds before it opens its mouth. Twelve seconds is enough time for a user to switch back to the editor and read a few lines of code; half a second means the reply appears just after they hit Enter. Let’s break down where those seconds go.
2. Where TTFT Goes: Prefill Is the Main Battleground
Once a request enters the inference service, it goes through roughly three stages: queuing, prefill, and sampling plus first-token output. For agent coding scenarios, the real bottleneck is prefill.
The reason is input size. Multi-turn sessions send the history of previous turns into the model along with the current one: source code, error messages, approaches already tried. In the evaluation, the median single input reached 89,000 tokens. Yet what the user actually added this turn might be a single sentence like “move the login button a bit to the right.”
Prefill computation grows roughly linearly with input length, while the attention portion grows close to quadratically. In other words, to process a dozen new characters, the system recomputes nearly 90,000 tokens. As concurrency rises, this repeated computation quickly saturates compute capacity, and queuing time amplifies the tail further.
3. Saving 11 Seconds: Prefix Caching and State Reuse
The solution is prefix caching: if the beginning of a new request is exactly identical to a previous request, there is no need to recompute it. Reuse the already-computed intermediate results and only process the newly added tail.
The “already-computed results” here refer to the computation records left after the model reads the full text, known as the KV cache: the key (Key) and value (Value) tensors for historical tokens at every layer and every attention head. Some model architectures also retain two kinds of state at the same time — one that preserves prior context for retrieval and backtracking, and one that keeps a more compact recurrent state for long-sequence extrapolation. What engineering actually needs to do is store these states safely per session, match them precisely by prefix, and evict them in an orderly way by capacity.
The core scheduling logic can be sketched as:
# Pseudocode: scheduling core with prefix matchingdef schedule(request, cache_pool):prefix = cache_pool.match(request.tokens) # longest common prefixhit_len = prefix.matched_lengthtodo = request.tokens[hit_len:] # only prefill the new partkv = prefix.kv_state # reuse existing KVkv = prefill(todo, kv) # incremental computationcache_pool.commit(request.session_id, kv) # return cache for next turn reusereturn first_token(kv)
The hit rate depends on two conditions: the prefix must be identical token by token, and the cache must not have been evicted. This explains many cases where “the optimization didn’t work” — inserting a system prompt at the start of a session, changing a timestamp, or reordering how history fragments are concatenated will all cause a prefix mismatch and invalidate the cache instantly.
4. Engineering Practice: An Actionable Optimization Checklist
- Stabilize the prefix: Put the system prompt, tool descriptions, and fixed context at the very front and never change them; place volatile content (timestamps, random IDs, user input) at the end.
- Increase cache capacity and hit rate: Reserve reusable state space for high-frequency sessions, paired with a sensible eviction policy, so long sessions don’t squeeze the cache out.
- Chunked prefill and priority scheduling: Slice very long inputs and interleave them with new requests to prevent a single large request from monopolizing compute and causing head-of-line blocking.
- Separate the two latency metrics: TTFT depends on prefill and queuing; output speed depends on the decode stage. Set targets for each separately rather than lumping them together.
- Make load tests realistic: Replay real sessions with multiple turns, long contexts, and high concurrency; P90/P99 are more informative than averages.
It’s worth stressing that these techniques are general industry practice, and their actual effect depends on model architecture, context length distribution, and hardware conditions — there is no universally optimal set of parameters. To reliably achieve sub-second TTFT, you typically also need observability infrastructure such as elastic container platforms, monitoring and alerting, and logging services, so the sources of tail latency can be traced to specific stages. The general capabilities Baidu AI Cloud offers in these scenarios mainly fall into categories like containerized deployment, metrics collection, and full-chain tracing.
5. Conclusion
The most valuable takeaway from this evaluation is not any single number but the methodology: when agents start building agents, performance optimization shifts from “tuning parameters” to an engineering loop that is measurable, reproducible, and iterable. First define the metric that the user experience depends on, then locate the bottleneck stage, and finally use cache reuse and scheduling strategies to eliminate repeated computation — the gap from 12 seconds to half a second is essentially whether those 90,000 tokens get recomputed or not.
