Time to First Token Optimization: How We Cut TTFT from 12s to 0.5s
This article breaks down Time to First Token (TTFT), the delay between pressing Enter and seeing the first token from an LLM. Using a benchmark based on replaying real 16-concurrent coding sessions with roughly 89,000-token inputs, it explains why a mature inference framework showed a P90 TTFT near 12 seconds while a model-written engine reached about 0.48 seconds with nearly identical generation speed. You will learn the four stages that make up TTFT (network, queueing, prefill, sampling), why long context and high concurrency amplify tail latency, and the mechanisms behind the improvement: prefix caching, chunked prefill, and scheduling that favors first-token latency. The article also includes illustrative Python code for prefix-cache matching and prefill batching, plus a practical optimization checklist covering measurement, caching, chunking, streaming, capacity planning, and monitoring.
1. Start with a familiar scenario
You ask an AI assistant to fix a login error. You apply the suggested change, rerun the login test, and the terminal throws the same red error again. You paste the new log into the chat, hit Enter, and wait for it to tell you where to look next.
Fixing a single bug often takes several rounds of this. Two different waits get mixed together here. One is the time you spend running tests and pasting logs, which is determined by your development workflow. The other is the “dead air” between pressing Enter and seeing the first character appear in the chat window. That second wait depends entirely on the inference engine.
The industry typically measures this with Time To First Token (TTFT): the time from when a request is sent to when the model emits its first token. It directly determines “how long after I hit Enter do I see a response.” And the deeper you go into a conversation, the longer the context attached to each turn tends to be, which makes a fast first token harder to achieve. This article is about how to push that first-token wait down to sub-second levels under long context and high concurrency.
2. How the test was run: replaying real coding sessions
Recently, a joint research team from a university and a chip manufacturer published a preprint. Its central question: can an agent build an agent on its own? One of the paper’s tests worked like this:
- Give the model under test a basic server codebase, 4 AI accelerator cards of the same model, and 12 hours, with no network access;
- Ask it to use an AI coding tool to build an inference engine from scratch that receives requests, schedules the accelerator cards to run the model, and sends responses back to users;
- Once the engine is done, judge it not only by code but by replaying real coding sessions against it.
The test ran two engines on identical hardware and model, and replayed the same batch of real coding sessions with 16 concurrent streams:
- Two engines: the engine written by the model under test, and a mature industry inference framework;
- Comparison dimensions: first, P90 Time to First Token. Sort the wait times of all requests; the value at the 90th percentile is P90, meaning 90% of requests begin responding within that time; second, generation speed (tokens emitted per second during the output phase).
Why P90 instead of the average? Because perceived experience depends on “how fast it is most of the time,” not on the average. A small number of very slow requests can ruin the feel, and the average hides that.
3. Results: ~25x faster first token, with generation speed almost unchanged
The comparison:
| Metric | Mature inference framework | Model-written engine |
|---|---|---|
| P90 Time to First Token | ~12.03s | ~0.48s |
| Generation speed (median) | ~125.0 tok/s | ~124.2 tok/s |
Twelve seconds is enough time to switch back to your editor and scan several lines of code around the error; half a second means the first character appears before your hand has even left the keyboard. After the first token, both engines emit tokens at almost the same speed, which shows the gap is not in “generation” but in “before speaking.” Let’s look at where those eleven and a half seconds actually went.
4. What makes up TTFT
To optimize first-token latency, break it down first. A request from dispatch to first token passes through roughly four stages:
- Network and ingress: the request reaches the gateway, completing authentication, routing, and so on. This is usually on the order of milliseconds;
- Queueing: existing requests occupy the compute, and new requests wait in a queue to be scheduled. This stage inflates as concurrency rises;
- Prefill: the model runs one forward pass over the input prompt, producing the intermediate states (KV cache) for all input tokens and the probability distribution for the next token;
- Sampling the first token: taking the first token from the probability distribution.
TTFT ≈ queueing time + prefill time + sampling time. Because attention requires every token to attend to all tokens before it, the compute for the attention part of prefill grows quadratically with input length. So long context is carried mostly by prefill, and high concurrency is carried mostly by queueing. Those eleven and a half seconds are the joint result of queueing and prefill, and each will be addressed below.
5. Why changing one sentence still requires reading ~90,000 tokens
Suppose you are using AI to edit a web page. You have already pasted the source, the error, and several proposed fixes; this round you only add one line: “move the login button a bit to the right.” In the replayed sessions used for testing, the chat history from previous rounds is sent to the server along with every new request, and with 16 concurrent streams the median single-request input was about 89,000 tokens.
A dozen-character instruction triggers prefill of nearly 90,000 tokens. If the engine recomputed from scratch every time, any single 90,000-token request would occupy the accelerator card for a considerable time, and requests queued behind it could only wait. Add 16-way concurrency, and the long tail is quickly amplified, eventually becoming a P90 on the order of 12 seconds.
The optimization idea can be summarized in two sentences: don’t recompute what has already been computed, and slice what must be computed.
6. Where those eleven and a half seconds were saved
6.1 Prefix caching: what’s already computed doesn’t need recomputing
In multi-turn conversations, a new turn’s prompt is usually “old prompt + new content,” and the beginning is often identical. Since the beginning hasn’t changed, there is no need to recompute the intermediate states (KV cache) of those tokens. The engine can retrieve the results computed in the previous round and only process the new part. This is prefix caching. In the test, both engines ran the same sessions, and a large portion of the inputs belonged to this reusable common prefix.
6.2 Chunked prefill: slice long requests so newcomers don’t just wait
A single request’s prefill doesn’t have to be computed all at once. Cutting it into chunks and interleaving them with the decode steps of other requests prevents one very large request from monopolizing compute for a long time, which lowers overall queueing time.
6.3 Scheduling and batching: keeping the wait as short as possible
Beyond reuse and slicing, scheduling itself determines how long queueing lasts. The more requests scheduled into a batch, the larger each batch’s compute, and the longer new requests must wait. When first-token latency is the primary goal, you need to trade off “batch size” against “queueing time” so each request enters computation as early as possible.
6.4 Think in reverse: not every request should be handled this way
It is not surprising that a mature inference framework spends those 12 seconds elsewhere. High-throughput services usually want to pack each batch full of requests to extract higher total throughput; long requests are also often scheduled as one big prefill to reduce scheduling rounds. These tradeoffs pay off for offline batch processing, but the cost lands on scenarios like interactive coding, with short instructions, long context, and accumulated multi-turn history.
So rather than saying the model “wrote a faster engine,” it’s more accurate to say it didn’t apply generic defaults, but re-balanced things for a usage pattern of “produce the first token first, then generate.” Choosing the right optimization direction matters more than stacking more complex algorithms.
6.5 Illustrative code for the two mechanisms
import hashlibimport numpy as npROOT_HASH = b"root"BLOCK_SIZE = 256 # cache is organized in blocksdef block_hash(prev_hash: bytes, tokens: np.ndarray) -> bytes:"""Concatenate the previous block's hash with the current block's tokens, then hash, forming a hash chain."""h = hashlib.sha256()h.update(prev_hash)h.update(tokens.astype(np.int32).tobytes())return h.digest()def match_cached_prefix(tokens: np.ndarray, cache: dict) -> int:"""Return the number of leading tokens that hit the cache; stop immediately at the first block miss."""matched, prev_hash = 0, ROOT_HASHfor start in range(0, len(tokens), BLOCK_SIZE):block = tokens[start:start + BLOCK_SIZE]if len(block) < BLOCK_SIZE: # incomplete tail blocks are not cachedbreakprev_hash = block_hash(prev_hash, block)if prev_hash not in cache:breakmatched += len(block)return matcheddef store_blocks(tokens: np.ndarray, cache: dict) -> None:"""After a request finishes, write complete blocks and their hashes into the cache."""prev_hash = ROOT_HASHfor start in range(0, len(tokens), BLOCK_SIZE):block = tokens[start:start + BLOCK_SIZE]if len(block) < BLOCK_SIZE:breakprev_hash = block_hash(prev_hash, block)cache[prev_hash] = len(cache) # example: position represented by cache entry index
The key to the hash chain: each block’s hash includes the previous block’s hash, so a consecutive run of n blocks matching from the beginning is equivalent to the first n×256 tokens being identical. Here is a simplified scheduling sketch that ties together “match cache first, then fill chunks into the batch”:
CHUNK_SIZE = 2048 # max tokens processed per prefill passdef build_prefill_batch(waiting, cache, budget=8192):batch, used = [], 0for req in waiting: # already sorted by priority: e.g., longest waiting, most recently active session# 1) prefix cache match: reused KV for the hit portion, no recomputationreq.reuse = match_cached_prefix(req.tokens, cache)req.pending = req.tokens[req.reuse:]# 2) chunked prefill: slice long requests into the batch, defer the remainderwhile req.pending and used + CHUNK_SIZE <= budget:req.batch_tokens = req.pending[:CHUNK_SIZE]batch.append(req)used += CHUNK_SIZEreq.pending = req.pending[CHUNK_SIZE:]if req.pending or used >= budget:break # defer requests that don't fully fit, so a few long requests don't crowd out new onesreturn batch
This is only an illustrative sketch. A real production engine also has to handle GPU memory capacity, cache eviction, KV layouts under different parallelism modes, and other details.
7. Pushing first token into sub-second territory: an optimization checklist
Once you understand the mechanisms, proceed with “measure first, then optimize, then verify”:
- Measure first, and break the wait apart. At the ingress layer, record queueing and prefill time separately, and continuously observe P50/P90/P99. Watching only the average leaves the long tail permanently hidden.
- Enable prefix cache reuse. Stable session prefixes (system instructions, fixed context) are naturally suited to caching; tune based on the actual hit rate.
- Chunk long requests, prioritize short ones. Use chunked prefill to bound how long a single long request occupies compute, then order scheduling by session characteristics and wait time so long-context requests don’t block newcomers.
- Use streaming output to change perceived latency. Even if the first token takes a few hundred milliseconds, pairing it with a “typing” indicator and token-by-token return noticeably reduces the felt wait.
- Capacity planning and parallelism strategy. Under high concurrency, queueing time often grows faster than a single prefill’s duration; use load testing to set the per-instance concurrency ceiling, and choose parallelism based on compute and GPU memory bandwidth needs.
- Turn optimization into reusable capability. In the cloud, this kind of work is usually carried by a combination of general product categories: a container platform handles elastic scaling of inference services, object storage holds model files, a logging service records call chains, and monitoring and alerting notify you promptly when P90 crosses the line. When implementing this on Baidu AI Cloud, you can follow the same approach to bring inference-service performance into unified monitoring.
8. Closing thoughts
The “AI writes AI” test reminds developers again that in real interactive scenarios, Time to First Token is the user’s first impression. The real lesson here is not that “the model-written engine is faster,” but three points: performance optimization must start from real workloads; the generic defaults of a mature framework are not necessarily optimal; and seemingly plain techniques like prefix caching and chunked scheduling are often the key to eliminating long-tail waits. To be clear, a single benchmark score cannot replace load testing against your own workload. As a next step, connect segmented timing and P90 monitoring to your inference service, and see where those 12 seconds actually go.
