Time to First Token (TTFT) Optimization: Cutting First-Token Latency from 12s to 0.48s

    This article examines why Time to First Token (TTFT) matters more than raw generation speed in multi-turn AI coding assistants, using a research experiment where an AI agent built its own inference engine and achieved a P90 TTFT of 0.48s versus 12s for a mature framework. It breaks down the request-to-first-token pipeline and details three optimization areas—prefix caching, cache-aware scheduling, and framework/kernel co-tuning—along with practical engineering takeaways for measuring and improving perceived responsiveness.

    Introduction: The Overlooked “Time to Speak”

    You are debugging a login error with an AI coding tool. You apply the suggested fix, rerun the tests, and the same red error appears in the terminal. You paste the new logs into the chat, hit enter, and wait.

    How long? Usually just a few seconds. But across a multi-turn session, those seconds stack up. Fixing a single bug often takes three or four back-and-forth rounds; waiting an extra ten seconds per round adds a full minute to one debugging session. The more hidden cost is attention: ten seconds is enough to switch back to the editor and start reading code, breaking your train of thought—and when the reply finally arrives, you have to rebuild context all over again.

    The industry typically measures this wait as Time To First Token (TTFT)—the time from sending a request to the model emitting its first token. Together with “time per output token,” it shapes the interactive feel: TTFT determines “how long until you see a response,” while the latter determines “how fast the reply streams in.” In multi-turn coding assistants, TTFT often affects efficiency more than generation speed, because you go through it again on every single turn.

    Case Background: Letting an Agent Build Its Own Inference Engine

    A research study on “whether agents can build agents” offers a representative experiment. In an offline environment, researchers gave an AI coding tool a basic server codebase, 4 high-end accelerators, and 12 hours, tasking it with implementing an inference engine from scratch: accept user requests, schedule the GPUs to run model computation, and stream generated replies back. The environment prohibited internet access, so every design decision had to rely on the model’s own knowledge.

    After the engine was built, evaluation didn’t stop at code review—it replayed real coding sessions directly: two engines ran the same model on equivalent hardware, handling 16 concurrent requests in parallel. The core metric was P90 TTFT—sort all requests’ first-token wait times and take the value at the 90th percentile, representing “90% of requests start replying within this time.” Compared to the average, P90 better exposes long-tail stalls, and the long tail is the main source of degraded interactive feel.

    The results were striking: a mature inference framework had a P90 TTFT of about 12 seconds, while the agent-built engine came in at just 0.48 seconds. Yet once output began, both had nearly identical median generation speed—about 125 tokens per second. In other words, the gap wasn’t in “how fast they speak,” but in “how fast they start speaking.”

    Where the Wait Goes: The Path from Request to First Token

    From sending a request to emitting the first token, a request typically passes through these steps in order:

    1. Connection and queuing: The server accepts the connection, completes authentication, rate-limit checks, and request parsing;
    2. Scheduling and allocation: Based on KV cache match, sequence length, and remaining GPU memory, it decides which instance and which batch handles the request;
    3. Prefill: A single parallel forward pass over all input tokens, producing the KV cache and the first output token;
    4. Sampling and return: Sample from the output distribution and stream the first token back to the client.

    Intuitively, parallel computation makes prefill fast, so the bulk of latency should be in “queuing.” But the data from this case reveals a more fundamental cause: recomputation.

    Optimization One: Don’t Make the Server Re-read Long Context

    Picture a common interaction: you ask the tool to edit a web page. You’ve already pasted the source code and error messages, and tried a few approaches. This round you just add one line: “move the login button a bit to the right.”

    In a naive implementation, the server must recompute everything before this new instruction just to “understand” the current line. The longer the surrounding context, the longer prefill takes, and the higher the TTFT. In multi-turn sessions, context only grows, so wait times keep climbing.

    Mature frameworks usually have an automatic prefix reuse mechanism: for identical prefixes, they reuse the cached KV state directly and skip recomputation. The key gap between the self-built engine and the mature framework in this case lay precisely in how thoroughly this mechanism was covered.

    Scenario Naive Implementation Prefix Cache Hit
    First-turn request, no history Full prefill Full prefill
    Append a short instruction Full recompute Only compute the new segment
    Retry request (identical content) Full recompute Nearly zero prefill
    Prefix has slight differences Full recompute Compute from the branch point

    What determines the actual benefit is the “cache hit rate.” The higher the hit rate, the more computation is skipped, the fewer long-tail requests, and the more pronounced the P90 drop; on a miss, both engines start from the same line, which is why the median generation speed is nearly identical.

    Common coverage approaches in engineering include:

    • Session-level KV cache reuse: Later turns in the same session hit directly, while cross-session requests are isolated by session ID;
    • Independent system prompt caching: Place stable segments like role settings and output specs at the front, and align tokenization boundaries to ensure cross-session reuse;
    • Send only diffs for edit requests: Don’t send the full file—send only the changed block plus a little context, shortening the prefix at the source.

    Optimization Two: Scheduling Determines the Long Tail

    Caching solves “how much a single request must compute”; scheduling solves “how requests affect each other.” Under 16-way concurrent replay, requests recur across multiple engine instances and multiple turns, and the scheduling strategy directly determines P90.

    In practice, you can start from these directions:

    • Cache-aware routing: Prioritize assigning a new request to an instance that already holds its prefix, so reuse actually happens;
    • Short-request priority: Prioritize requests with “short context and little output,” preventing short requests from being stuck waiting behind long tasks;
    • Input-length admission control: Queue or split overly long requests separately, preventing them from crowding out the processing window for interactive short requests;
    • Incremental routing: Some frameworks support dynamically adjusting routing within a single generation, shifting load away from long-sequence instances.

    Take “first-turn long-document summarization” versus “second turn appending just one modification”: the former is heavy, the latter light, but under naive scheduling the lightweight request can be pinned behind the long task, and its wait is rapidly amplified. P90 measures exactly this long tail.

    Optimization Three: Joint Tuning of Framework and Kernels

    On top of caching and scheduling, the self-built engine also compressed single-prefill time through joint tuning at the framework and operator levels. Common approaches in public technical materials include:

    • Unified memory management: Manage the KV cache in a paged manner to reduce fragmentation and copying, improving GPU memory utilization and the upper limit on batch size;
    • Custom kernel fusion: Merge attention computation and sampling into a single execution, reducing read/write of intermediate tensors and kernel launch overhead;
    • Graph capture and zero-copy transfer: Lower the fixed overhead of the scheduling layer, so short requests don’t pay for framework overhead.

    These techniques reduce the fixed cost of each prefill. Note that the 4th accelerator reserved GPU memory for model weights, and the KV cache still had to share the remaining space with the weights, so the number of cache entries and their residency time had to be traded off within limited memory rather than retained without limit.

    Engineering Takeaways: Make “Time to Speak” a First-Class Metric

    The direct lesson from this case for building intelligent applications is that latency optimization should be treated as a systems engineering effort, not a single-point tuning exercise.

    1. Define metric tiers: Observe P50/P90/P99 TTFT and decoding speed together—use P90 to guard the long-tail experience and the median to reflect overall throughput;
    2. Reshape request forms: Place stable system instructions at the front and switch multi-turn edits to diff transmission, reducing recomputation from the input side;
    3. Cache-aware scheduling: Factor “whether the prefix hits” into routing decisions so caching actually pays off;
    4. Ensure cache consistency: Reclaim caches promptly when a session ends or context becomes invalid, preventing stale state from being returned;
    5. Close the observability loop: Instrument cache hit rate, queue time, and prefill time separately in logging and monitoring/alerting to pinpoint whether the bottleneck is in caching, scheduling, or computation.

    If the application runs in the cloud, you can use a container platform to host engine instances, object storage to hold session and cache snapshots, a message queue to smooth out traffic spikes, and logging/monitoring systems to locate long-tail requests—achieving an optimization effect close to the above at relatively low rework cost.

    Boundaries and Scope

    It must be stated objectively that this result has clear preconditions: the same model, equivalent hardware, the same batch of replay traffic, 16-way concurrency, and an offline environment with no external network. It shows that “self-built plus targeted optimization” can deliver significant gains in specific scenarios, but it does not mean a self-built engine beats a mature framework on every dimension—mature frameworks still hold clear advantages in model coverage, operator ecosystems, distributed scaling, and long-term maintenance.

    At the same time, cache reuse is not without cost: it depends on the prefix being exactly identical, offering limited benefit for dynamically concatenated prompts and frequently changing context; the cache itself also consumes GPU memory and must be traded off against batch size.

    Conclusion

    The gap “from 12 seconds to 0.48 seconds” is essentially not a compute gap but an engineering trade-off gap: whether you reuse already-computed context, whether you let short requests pass first, and whether you govern the latency long tail as a first-class citizen.

    For teams building AI coding assistants, intelligent customer service, or any multi-turn interactive application, this lesson transfers directly: first measure the TTFT percentiles, then check whether request prefixes can be reused, and finally review whether scheduling is friendly to short requests. Put “time to speak” into your metrics, and improvements in interactive experience often come faster and more directly than piling on more compute.