Reducing Time to First Token from 12 Seconds to Half a Second: A Practical Optimization Guide

    This article breaks down how a 16-concurrent coding-session benchmark cut P90 time to first token from roughly 12 seconds to about 0.48 seconds without faster GPUs or a larger model. It explains what P90 first-token latency measures, why prefill and context growth create the long tail, how byte-stable prefix caching and cache-aware scheduling remove most of the wait, and ends with a reusable implementation checklist.

    1. The Problem: Why the “First Words” Matter More Than Generation Speed

    In AI coding scenarios, a single fix is rarely a one-shot question and answer. It is a multi-turn loop: paste in source code and an error, accept a suggestion, re-run, then paste the new logs back. After each submission, what users actually perceive is not how many tokens the model can emit per second, but the blank stretch between pressing Enter and seeing the first character.

    A public technical evaluation offers a telling comparison. With identical hardware and model conditions, two inference engines replayed the same batch of 16 concurrent real coding sessions. The mature solution’s time to first token reached roughly 12 seconds at P90, while an engine built in-house by an agent under a time limit came in at about 0.48 seconds. Once both started emitting output, median generation speed was nearly identical (about 124 vs. 125 tokens per second).

    The comparison points to an easily overlooked conclusion: generation throughput and time to first token are two different optimization curves. The former determines how long it takes to finish reading; the latter determines whether the user is willing to keep waiting. In interactive scenarios, the latter is the real dividing line for experience.

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

    Sort every request by the time elapsed from dispatch to the model beginning its reply, then take the 90th percentile. That is P90 time to first token. It bundles together queueing, scheduling, prefill, and the first decode step, covering nearly every source of server-side waiting.

    P90 is chosen over the average because interactive experience is decided by the most painful batch of requests. An average gets diluted by a large volume of short requests and hides the fact that long-context requests are repeatedly pushed back in the queue. In practice, it helps to observe three views at once:

    • Median time to first token: reflects the typical experience;
    • P90/P99: reflects where the long tail collapses;
    • Joint distribution of input length and concurrency: pinpoints the source of pressure.

    Illustrative statistics logic can be written as:

    1. # Pseudocode: percentile measurement
    2. latencies = [req.started_at - req.received_at for req in finished]
    3. latencies.sort()
    4. p90 = latencies[int(len(latencies) * 0.9)]

    3. Where the 11.5 Seconds Go: Prefill and Context Bloat

    To understand the optimization headroom, first understand the step a model must complete before it can reply: prefill. The model has to read the entire input once and produce the intermediate computation records that later decoding depends on before it is eligible to emit the first token.

    And coding sessions bloat naturally. Multi-turn conversations drag along historical source code, errors, and several failed attempts. In the evaluation, median input per request reached about 89,000 tokens. Even if the user only typed “move the button a bit to the right” this turn, the server still faces nearly ninety thousand tokens of context.

    That is how the long tail forms: 16 sessions arrive concurrently, each carrying a long history, and who gets scheduled first, who gets split into chunks and fed in batches, and whether the previous turn’s computation records still fit in GPU memory together determine the height of that 90th-percentile curve.

    4. The Half That Gets Eliminated: Using Prefix Caching Correctly

    If the beginning of a new request is identical to the previous turn, the prefill result for that shared prefix can be reused directly, and only the new content needs processing. This is prefix caching, and it is the main source of the gap in this comparison.

    One critical prerequisite is often ignored: whether the cache hits depends on the prefix being byte-for-byte stable. The following pattern invalidates the cache entirely:

    1. # Counter-example: timestamp and random ID placed at the front
    2. prompt = f"Current time {now()} session {uuid4()}\n" + history + new_msg

    The correct approach puts volatile content last and stable content first:

    1. # Correct example: stable prefix first, volatile content last
    2. system_block = STABLE_SYSTEM_PROMPT # no timestamp, no random ID
    3. history_block = normalize(history) # normalize whitespace and line breaks
    4. turn_block = f"\n[Current turn input]\n{new_msg}"
    5. payload = system_block + history_block + turn_block

    Three engineering constraints come with this. First, history messages should only be appended to, never rewritten, so the hash of the whole prefix stays unchanged. Second, template rendering must be deterministic, with fixed ordering for floating-point values and set iteration. Third, cache capacity is limited, so an eviction policy is needed to keep the “hot prefix” of long sessions resident.

    5. Intelligent Scheduling: Short Requests Should Not Queue Behind Long Ones

    Even with cache hits, the scheduling policy still shapes the long tail. Common and effective combinations include:

    • Chunked prefill: split oversized inputs into small blocks and interleave them with decode steps, so one long request cannot monopolize compute and other sessions can squeeze in to produce their first token;
    • Priority and fair queues: interactive requests take precedence over batch offline jobs, while each session keeps a minimum progress quota to prevent starvation;
    • Admission control: when queue depth crosses a threshold, reject or degrade quickly instead of letting every request slow down together;
    • Cache-aware routing: with multiple replicas deployed, route later turns of a session to the replica holding its prefix cache.

    A simplified scheduling decision can be expressed as:

    1. def schedule(queue, cache_index, max_prefill_chunk=4096):
    2. # Interactive requests first, and prefer replicas with a cache hit
    3. req = min(queue, key=lambda r: (r.is_batch, -cache_index.hit(r)))
    4. chunk = min(req.remaining_prefill, max_prefill_chunk)
    5. return req, chunk

    6. A Reusable Implementation Checklist

    1. Measure before optimizing: instrument queueing, prefill, and first-step decode separately, so the problem is not attributed to the wrong place.
    2. Stabilize the prefix: render the system prompt and history deterministically, and move volatile fields such as timestamps and request IDs to the end.
    3. Control context size: trim and summarize historical source code, keeping only the fragments relevant to the current turn. This is the most direct way to cut prefill cost.
    4. Enable chunking and interleaving: trade a little single-request peak speed for a smoother long tail using small-block prefill.
    5. Establish a capacity baseline: record P90 curves across different input lengths and concurrency levels as the basis for scaling and rate limiting.
    6. Pair it with observability: set percentile-latency thresholds in your logging service and alerting, and keep headroom for elastic scaling on the container platform side.

    7. Conclusion

    The gap from about 12 seconds to 0.5 seconds did not rely on faster GPUs or a larger model. It came from rethinking the structure of waiting: keep the repeated prefill results, cut long requests into fragments that can be interleaved, and move volatile content out of the prefix. For interactive agents, time to first token is a capability that can be broken down and verified item by item through engineering, not something mysterious.