How Inference Engines Cut Time to First Token to Half a Second

    This article explains how an inference engine reduced P90 time to first token (TTFT) from about 12 seconds to 0.48 seconds under 16-way concurrency, without changing generation speed. It covers why TTFT matters, how prefill and prefix caching work, scheduling techniques such as chunked prefill and prioritization, hidden costs like tokenization, and a practical optimization checklist.

    What Users Actually Wait For After Pressing Enter

    Asking an AI coding tool to fix a login error is a familiar workflow for developers: paste the source code, paste the logs, hit Enter, and stare at the dialog waiting for the first character. After one fix, the tests fail with the same red line, so the new logs get pasted back in and the wait begins again. Even a simple bug can take several rounds, and the perceived difference between rounds comes almost entirely from the wait before the model starts speaking.

    A public benchmark offers a clear comparison: with the same four high-end accelerators, the same model, and a replay of 16 concurrent real coding sessions, one AI coding tool’s self-built inference service reduced P90 TTFT from roughly 12 seconds to 0.48 seconds. Once output began, generation speed was nearly identical for both setups (median around 124–125 tokens per second). The key takeaway is that the optimization did not make the model speak faster; it made the model start speaking sooner.

    Define the Metric First

    P90 time to first token (TTFT) is the 90th percentile of the time from request dispatch to the first token emitted, across all requests. P90 is chosen over the average because interaction quality is determined by the worst small group of requests. An average gets diluted by many short requests and hides the real pain of long-context requests.

    Where the Latency Goes: Prefill and Prefix Caching

    A request entering the inference service goes through roughly three stages: queuing, prefill, and sampling the first token. Coding sessions are unusual because the input is extremely long: multi-turn chat history is sent with each request, and the median input in the benchmark reached 89,000 tokens. The user may only add one sentence such as “move the login button a bit to the right,” but the server must face nearly 90,000 tokens of context again.

    If the model has already computed that preceding context, it should not need to recompute it. This is prefix caching: when the same prefix is hit, existing computation results are reused and only new content is processed. Those “computation results” are the key-value cache (KV Cache) in the model’s attention mechanism—the intermediate state left behind when the model reads the preceding text. The model used in the benchmark keeps two such cache records, each serving a different attention computation path, so the cache hit rate directly determines how much work prefill must actually do.

    To ensure hits in practice, three points matter:

    • The prefix must be byte-for-byte stable. Embedding timestamps or random request IDs in the system prompt invalidates the entire cache.
    • Organize session history in an append-only fashion, placing stable content first and volatile content last.
    • Cache capacity is limited, so an eviction strategy (such as least recently used) and a sharded layout are needed to keep hot prefixes from being repeatedly pushed out.

    An illustrative request layout:

    1. [stable prefix] system instructions + tool descriptions + repository conventions
    2. [stable prefix] turn 1 Q&A ... turn N-1 Q&A
    3. [new content] current user input + latest logs

    Scheduling Under High Concurrency: Let Short Interactions Cut In Line

    16-way concurrency means memory and compute are repeatedly partitioned. With first-come, first-served, one long prefill task blocks all the small requests behind it in the queue, and P90 naturally climbs into the teens. General approaches that work include:

    1. Chunked prefill: split long inputs into fixed-size chunks and interleave them with decode steps so a long task does not monopolize the device.
    2. Request priority: interactive requests take precedence over batch offline jobs, with preemption of low-priority requests when necessary.
    3. Continuous batching: dynamically assemble batches so new requests can join a batch that is already decoding, improving throughput without sacrificing latency.
    4. Cache-aware routing: with multiple instances, route requests that hit the same prefix to the same instance to improve local hit rates.

    Pseudocode for priority and preemption:

    1. def schedule(queue, kv_pool):
    2. queue.sort(key=lambda r: (r.priority != INTERACTIVE, r.arrival))
    3. for req in queue:
    4. if kv_pool.free_blocks() < req.blocks_needed:
    5. preempt_lowest_priority_running()
    6. chunk = req.next_chunk(CHUNK_SIZE) # chunked prefill
    7. run_prefill_step(chunk)
    8. if req.prefill_done():
    9. admit_to_decode_batch(req)
    10. yield # give the time slice to the decode batch

    Hidden Costs Worth Noticing

    TTFT is also affected by tokenizer processing, request body parsing, and logging and metrics reporting. An 89,000-token input processed synchronously token by token can spend hundreds of milliseconds on tokenization alone. In practice, tokenization, validation, and cache lookup should be pipelined, and the serialization overhead of large requests should be included in monitoring.

    A Practical Optimization Checklist

    • Metrics: observe P50/P90/P99 TTFT, decode throughput, cache hit rate, and queue time together; none of the four can be missing.
    • Load testing: replay real sessions rather than synthetic short requests, and make sure the input length distribution matches production.
    • Capacity planning: reserve KV cache space for peak concurrency, and prioritize the interactive path when cache is insufficient.
    • Cloud setup: container platforms host inference instances, object storage holds sessions and logs, monitoring and alerting notify in real time when P90 crosses the line, and message queues smooth out peaks and fill valleys.
    • Regression protection: include TTFT in continuous integration gates so prompt changes cannot quietly break the cache.

    Conclusion

    Cutting the wait from 12 seconds to half a second relies not on faster GPUs but on eliminating repeated computation and reordering the queue. For developers, quantifying the TTFT distribution first and then checking prefix stability, chunked scheduling, and priority policies in order usually yields an order-of-magnitude improvement in experience. General practices from Baidu AI Cloud in inference services and observability can also serve as a reference path for similar optimizations.