Cutting Time to First Token from 12 Seconds to 0.5 Seconds

    This article examines what Time to First Token (TTFT) measures and why P90 latency matters for interactive coding workloads. Using a real-world comparison under identical hardware, model, and concurrency, it shows how an agent-built inference engine reduced TTFT from roughly 12 seconds to under 0.5 seconds while generation speed stayed nearly unchanged. It walks through the full request path, then covers three core optimizations—prefix caching and KV state reuse, scheduling strategy, and memory hierarchy management—and closes with a practical guide to reproducing and guarding these gains in your own service.

    1. The Overlooked Wait Before the First Word

    You ask an AI coding tool to help debug a login error. You apply the suggested change, rerun the tests, and the terminal throws the same red line again. You paste the new logs back into the chat, hit Enter, and start waiting.

    Fixing a bug usually takes several rounds of back-and-forth, and the experience of each round is decided almost entirely by one number: how long you wait between pressing Enter and seeing the first character appear in the chat.

    A comparison test based on real coding sessions produced a striking result. Under identical hardware, the same model, and the same concurrency pressure, a mature open-source inference solution had a time to first token of about 12 seconds, while an inference engine written and tuned by an AI agent pushed that number below 0.5 seconds. Even more notable, once output began, the two ran at nearly the same generation speed, with medians of roughly 124 and 125 tokens per second respectively.

    This means the optimization did not make the model “speak faster.” It compressed the blank stretch before the model opened its mouth.

    2. Metric Definition: What P90 Time to First Token Actually Measures

    To understand this optimization, start by defining the metric clearly.

    Time to First Token (TTFT) is the time from when a single request is sent to when the model produces its first token. In engineering practice, people usually look at P90 rather than the average: sort all request wait times and take the 90th percentile. It answers the question—90% of requests can begin replying within this time.

    P90 is chosen over the mean because interactive coding workloads have an extremely pronounced long tail. The average is dragged down by a large number of short requests, hiding the 10% of users who are “stuck”—and those 10% are exactly the people whose attention drifts away and who start to suspect the tool has died. For interactive experience, the long tail is the real experience.

    3. Where the Time Goes: The Full Path of a Request

    Before it opens its mouth, a single inference request passes through several stages:

    1. Admission and queuing: the request reaches the gateway and enters a waiting queue;
    2. Prefill: the model reads the entire input in parallel and generates the first token;
    3. Sampling and first-packet return: the first token is determined and streamed back.

    In real coding sessions, the cost of the second stage is significantly amplified. The reason is extremely long context: source code, error messages, and patches from previous rounds are all resent together, and the median single input in testing reached about 89,000 tokens. Yet in this round the user may have said only one thing: “move the button a little to the right.”

    So the question becomes: for one incremental instruction, should the server read all 89,000 tokens again?

    4. Core Optimization One: Prefix Caching and KV State Reuse

    The product of prefill is the KV cache—the computation record the model leaves behind after reading each segment of prior context. If a new request’s prefix is exactly identical to the previous round, this computation can be reused directly, and only the new content needs to be processed. The model in this test maintains two states: one stores prior-context information for retrospective retrieval, and the other stores the key-value pairs needed for generation.

    The prerequisite for reuse is that the prefix matches strictly byte for byte, so there is an iron rule in engineering: put stable content first and volatile content last.

    1. [System prompt][Tool definitions][Fixed knowledge snippets] ← Stable prefix, cache hit
    2. [Conversation history][New instruction this round] ← Incremental part, only recompute here

    The counter-example is equally common: inserting a timestamp or a random request ID at the very front of the request invalidates the entire prefix cache.

    5. Core Optimization Two: Scheduling Strategy Determines the Long Tail

    With 16 concurrent sessions, if the scheduler only looks at “first come, first served,” one long-input request will block all the short requests behind it, and P90 shoots up quickly. Common improvement directions include:

    • Chunked prefill: split long inputs into small chunks and interleave them with decoding steps, avoiding a long request monopolizing the device;
    • Priority and fairness: reserve quota for interactive short requests to prevent them from being starved by batch jobs;
    • Continuous batching: dynamically batch at the request level, forming batches separately for the input and output phases;
    • Admission control: fail fast or degrade when the queue exceeds a threshold, rather than waiting indefinitely.

    A schematic scheduling loop:

    1. while serving:
    2. batch = scheduler.form_batch(max_tokens=BUDGET)
    3. if batch.has_prefill():
    4. batch = chunk_prefill(batch, chunk_size=2048)
    5. step(batch) # One forward pass, produces several tokens
    6. scheduler.update(batch)

    The key point is this: the scheduling goal is not to maximize throughput, but to flatten tail latency under an acceptable throughput constraint.

    6. Core Optimization Three: GPU Memory and the Memory Hierarchy

    The KV cache occupies GPU memory, and under long context it easily triggers preemption and swapping. Once recomputation happens, time to first token rebounds instantly. Viable approaches include paged cache management to reduce fragmentation, offloading the cache to host memory, and carving out separate resource pools for requests of different lengths to avoid long and short requests interfering with each other.

    7. How to Reproduce These Optimizations in Your Own Service

    1. Measure first: add instrumentation that separates queue time from prefill time, and report P50/P90/P99 for each;
    2. Then locate: if queuing dominates, the problem is scheduling; if prefill dominates, the problem is cache hits and batch strategy;
    3. Then tune: change one variable at a time and validate with a fixed session replay set;
    4. Build guardrails: bring P90 time to first token into release gates and production alerts.

    When deploying in the cloud, you can rely on a container platform to host inference instances, object storage to hold replay datasets, and logging and monitoring/alerting systems to track percentile metrics, forming a closed loop.

    8. Conclusion

    Time to first token is fundamentally a systems engineering problem, not a model capability problem. Prefix caching decides “whether to recompute,” scheduling strategy decides “how long you wait in line,” and GPU memory management decides “whether it gets even slower.” Only when the three stack together do they compress the 12-second long-tail wait into half a second—turning the interaction from “wait—switch away—come back” into a genuinely continuous conversation.