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

    This article explains why time to first token (TTFT), not generation speed, shapes the feel of interactive AI coding tools. It breaks the delay into queueing, prefill, and first-packet network overhead, then shows how prefix caching and KV state reuse eliminate repeated reading of long contexts. It also covers the engineering requirements for cache hits, the observability metrics needed to manage latency, a load-testing approach based on replaying real sessions, and how to build a low-latency inference service on Baidu AI Cloud.

    1. The Overlooked Wait: TTFT Shapes the Interactive Experience

    Asking an AI coding tool to fix a login error is a daily scenario for developers. You change the code, rerun the tests, and the terminal throws the same red line again, so you paste the new logs back into the chat and press Enter to wait for the next suggestion. A single bug often takes several rounds, and the experience in each round is decided not by generation speed but by “when does the first word appear.”

    The industry usually measures this with P90 time to first token (TTFT): sort the waiting time from request dispatch to the model’s first output across a batch of requests, and take the 90th percentile. It expresses that “90% of requests start replying within that time,” and reflects the long-tail experience better than an average. In a public technical benchmark, with the same 16 concurrent real coding sessions, the same 4 accelerator cards, and the same model, one self-developed inference engine had a P90 TTFT of about 0.48 seconds, while a mature open-source solution was about 12 seconds; once generation began, both had a median throughput of more than 120 tokens per second, nearly identical.

    The conclusion is clear: the gap is not in “how fast it writes” but in “what it does before it opens its mouth.”

    2. Deconstructing the 12 Seconds: Where TTFT Actually Goes

    TTFT consists mainly of three parts: queueing, prefill, and sampling plus the first-packet network round trip.

    • Queueing: whether a request can immediately get GPU memory and compute resources after arrival. Under high concurrency, waiting amplifies the long tail quickly.
    • Prefill: the model must read the entire input before producing the first token. The computation grows roughly linearly with input length.
    • First-packet path: tokenization, request packaging, cross-network transmission, and streaming return; jitter on any hop counts toward P90.

    In coding sessions, the first few rounds of source code, errors, and patches are sent back together, and the median single input can reach 89,000 tokens. That means the user only adds one line this round, “move the login button a bit to the right,” but the server has to read nearly 90,000 tokens again. Without a reuse mechanism, those 11.5 seconds are entirely consumed by repeated reading.

    3. The Key Mechanism: Prefix Caching and KV State Reuse

    After reading the preceding context, the model leaves behind computation records, i.e., the KV cache. Newer models in the industry usually keep two states: one carries the preceding information for backtracking, and one is used for compressed long-range memory. The value of prefix caching is that when the beginning of a new request matches the previous round, the already-computed results are reused directly, and only the new segment is processed.

    1. Round N input = [system prompt + historical source code + historical errors + new content this round]
    2. Prefix hit portion: can skip recomputation
    3. Only the new portion: actually needs to enter prefill

    To make the cache actually hit in engineering, three points matter:

    1. Prefix stability: put the system prompt, tool definitions, and fixed context at the front, and variable content at the back, to avoid “one small change invalidating the whole segment.”
    2. Cache capacity and eviction: GPU memory is limited, so retention and eviction should be based on session affinity to avoid hot sessions being repeatedly pushed out.
    3. Batching strategy: mixing long-input requests with short ones drags each other down; it is better to bucket by length and set admission and timeouts.

    Illustrative scheduling pseudocode:

    1. def schedule(requests, cache, max_batch_tokens):
    2. # 1) Compute the prefix hit length; the hit portion is not prefilled again
    3. for r in requests:
    4. r.hit = cache.match_prefix(r.prompt)
    5. r.remaining = r.prompt[r.hit:]
    6. # 2) Bucket by length to avoid long requests blocking short ones
    7. buckets = group_by_length(requests)
    8. batch = []
    9. for r in sort_by_arrival(buckets):
    10. if used_tokens(batch) + len(r.remaining) > max_batch_tokens:
    11. flush(batch); batch = []
    12. batch.append(r)
    13. flush(batch)

    4. Observability: No Metrics, No Optimization

    To turn latency from “gut feeling” into something manageable, you need at least four metrics: queue time, prefill time, TTFT distribution (P50/P90/P99), and cache hit rate. With logging services and monitoring alerts, instrumenting the stage timing of each request is what lets you locate whether the bottleneck is queueing, insufficient GPU memory, or prefix invalidation.

    Recommended minimal instrumentation fields:

    1. {"req_id":"r-1","queue_ms":8,"prefill_ms":420,"hit_tokens":87000,"new_tokens":36,"ttft_ms":478}

    5. Implementation on Baidu AI Cloud: Building a Low-Latency Inference Service with General Capabilities

    • The container platform hosts the inference runtime and scales elastically by session affinity to ease the queueing long tail.
    • Object storage holds session context and prompt templates to keep prefixes stable and versionable.
    • A message queue handles request prioritization and peak shaving, isolating interactive short requests from batch jobs.
    • Logging services and monitoring alerts connect to a stage-timing dashboard, forming a “load test, locate, tune” loop.

    6. Load-Testing Method: Replay Real Sessions Instead of Toy Data

    The benchmark is convincing because it replays real coding sessions with fixed concurrency and input distribution. In practice, fix 16 concurrent connections and a median input of 89,000 tokens, record the P90 TTFT with and without prefix caching, then gradually increase concurrency and observe the inflection point. If enabling the cache drops P90 by an order of magnitude while generation throughput stays basically unchanged, the optimization target is correct.

    7. Conclusion

    TTFT is not magic; it is the combined result of queueing, prefill, and cache hits. Put fixed prefixes first, reuse long- and short-term KV states, and instrument stage timing, and you can turn “waiting 12 seconds” into “text in half a second” on the same hardware. This approach does not depend on any particular product; any team can reproduce and iterate on it on their own inference stack.