Compressing First Token Latency: From 12 Seconds to Half a Second in AI Inference Engines

    This article explores how AI inference engines optimize first token latency (TTFT), a critical but often overlooked user experience metric. Through a benchmark test where an AI agent independently built an inference engine, we examine how strategic prefix caching reduced P90 TTFT from 12 seconds to 0.48 seconds compared to a mature open-source engine. The analysis covers the mechanics of the prefill and decode stages, the implementation of KV cache reuse for multi-turn dialogues, and actionable principles for optimizing real-world AI inference workloads.

    1. An Easily Overlooked UX Metric: First Token Latency

    When using an AI coding assistant to fix a login error, the typical workflow looks like this: paste the error logs into the dialog box, hit Enter, and wait for the AI to provide troubleshooting suggestions. After modifying the code based on the suggestions, you run the tests again. If the same error occurs, you paste the new logs back in and start another round of conversation. Pinpointing a bug often requires several back-and-forth iterations.

    In this process, the factor that truly impacts the user experience is often not the speed at which the model generates its reply, but the blank time between submitting the prompt and seeing the first character output by the AI. During this time, the user has nothing to do but wait. If the wait exceeds 10 seconds, the user will likely switch back to their editor to search the code themselves; if the wait is under 1 second, the conversational experience feels like real-time Q&A.

    The common metric for measuring this is P90 Time-To-First-Token (TTFT): sorting the wait times from request submission to the start of model output across all requests, and taking the 90th percentile value. In other words, 90% of requests will begin receiving a reply within this timeframe. Compared to averages, P90 better reflects the worst-case user experience, as long-tail requests are exactly what users perceive most noticeably.

    2. A Fascinating Benchmark: Can an Agent Build an Agent?

    Recently, researchers from a university and a chip manufacturer released a preprint study called the “Singularity Benchmark.” The core question was: Can an AI agent build an AI agent? That is, under restricted conditions, can an AI agent independently complete a system-level task that typically requires a senior engineer?

    One particular task was highly representative: researchers provided basic server code and several high-performance GPUs, restricted the agent’s internet access, and required it to build a complete inference engine from scratch within a limited time using intelligent coding tools. The engine’s functionality had to cover the entire pipeline—from receiving user requests and scheduling GPUs to run the model, to returning the generated results to the client.

    The value of this task lies in the fact that it tested not just “whether the agent could write runnable code,” but “whether the written code could achieve production-level performance.” Therefore, the evaluation went beyond code review and employed real-load stress testing: the engine built by the agent was compared against a mature open-source inference engine under identical hardware and model conditions, replaying the same batch of 16 concurrent real programming sessions to compare P90 TTFT.

    The test results were staggering: the mature engine had a P90 TTFT of about 12 seconds, while the engine built by the agent in a short time achieved only about 0.48 seconds—faster by an order of magnitude. More interestingly, once generation began, the throughput speeds of both engines were nearly identical. Based on the median, the difference in tokens generated per second was less than 1%. This indicates that the gap was entirely concentrated in the “prefill” stage before outputting the first token, rather than in the generation stage.

    3. Where Do the 11.5 Seconds Actually Go?

    To understand the source of this gap, it is necessary to understand the two stages of large language model inference:

    1. Prefill Stage. The model must process the entire input before it can begin outputting the first token. The longer the input, the greater the prefill computation, and the longer the wait.

    2. Decode Stage. The model generates the reply token by token. The speed in this stage is primarily affected by memory bandwidth and scheduling efficiency.

    In the replay of real programming sessions, there is a crucial detail: the history of the multi-turn dialogue is sent to the server with each request. When 16 concurrent sessions are running, the median input for a single request is as high as approximately 89,000 tokens. Assuming the user already pasted source code and error information in previous rounds and only added “move the login button slightly to the right” in this round, the server still needs to process all nearly 90,000 tokens of input.

    If the engine recalculates the prefill for the entire input from scratch for every request, the latency naturally remains high. The optimization approach is already well-established in the industry—Prefix Caching.

    Prefix Caching: Reusing Computed Results

    Multi-turn dialogue requests have a natural property: the beginning of a new round’s input heavily overlaps with the previous round’s input (system prompts and dialogue history are both prefixes). Furthermore, the attention calculation in Transformers is prefix-deterministic—the intermediate states produced by the model for the same prefix are identical.

    Therefore, the engine can save the intermediate computation results (KV cache) of historical prefixes. When a new request arrives, it first calculates the longest common prefix with the cached prefix, directly reuses those results, and only performs incremental prefill on the newly appended content. Taking an 89,000-token input with only a few hundred newly added tokens as an example, the computation volume can drop by over two orders of magnitude.

    1. Pseudo-logic for request processing:
    2. prefix_hit = longest_common_prefix(new_input, cached_prefix)
    3. kv_cache = load(cached_prefix[:prefix_hit])
    4. prefill(new_input[prefix_hit:], kv_cache) # Compute only the incremental part
    5. decode(...) # Start generating the reply

    The core reason the agent-built engine managed to compress P90 latency to half a second was taking prefix caching to the extreme: a high cache hit rate, precise prefix matching, and tight integration between cache scheduling and concurrent request management. In contrast, some mature engines prioritize generality in their design, resulting in cache utilization under complex real-world workloads that is actually lower than highly customized implementations tailored for this specific scenario.

    4. General Insights for Inference Service Optimization

    From this test, several practical principles applicable to all inference services can be distilled:

    • First Token Latency is an independent optimization target. It is a different metric from generation throughput and requires separate modeling and stress testing.
    • Prefix cache hit rate is the core lever. When routing requests, try to schedule requests with the same prefix to the same instance to avoid cross-node cache invalidation; cache eviction strategies should align with the temporal locality of sessions.
    • Evaluate with real workloads. Synthetic benchmarks often use short inputs and simplistic prefix repetition patterns, which fail to expose long-tail issues like cache misses. Only replaying real sessions can yield credible P90 data.
    • Agents possess system-level building capabilities. Under clear constraints and quantifiable goals, agents can complete a closed loop from code generation to performance tuning, providing empirical evidence for “AI building AI infrastructure.”

    When prefill wait times drop from 12 seconds to half a second, the AI interaction experience transforms from “tool invocation” to “conversational collaboration.” For developers, understanding the caching and scheduling mechanisms behind this half-second is the first step toward optimizing the response speed of their own AI applications.