Optimizing LLM Inference Time to First Token: Reducing TTFT from 12 Seconds to 0.5 Seconds
Time to first token (TTFT) often has a greater impact on perceived responsiveness than total inference latency in interactive LLM applications. This article explains how TTFT is composed of queueing, graph execution preparation, KV-cache allocation, prefill computation, and first-token transmission; reviews graph compilation and operator fusion, paged KV cache and preallocation, the limits of speculative decoding for TTFT, scheduling separation, and streaming output; and provides a stage-by-stage measurement approach plus autoscaling tradeoffs. It also cautions that the reported reduction from about 12 seconds to 0.5 seconds, with an approximately 96% improvement in experience, comes from a single scenario whose full test conditions were not provided.
1. Why TTFT Matters More Than Total Latency for Perceived Experience
Time to first token (TTFT) is the time between a user submitting a request and the model outputting the first token. In interactive applications, this metric determines whether users feel that the system is responding.
Consider real-time coding assistance. A developer pastes an error trace into a terminal, and the AI needs to read the context, locate the problem, and provide suggestions. If the first character appears only after more than ten seconds, the developer often switches back to the editor to investigate independently, and their attention is interrupted. If the first token appears in about half a second, users can start reading and understanding even if the complete answer takes longer. The interaction rhythm feels noticeably different.
People usually tolerate one to two seconds of system response time. Beyond that range, users begin to suspect that the system is stuck and shift attention from the problem itself to the wait. As a result, TTFT directly affects satisfaction in scenarios such as intelligent customer service, real-time translation, and code completion.
2. What Contributes to TTFT
Before reducing TTFT, it is necessary to know where the time is spent. A request typically passes through queueing, graph execution preparation, KV-cache allocation, prefill computation, and first-token transmission before the first token is delivered.
The prefill phase feeds all user input tokens into the model at once, computes key-value vectors for each layer, and writes them into the KV cache. The computation in this phase has two parts. The attention part grows approximately quadratically with sequence length because each token computes attention scores with every other token. The feed-forward network and linear projection parts grow roughly linearly with the number of tokens. Therefore, total prefill computation cannot be estimated simply as a linear function. The longer the input, the more likely the attention part becomes the main burden.
2.1 Graph Execution and Scheduling Overhead
Inference frameworks often compile models into computation graphs. For models with fixed shapes, the graph can be compiled ahead of deployment and only executed at runtime. In this case, per-request scheduling overhead is small.
The problem appears with dynamic shapes. When input length differs on every request, the framework may need to re-determine tensor shapes, re-plan memory, and regenerate the execution plan at runtime. These steps add preparation time to each request. In workloads where input length changes frequently, this overhead cannot be ignored.
2.2 Memory Allocation
Transformer inference relies on the KV cache to store key-value vectors for historical tokens. If the system allocates KV cache only after prefill completes, the allocation action is serialized before computation and directly delays first-token output. If the system reserves memory for the maximum possible length in one go for safety, it wastes a large amount of memory and reduces the number of requests that can be processed concurrently.
KV caches for large models often occupy tens of GB of memory. Memory fragmentation management and cross-device memory copies also introduce additional waiting.
2.3 Queueing and Scheduling
Inference services usually process multiple requests at the same time. If the scheduler executes requests in first-come, first-served order, a very long input request can occupy compute resources, and shorter requests behind it can only wait. This blocking directly raises the TTFT of subsequent requests.
Continuous batching can improve throughput, but when prefill and decode are scheduled together, their resource needs differ. Prefill is more compute-intensive, while decode is more memory-bandwidth-intensive. Without distinguishing between them, the prefill of a new request may not receive compute resources for a long time.
2.4 The Computation Itself
Model size and input length determine the baseline prefill computation. Without any optimization, a coding context of several thousand tokens may require a considerable number of floating-point operations. This part of the time is determined by the model and hardware. Scheduling and graph optimization can reduce other overheads but cannot eliminate this computation.
3. Optimization Methods and Their Boundaries
The following four categories target different parts of the pipeline. Before choosing among them, measure first to confirm where the bottleneck is.
3.1 Graph Compilation and Operator Fusion
Operator fusion combines multiple fine-grained operators, such as matrix multiplication, normalization, and activation functions, into a larger kernel. After fusion, the number of kernel launches decreases, intermediate results do not need to be repeatedly written back to memory, and CPU-side scheduling pressure is reduced.
For dynamic shapes, a common approach is to compile when a shape is first encountered and cache the compiled artifact. Subsequent requests with the same or similar shapes can reuse the cache directly.
Applicability boundaries:
- Fusion effectiveness depends on the inference framework version and operator library support. After upgrading the framework, it must be validated again.
- Compiled artifacts are related to GPU architecture. Changing the GPU model may require recompilation.
- The hit rate of dynamic-shape caching depends on the input-length distribution. If input lengths are highly dispersed, the cache hit rate decreases, and compilation overhead remains.
3.2 Paged KV Cache and Preallocation
Paged KV cache borrows the idea of virtual memory from operating systems. The cache is divided into fixed-size blocks, and logical sequences are mapped to physical blocks through a page table. The system allocates blocks on demand, avoiding memory reservation for maximum length and reducing fragmentation caused by large contiguous memory allocations.
Preallocation means starting to prepare KV-cache space when a request enters the queue, overlapping memory allocation with queue waiting. The system can also adjust reservation policies based on the historical request-length distribution to balance memory utilization and allocation speed.
Cross-request reuse means maintaining a memory block pool. After a request finishes, released blocks return to the pool for new requests, reducing the number of times memory is requested from the GPU driver. In workloads with many long sessions, this approach can significantly reduce allocation overhead. The exact benefit depends on session length and concurrency and must be measured under your own workload.
Applicability boundaries:
- Paged KV cache requires support from the inference framework at a low level. Implementing it independently is costly.
- If preallocation reserves too much, it takes memory away from other requests and reduces concurrency.
- Writing KV cache to disk and reading it back introduces additional I/O latency and actually increases first-token time. This is not a TTFT optimization method.
3.3 Speculative Decoding: Mainly Accelerates the Decode Phase
Speculative decoding uses a lightweight draft model to generate several candidate tokens first, and then the target large model verifies them in one pass. Tokens that pass verification can all be accepted in a single forward computation, reducing the number of serialized inference steps in the target model.
It is important to note that speculative decoding mainly accelerates the decode phase, which is the process of generating subsequent tokens one by one. The first token is produced in the prefill phase, so speculative decoding provides no direct benefit for TTFT. Some approaches attempt to pre-generate a response before the user finishes input, but this is an application-level prediction or caching strategy that depends on the business scenario and hit rate. It is not a standard optimization method in inference engines and should not be treated as a general-purpose technique.
The effect of speculative decoding depends on the distribution consistency between the draft model and the target model. Distillation or sharing some parameters can improve the acceptance rate. The acceptance rate is closely related to task type and model combination. Numbers from papers or blogs can only serve as references and must be tested on your own models and data.
Applicability boundaries:
- An additional draft model must be maintained, increasing memory usage and deployment complexity.
- When the acceptance rate is low, verification overhead may offset the benefit.
- The improvement in TTFT is limited. If slow first-token generation is the main problem, prefill-related stages should be addressed first.
3.4 Scheduling Separation and Streaming Output
At the scheduling level, prefill and decode can be managed separately. Prefill requests receive priority access to compute resources, ensuring that first-token computation for new requests can start promptly. The decode phase then proceeds in batches using the remaining resources.
Streaming output means pushing the first token to the client immediately after the model generates it, rather than waiting for the complete response. With protocols such as Server-Sent Events (SSE), the user-perceived first-token time approaches the network round-trip time. Streaming output does not reduce model computation, but it lets users see content earlier, and the improvement in interactive experience is often significant.
Applicability boundaries:
- If priority scheduling is configured improperly, low-priority requests may be unable to obtain resources for a long time, causing starvation. A maximum wait time or aging mechanism is needed.
- Streaming output requires the client to handle incremental content, and both the frontend and intermediate gateways must support long connections.
4. How to Measure: Break TTFT Down First
Looking at only a single total latency number makes it impossible to determine where optimization should start. It is better to break TTFT into several stages and collect metrics separately.
| Stage | Metric of Interest | Collection Method |
|---|---|---|
| Queueing | Wait time from entering the queue to being scheduled | Timestamps at scheduler entry and exit |
| Graph compilation | Compilation or graph preparation time under dynamic shapes, and cache hit rate | Framework compilation logs or custom timing |
| KV allocation | Memory allocation time and number of allocation failures | Instrumentation on memory allocation APIs |
| Prefill computation | Relationship between computation time and input length | GPU performance counters or framework profiler |
| First-token transmission | Time from generation to client receipt | Record separately on client and server |
When analyzing statistics, use percentiles such as P50, P95, and P99 rather than only the average. Averages mask slow long-tail requests. Also record input length, output length, concurrency, model version, and hardware configuration; otherwise, the data cannot be reproduced or compared with other systems.
5. Elastic Scaling and Cost Tradeoffs
When deployed on the cloud, the number of inference instances can be adjusted dynamically based on request volume. Scale up during peak periods and scale down during off-peak periods to protect experience while controlling cost.
However, elastic scaling has several clear risks. First, new instances need to load models and warm up at startup, and TTFT during cold start can be very high. Second, scaling too frequently causes instability: requests migrate back and forth between instances, which can slow responses. Third, when combined with priority queues, if high-priority requests keep arriving, low-priority requests may go unserved for a long time.
In practice, set a warm-up period for scale-up, a cooldown window for scale-down, and maximum wait times for requests at different priorities.
6. Notes on the Data and Future Directions
The reduction from about 12 seconds to 0.5 seconds, and the approximately 96% improvement in experience mentioned in this article, come from a single scenario. The original material did not provide complete test conditions, including model size, input and output lengths, hardware configuration, concurrency, cache state, and statistical methodology. Readers should not treat this number as an expectation for their own systems.
A more reliable approach is to first collect stage-by-stage data from your own system using the method in Section 4, identify the stage with the largest share, then choose the corresponding optimization method and compare before and after under the same conditions.
Looking ahead, several directions are worth watching. In model architecture, methods such as linear attention can reduce the computational complexity of the attention part, but they introduce tradeoffs in accuracy or capability that must be evaluated. Co-design of inference engines and hardware may also create new room for improvement in memory bandwidth and compute-unit utilization. Whichever direction is adopted, the composition of TTFT should be understood first before deciding where to invest.
