LLM Inference First-Token Latency Optimization: From 12 Seconds to Sub-Second

    This article breaks down why first-token latency matters more than raw throughput in interactive AI coding workflows, and where that latency actually goes. It covers prefix caching, scheduling and batching strategies, KV cache memory management, parallelism, and kernel-level tuning, then outlines a practical optimization order based on measurement first. Readers will learn how to diagnose queuing, prefill, and sampling costs and reduce time-to-first-token without changing model quality.

    1. Start With “Waiting for the First Word”

    Most developers who use AI coding tools know the loop well: paste an error log into the chat, hit Enter, and wait. If the suggestion doesn’t work, paste a new log and wait again. Fixing what looks like a trivial login bug often takes three to five rounds. What really drains energy isn’t editing the code, it’s the fragmented, repeatedly interrupted waiting in between.

    A benchmark study on agent capabilities offers a telling observation. In a constrained offline development environment, a model was given four high-performance accelerators and twelve hours to build an inference service from scratch that could accept requests, schedule GPUs, and return generated results. It was then validated by replaying real coding sessions. The metric for “how long before it starts speaking” was P90 first-token latency: a mature solution came in around twelve seconds, while the model’s self-built engine came in around half a second. Once output began, the median generation rate for both was nearly identical, at over 120 tokens per second.

    The engineering implication is clear: generation throughput determines how long it takes to finish reading, while first-token latency determines whether users are willing to keep waiting. The former is about compute efficiency; the latter is about interaction experience. Their optimization paths are not the same.

    2. Where First-Token Latency Actually Goes

    From the moment a request is sent to the moment the first token comes out, it typically passes through queuing, network and serialization, input preprocessing, prefill, and the first sampling step. Prefill is usually the biggest chunk: the model must read the entire input before it can produce a result for the first output position.

    Input size is the key factor. In multi-turn coding sessions, conversation history, source snippets, and error logs are resent with every turn. In the benchmark, the median single-request input under 16-way concurrency was about 89,000 tokens. In other words, the user only added one line this turn, “move the login button a bit to the right,” but the server has to face nearly 90,000 tokens of context all over again. Without a reuse mechanism, the attention computation for those 90,000 tokens is recomputed every turn, so twelve-second latencies are not surprising.

    3. Prefix Caching: Turning Repeated Computation Into a Lookup

    The core assumption behind prefix caching is that the beginning of multi-turn requests is often identical. The system stores computed intermediate states by token block; when a new request hits the same prefix, it loads them directly and only computes the new tail. The widely accepted definition is that the cache is block-granular, indexed by content hash, and the longer the hit, the greater the benefit.

    Engineering-wise, three things need handling. First, block size trade-offs: blocks that are too small create high metadata overhead, while blocks that are too large waste compute on the uncached tail. Second, eviction policy: GPU memory is limited, so retention must be decided by recency of use and reference counts. Third, hit-rate observability: without metrics for hit rate, hit length, and cache occupancy, optimization is blind tuning.

    Illustrative prefix-matching logic:

    1. def match_prefix(cached_blocks, tokens, block_size=256):
    2. n = min(len(cached_blocks), len(tokens) // block_size)
    3. hit = 0
    4. for i in range(n):
    5. key = hash(tokens[i * block_size:(i + 1) * block_size])
    6. if cached_blocks.get(key) is None:
    7. break
    8. hit += block_size
    9. return hit # returns hit tokens matched; the rest must be re-prefilled

    It must be emphasized that the cache must be content-based and session-isolated. Any cross-user reuse of unvalidated content creates a risk of data leakage between users.

    4. Scheduling and Batching: Don’t Let Queuing Eat the Gains

    Caching solves “compute less”; scheduling solves “queue less.” Common practices include: putting long inputs and short inputs in separate queues to keep long requests from blocking small ones; time-slicing requests already in the decode phase against newly arriving prefill requests to prevent decoding from being starved for long periods; and setting queue limits and timeouts so that requests exceeding them fail fast rather than waiting indefinitely.

    On batching, static batches are easily dragged down by the longest request, while continuous batching backfills immediately when a request completes, significantly raising utilization. But the larger the batch, the worse the per-request queuing and first-token latency, so latency-sensitive scenarios should give first tokens a dedicated priority lane.

    5. GPU Memory, Parallelism, and Kernels

    KV cache usage often exceeds the weights themselves, especially under long contexts. Available techniques include paged memory management to reduce fragmentation, quantizing and compressing the cache, splitting single-layer computation across cards with tensor parallelism, and distributing inter-layer load with pipeline parallelism. In addition, the choice of attention kernel, operator fusion, and graph capture to reduce launch overhead all show up directly in first-token latency. On a platform like Baidu AI Cloud, you can rely on a container platform to host the engine, object storage to distribute model files, and monitoring and alerting services to observe latency percentiles.

    6. A Practical Optimization Order

    1. Instrument first: separately measure queuing, prefill, and first-step sampling time, plus P50/P90/P99.
    2. Then enable prefix caching and watch whether hit length grows with each turn.
    3. Tune scheduling policy and batch parameters, using small-traffic canary comparisons of P90.
    4. Finally, change parallelism topology and quantization, one variable at a time.

    7. Conclusion

    Getting from twelve seconds to half a second doesn’t rely on a single silver bullet. It comes from stacking three things: compute less, wait less, and compute faster. For developers, measuring before optimizing is the only reliable path to avoiding wasted tuning.