LLM Inference Time to First Token: From 12 Seconds to 0.5 Seconds
This article examines why fast token generation does not necessarily translate into a fast user-perceived response in interactive coding workflows. It breaks first-token latency into queueing, prefill, decoding, and transport stages; discusses prefix-cache reuse for long sessions; reviews scheduling and memory-management trade-offs; and outlines a validation and implementation sequence for reducing time to first token without compromising correctness. It also discusses a reported replay result of roughly 12 seconds versus 0.48 seconds at the 90th percentile under the stated test conditions, while noting the limits of that result.
1. Why Do Users Still Wait When the Model Generates Quickly?
In intelligent coding workflows, users often interact with a model continuously: first they provide source code, then add an error message, then ask for an implementation adjustment, and finally request a small UI detail change. From the user’s perspective, the new request may be only one sentence. From the inference service’s perspective, however, it may carry a large amount of accumulated context.
Therefore, “how many tokens the model generates per second” is not enough to describe the service experience. A system may generate quickly once output begins, yet still make users wait several seconds or longer before the first output appears.
The original material describes a real coding-session replay. Under the same model, hardware, and concurrency conditions, two implementations showed 90th-percentile first-token latencies of approximately 12 seconds and 0.48 seconds, while median generation speed in the output phase was close.
These results only represent the test conditions described in the material and cannot be directly generalized to other models, workloads, or deployment environments. The material also does not provide enough implementation detail to conclude that the improvement came from one specific optimization. Still, the observed pattern points to an engineering issue worth attention:
A clear improvement in inference experience may not come from a comprehensive increase in model computation speed. It may come from reducing repeated work and waiting before the model starts generating.
For developers, understanding this point is more valuable than simply chasing a particular performance number.
2. Break Down First-Response Latency Before Optimizing
Time to first token usually refers to the time from when a request is sent to when the first output token is received. A token here is the basic unit the model uses to process text; it does not necessarily correspond to a word or a character.
In actual deployments, the measurement boundary must also be defined: whether it is recorded on the client or at the service entry point; whether the network connection is already established; and whether connection establishment and response buffering are included. Data measured under different definitions cannot be compared directly.
From the user side, first-response latency can be approximated as:
First-response latency ≈ network and access time + queueing time + input processing time + context prefill time + first decoding step time + output transmission time.
These stages may partially overlap in a specific system, so this expression is better used as a diagnostic model than as a strict timing formula.
2.1 Queueing: The Request Has Arrived, but Compute Resources Are Not Yet Available
When concurrent requests exceed immediate processing capacity, the service must decide who runs first, how much to process at a time, and whether a new request can join the current batch.
Queueing delay is related not only to concurrency but also to input length, output length, request arrival patterns, and memory pressure. The same average concurrency may correspond to very different tail latency.
2.2 Prefill: The Model Must Process Input Before It Can Continue Generating
The prefill stage processes the input context and establishes the state needed for subsequent generation. Longer inputs usually require more computation, but the actual time also depends on model architecture, execution method, batch size, and cache state.
If every dialogue turn reprocesses the full prior history, the service may incur a computation cost far higher than the new sentence itself, even when the user has added only one sentence.
2.3 Decoding: Output Begins Step by Step
The decoding stage usually generates subsequent tokens step by step. Its computational characteristics differ from prefill, and its resource bottleneck may also differ.
Therefore, when first-response latency is slow but output speed is normal, the first places to check are queueing, prefill, and the cache path, rather than assuming that the generation stage is the problem. At the same time, communication, input processing, and output buffering should not be ignored.
3. The Key Problem in Long Sessions: Which Context Can Stop Being Recomputed?
Suppose a coding session already contains multiple pieces of source code, error messages, and several rounds of fix suggestions. The user then asks only: “Move the login button a little to the right.”
From a business perspective, this is a small change. From a computation perspective, the request may still contain the full history. If the service cannot identify and reuse the stable prefix that has already been computed, it must process a large amount of identical content again.
3.1 The Role and Boundaries of the KV Cache
In common autoregressive attention models, the key-value cache stores intermediate states corresponding to tokens that have already been processed, avoiding recomputation of the full history each time a new token is generated.
But two questions must be distinguished here:
- Reusing historical state within the same generation request;
- Reusing a previously processed common prefix across later requests.
The latter requires the inference service to provide cross-request prefix identification, cache management, and scheduling mechanisms. The fact that a model uses a KV cache does not mean that multi-turn requests naturally avoid recomputation.
3.2 Prefix Reuse Requires Consistent Computation Conditions
Similar-looking text does not necessarily mean the cache can be reused. It is usually necessary to confirm that the token sequence is identical and that conditions affecting computation, such as model version and positional encoding handling, are compatible.
For example, inserting a new system instruction before historical messages changes the positions and input sequence of subsequent content. In that case, the existing cache may not be usable along the same path.
In engineering practice, the following approaches can be used:
- Place stable system instructions and common content in relatively fixed positions;
- Keep message organization and text serialization rules consistent;
- Version model configurations that affect computation;
- Identify reusable prefixes by token sequence rather than comparing only raw strings;
- Design explicit validity checks and invalidation mechanisms for cache state.
The goal of these measures is not to change user semantics in order to improve hit rate, but to reduce unnecessary input variation while keeping semantics unchanged.
3.3 Cache Hit Length Is More Informative Than Hit Count
A request that reuses a small set of common instructions and another request that reuses most of a long session history may differ greatly in the amount of computation saved.
Therefore, in addition to request-level hit rate, teams should observe:
- The number of prefix tokens per hit;
- The ratio of reused tokens to total input tokens;
- The actual prefill time after a hit;
- Cache occupancy and eviction behavior.
Otherwise, a high hit rate may mask the problem that a hit saved little work.
4. Scheduling: Optimize Throughput and Interactive Latency Together
Caching can reduce repeated computation, but it cannot eliminate queueing. When multiple long-input requests arrive at the same time, scheduling policy may still determine how long tail users wait, even if some requests hit the cache.
4.1 Do Not Control Batches by Request Count Alone
Two batches may contain the same number of requests but have completely different computational loads. Dozens of short questions and dozens of long code sessions cannot simply be treated as equivalent tasks.
More reasonable scheduling inputs include input token size, the number of active sequences, expected memory occupancy, and time already spent waiting.
4.2 Chunk Long Inputs to Reduce Sustained Occupancy
Chunked prefill processes long inputs in segments, giving the service an opportunity to schedule other tasks while handling long requests.
It can mitigate blocking of interactive requests by some long inputs, but it is not free: chunking increases scheduling complexity, may introduce additional overhead, and different chunking strategies affect throughput and latency.
Therefore, chunk size and scheduling rules should be validated against real workloads rather than assuming that finer chunks are always better.
4.3 Priority Needs Fairness Mechanisms
Prioritizing short inputs or interactive requests may improve the experience for many users, but without waiting-time compensation, long requests may be starved for a long time.
Production systems should define clear priority rules and combine waiting time, business tier, and resource budget for fairness control. Under overload, rate limiting, timeouts, and cancellation handling are also needed so that requests that no longer have business value do not continue to occupy compute resources.
5. Memory Management Determines Whether Optimization Is Sustainable
Prefix caching consumes GPU memory, while memory must also hold model weights, active request state, and temporary space needed during execution.
Therefore, “retain as much cache as possible” is not a complete strategy. Retaining too much cache can reduce admissible concurrency and may even cause frequent evictions, state movement, or request failures, worsening tail latency.
Cache management should consider three dimensions:
Reuse value. Long prefixes that are frequently accessed again are usually more worth retaining than short prefixes that are rarely reused, but the decision should also consider storage cost and recomputation cost.
Resource budget. Reserve headroom for active requests and temporary computation space, avoiding passive handling after the cache fills resources.
Lifecycle. Release or invalidate corresponding state when a request ends, a user cancels, a session expires, or a model configuration changes.
In addition, caching involves intermediate representations of input data and should still follow tenant isolation, permission boundaries, and data retention rules. Reuse policies for public content and private sessions need to be distinguished; technical shareability alone should not cross business authorization boundaries.
6. How to Verify That “Faster First Response” Is Real
Effective performance optimization must be based on reproducible tests. Testing only a single short question cannot represent real coding sessions.
6.1 Replay Multi-Turn Requests and Preserve Timing Relationships
Real workloads include not only input content but also user thinking intervals, request overlap, cancellation behavior, and context growth.
Tests should cover short inputs, long inputs, multi-turn appends, partial history edits, and cache invalidation, while preserving the real arrival rhythm as much as possible. Otherwise, cache reuse opportunities and queueing pressure may be artificially changed.
6.2 Distinguish Cold Cache from Warm Cache
Cold-cache tests observe performance when historical state is absent; warm-cache tests observe the benefit of reuse in stable sessions.
Reporting only warm-cache results underestimates the cost of new sessions; reporting only cold-cache results may ignore the actual benefit in multi-turn interaction. The two states should be reported separately, with the warm-up method explained.
6.3 Check Latency, Throughput, and Correctness Together
At minimum, record:
- Median, 90th-percentile, and 99th-percentile first-response latency;
- Output token intervals and total request time;
- Total throughput, success rate, and timeout rate;
- Stage times for queueing, prefill, and first-step decoding;
- Cache reuse ratio, memory occupancy, and eviction frequency.
The 90th percentile means that approximately 90% of observed requests do not exceed that value, but results are affected by sample size and statistical method. Small-sample tests should not be used to make stable tail-latency promises.
Correctness must also be verified at the same time. Incorrect prefix matching, state mixing, or defects in invalidation mechanisms may make output look fluent while generating from the wrong context. Performance improvements cannot come at the cost of breaking conversation consistency.
7. Suggested Implementation Order
For an existing inference service, the following order can be used without rewriting the entire engine at the beginning.
First, establish end-to-end tracing to identify which stage consumes most of the time.
Second, build a representative session set and treat input length, concurrency intensity, and cache state as independent test dimensions.
Third, reduce meaningless context variation and verify the correctness and benefit of prefix reuse.
Fourth, adjust batching, chunked prefill, and fairness policies based on existing measurements.
Fifth, complete memory budgeting, cache reclamation, overload control, and failure handling.
Sixth, validate the effect with a small amount of traffic and keep a rollback path, so that gains in an experimental environment do not mask variance in production.
Conclusion
Reducing first-response wait time from seconds to sub-second levels is usually not the result of a single “acceleration switch.” It depends on decomposing the request path, effectively reusing repeated context, and coordinating scheduling, memory, and workload characteristics.
Automated coding agents can help generate implementations, analyze bottlenecks, and iterate on experiments, but generated code is not the same as production validation. Truly reliable inference optimization must answer three questions at the same time: what work is avoided, why correctness is not affected, and within which workload boundaries the optimization remains effective.
For interactive intelligent applications, the optimization focus is not only making the model generate faster, but enabling the service to start responding to users in a timely way with less repeated computation and more predictable waiting.
