Cutting First-Token Latency from 12 Seconds to 0.5 Seconds in an LLM Inference Engine

    This article explains how to optimize large language model inference for interactive coding workloads, where first-token latency (TTFT) matters more than generation speed. It covers why P90 is the right metric for user-perceived responsiveness, the characteristics of coding-assistant workloads (long contexts and heavy prefix overlap), and the engineering levers that turn repeated prefill computation into cache lookups: prefix caching, cache-aware routing, chunked prefill, priority scheduling, admission control, and memory watermarking. It also outlines the observability signals and the iterative optimization path that took a real workload from a 12-second P90 TTFT down to under half a second.

    1. The Overlooked 11 Seconds: The Real Pain Point of Interactive Coding

    Asking an AI assistant to fix a login error is one of the most common development workflows today. You change some code, rerun the tests, the terminal throws the same red error line again, so you paste the new log back into the chat and press Enter to wait for the next round of troubleshooting suggestions. A single bug often takes three or four rounds of back-and-forth, and every round includes a stretch of dead waiting.

    In interactive scenarios, the length of this wait affects perceived experience even more than generation speed. The reason: during the generation phase, users can watch text scroll continuously, which psychologically feels like progress. Before the first token arrives, the interface is completely static, so users tend to switch away to skim their code; by the time they look back, the conversation has moved on and their context is broken.

    A public preprint benchmark quantified this gap: replaying real coding sessions on 4 high-end accelerators with the same model and 16-way concurrent sessions, the P90 first-token latency of a mature open-source inference engine was about 12.03 seconds, while an inference engine built in-house within 12 hours by a certain AI coding tool reached only 0.478 seconds. Once output begins, the median generation speed of both is nearly identical (about 124.2 tokens/s vs. 125.0 tokens/s). This shows the gap is not about insufficient compute, but about “the scheduling and prefill before the model starts speaking.”

    2. Metric Definition: Why P90 Rather Than the Average

    The calculation of P90 first-token latency is straightforward: sort the wait times from request emission to the model’s first token across all requests, then take the 90th percentile.

    1. samples = sorted(ttft_list) # unit: seconds
    2. p90 = samples[int(0.9 * len(samples))]
    3. # Meaning: 90% of requests start receiving a reply within this time

    P90 is preferred over the average because the interactive experience is determined by “the slowest batch of requests.” Averages are dragged down by many short requests, which masks the queueing tail. P90 directly corresponds to the frustrating experience of “1 in every 10 operations stalls long enough that you switch windows.” For capacity planning, P90 is also closer to the real SLA than the average.

    3. Workload Profile: Long Contexts + High Prefix Overlap

    The input distribution of these scenarios differs greatly from traditional online Q&A:

    • Extremely long contexts. In the replayed sessions, the median per-request input is about 89,000 tokens, because source code, errors, and previously attempted fixes from earlier turns are all resent.
    • Highly overlapping prefixes. A new turn often appends only one sentence at the end, such as “move the login button a little to the right,” while the preceding tens of thousands of tokens remain completely unchanged.
    • Sustained but moderate concurrency. With 16 concurrent requests, the trade-offs between memory and scheduling strategy are more sensitive than in high-throughput scenarios.

    The model must “read” the input before it can reply—this step is called prefill. The compute cost of prefill grows roughly linearly with input length, so the repeated computation over 90,000 tokens is the primary source of the 12-second latency.

    4. Prefix Caching: Turning Repeated Compute into Table Lookups

    If the beginning of a new request matches the previous one, the engine can reuse the intermediate results already computed for that prefix and only process the new portion—this is prefix caching. The “computed results” are the computation records left behind when the model reads the context; a common practice is to keep two copies: the key-value cache needed by attention for the current generation, and a representation record that can be retrieved for later reuse.

    For caching to actually hit, three engineering points matter:

    1. Prefixes must be byte-for-byte stable. Embedding timestamps or random request IDs into the system prompt invalidates the entire cache.
    2. Eviction policy must be reuse-aware. For conversational workloads, prioritize retaining cache blocks of “recently active sessions” rather than plain LRU.
    3. Routing must be cache-aware. In multi-replica deployments, subsequent requests in the same session should be routed back to the replica that holds its cached prefix.
    1. def route(session_id, text):
    2. # Cache-aware routing: prefer the replica that already holds this session's prefix
    3. replica = cache_index.lookup(session_id)
    4. if replica and replica.has_prefix(text):
    5. return replica
    6. replica = pick_least_loaded()
    7. replica.warm_prefix(session_id, text) # Warm asynchronously to avoid a second miss
    8. return replica

    5. Smart Scheduling: Hiding Queues inside Batches

    Beyond cache hits, the scheduler determines tail latency:

    • Chunked prefill. Split long inputs into chunks and mix them into batches with decode requests, so a single 90,000-token request doesn’t monopolize the entire card and block every other request in the queue.
    • Priority differentiation. Mark interactive requests as high priority and dequeue short outputs first; offline batch jobs fill idle compute at lower priority.
    • Admission control. When queue depth exceeds a threshold, return quickly or degrade gracefully instead of letting all requests time out together.
    • Memory watermark management. Reserve elastic space for cache blocks, dynamically balancing between “more cache” and “more concurrency.”

    Example configuration:

    1. scheduler:
    2. chunked_prefill: 2048 # Prefill chunk size
    3. max_batch_tokens: 32768
    4. priority: interactive_first
    5. prefix_cache: enabled
    6. cache_affinity_routing: true
    7. queue_timeout_ms: 800 # Degrade on timeout to protect P90

    6. Observability and Continuous Tuning

    Optimizing first-token latency must be measurable. At minimum, collect: queue wait time, prefill duration, cache hit rate, in-batch decode share, and P50/P90/P99 first-token latency. Centralize structured instrumentation in a logging service, set alerting thresholds on P90, use the container platform for elastic replicas and canary releases, and archive session samples to object storage for offline replay. Cache hit rate is the single most important metric to watch: as soon as it drops, P90 usually deteriorates in tandem.

    7. Conclusion

    The gap between 12 seconds and 0.5 seconds is not fundamentally a hardware gap; it is the difference between “turning repeated long-context computation into cache lookups” and “having the scheduler protect tail requests.” For engineering teams, the reusable methodology is: first define the experience target using P90 rather than the average, then characterize the workload’s prefix-overlap profile, and finally implement prefix caching, cache-aware routing, chunked prefill, and priority scheduling in sequence. Built on top of general-purpose container and monitoring capabilities of platforms such as Baidu AI Cloud, this path can be applied directly to your own inference services, compressing users’ dead waiting time to nearly imperceptible levels.