From 12 Seconds to Half a Second: Inside Inference Engine TTFT Optimization

    A recent preprint describes how an inference engine written by an AI agent reduced P90 time-to-first-token (TTFT) from about 12 seconds to 0.48 seconds in real coding sessions, while matching an established engine's generation speed. This article breaks down how the experiment was designed and what the results show, explains why the perceived "slowness" of an AI assistant comes mostly from the prefill stage rather than from token generation, and walks through the core technique behind the improvement—prefix caching—along with the broader engineering toolkit used to compress tail latency.

    A Wait That Happens Every Day

    Start with a scene almost every developer knows.

    You are using an AI assistant to debug an error in a login feature. You paste in the source code, drop in the logs, copy the error message, and the AI offers some troubleshooting suggestions. You apply the changes and run it again—the terminal is still red, and it is the same error. So you paste the new logs into the chat box and press Enter. Then you wait. You wait for the first character of the AI’s reply.

    A single round of debugging often goes back and forth several times like this. And each round of waiting quietly drains your focus and patience. So there is a question worth asking: Between the moment you press Enter and the moment the AI types out its first character, what exactly is happening? Why is it sometimes lightning fast and other times a dead wait of ten seconds or more?

    Recently, a preprint submitted by an academic team together with an industry research group offered a quantified answer through a set of controlled experiments: in real coding sessions, an inference engine written entirely by an AI agent compressed the “time to first token” from around 12 seconds to under half a second. The technology behind this is worth a careful breakdown for every engineer working on AI applications.

    How the Experiment Was Designed

    The core proposition this research explores is “can agents build agents.” One part of the design was particularly clever: the research team gave an AI agent a base server codebase, four high-performance accelerator cards, and 12 hours, and asked it to write a complete inference engine from scratch.

    The engine had to take on the typical responsibilities of a production-grade inference service—receiving user requests, scheduling the accelerators to run the model, and streaming the generated replies back to the client. Once it was done, the researchers did not stop at “reading the code.” Instead, they put it to the test in real coding sessions to check its practical performance.

    The evaluation methodology was equally rigorous:

    • Run two engines under identical hardware and the same model, each using four accelerator cards.
    • Replay the same set of 16 concurrent real coding sessions.
    • Measure P90 time-to-first-token (P90 TTFT).

    Here, “P90” means ranking the wait time “from when a request is sent to when the model starts replying” across all requests and taking the value at the 90th percentile—meaning 90% of requests begin replying within that time. Compared with an average, P90 better reflects the real experience users have “in the worst-case 10% of situations,” making it a tail-latency metric that stays closer to actual user experience.

    Results: Half Surprising, Half Expected

    The data comes in two parts, and the contrast is interesting.

    First, time to first token. Under the same load, a mature industry inference engine had a P90 TTFT of about 12 seconds; the AI-built engine came in at just 0.48 seconds. In other words, while you wait those 12 seconds, you may have already switched back to your editor and scrolled several lines through the code following the error; but in half a second, you have just finished pressing Enter and the first character of the AI’s reply is already showing in the box.

    Second, the generation speed once a reply has begun. The two are nearly on par—by the median, the AI-built engine generates about 124 tokens per second, and the mature engine about 125.

    This contrast points right at the heart of the problem: “freezing up” and “generating slowly” are two different things. The bulk of the pain users feel as “the AI is so slow” comes from “the silence before it starts talking,” not from “the speed at which it spits out characters after it starts.” Since the two engines are evenly matched in the generation stage, that extra eleven-and-a-half seconds must come from somewhere “before it opens its mouth.”

    Where the Delay Happens Before the Model Speaks

    To understand where those eleven-and-a-half seconds go, you first need to understand the two stages of large-model inference.

    The first stage is called prefill. The model must first “read in” all of your input before it can begin generating a reply. This step processes every token in the input in parallel—it is compute-intensive and demanding on hardware.

    The second stage is called decode. The model generates new tokens one by one, spitting them out one after another. This is memory-bandwidth-intensive.

    The key factor is how long the input is. In the coding sessions the paper replayed, the chat history from the previous few rounds is sent to the server along with the new question. With 16 sessions running at once, the median single input reached as high as about 89,000 tokens.

    Imagine this: you have already pasted in source code, error messages, and tried several fixes in earlier rounds, and this round you only added one line—“move the login button a bit to the right.” To a human, that is a one-sentence task. But to the model, it may have to recompute that history of nearly 90,000 tokens from scratch—and that is the root of slow prefill, as well as the culprit behind spiking first-token latency.

    The Key to Saving Time: Prefix Caching

    So how did the AI-built engine get around this hurdle? The core weapon is prefix caching.

    Look back at the earlier example: this round’s new request actually highly overlaps with the previous round—the prior conversation history is unchanged to the last character, with only the new line “move the login button a bit to the right” appended at the end.

    So here is the question: if the beginning is completely identical, why recompute it all again?

    This calls for some background: when the model processes input, it computes a set of intermediate states for each token, usually called the KV Cache (key-value cache). This cache is the basis for the subsequent generation. If the new request’s prefix is exactly the same as before, the engine can simply pull out the previously computed KV Cache and reuse it, processing only the small portion that was newly appended.

    Here is a simple pseudocode sketch of the logic:

    1. def handle_request(new_messages, history_cache):
    2. # Try to find the longest prefix in the cache that matches the current request
    3. cached_len, kv_cache = history_cache.match_prefix(new_messages)
    4. # Only run prefill on the newly added part; reuse the matched prefix directly
    5. new_part = new_messages[cached_len:]
    6. if new_part:
    7. new_kv = prefill(new_part)
    8. kv_cache = kv_cache.concat(new_kv)
    9. # The more the cache hits, the fewer tokens need computing, and the faster the first token returns
    10. history_cache.store(new_messages, kv_cache)
    11. # The subsequent decode stage generates tokens one by one as usual
    12. return decode(kv_cache)

    On a cache hit, of those 89,000 tokens, perhaps only the small newly added segment actually needs to be computed, while everything else is “fetched from a lookup table.” The prefill compute load drops off a cliff, and first-token latency naturally falls from “ten-plus seconds” to the “half a second” level.

    This also explains why generation speed is unaffected: prefix caching only optimizes the prefill stage “before the model opens its mouth,” and does not intervene in the decode stage “after it starts”—the two are inherently independent steps.

    The Complete Toolkit in Engineering Practice

    Prefix caching is the most critical piece of this optimization, but a mature high-performance inference system is usually a combination of several techniques. Here are directions widely recognized in the industry that can be adopted as needed:

    • Prefix caching with tiered storage: Manage the KV Cache in a tiered fashion across GPU memory, system memory, and disk, keeping hot prefixes on the fastest storage medium as much as possible to balance hit rate and capacity.

    • Chunked prefill: Break a very long prefill into smaller chunks and interleave them with decode tasks in scheduling. This keeps a single long request from monopolizing the accelerator and blocking other requests from streaming their tokens, significantly improving tail latency under concurrency.

    • Continuous batching: Instead of waiting for a whole batch to finish before wrapping up, schedule on the fly and assemble batches dynamically, greatly improving GPU utilization and throughput.

    • First-token-priority scheduling: In the request queue, give priority to requests that can “produce their first character as soon as possible,” optimizing directly for the TTFT experience metric.

    • Request routing and affinity: Route sessions carrying the same long prefix to the same instance as much as possible to raise the cache hit rate.

    It is worth noting that tail-latency metrics like P90 matter precisely because they are extremely sensitive to “the slowest batch of requests.” The chunked scheduling, priority queues, and similar techniques above are, in essence, all about “smoothing out the peaks and filling the valleys” to push down the long tail.

    Summary: Optimizing the Wait, Improving the Experience

    Back to the original scene. What this research really sets out to show is: measuring whether an AI application is “fast” cannot rely only on throughput or average generation speed; it must also look at experience metrics like time-to-first-token.

    • The “freezing up” users perceive directly comes mainly from the prefill stage, especially the overhead from repeatedly computing long context;
    • Prefix caching, by reusing the KV Cache of identical prefixes, turns “re-reading 90,000 tokens” into “a cache hit,” and is the key to compressing TTFT;
    • Chunked prefill, continuous batching, and priority scheduling then work to push down tail latency like P90 under concurrent load.

    For teams building AI applications, the value of this approach goes beyond a single number. Next time you complain that “the AI is slow to respond,” you might first ask: is what is slow the speed at which it spits out characters, or the silence before it opens its mouth—quietly consumed by redundant computation? Once that is clear, the direction for optimization naturally falls into place.