Prefix Caching in LLM Inference: How to Reduce Time to First Token

    This article explains why time to first token (TTFT) is a key latency metric for LLM serving, how the prefill and decode phases differ, and how prefix caching reuses KV cache state to shorten TTFT in multi-turn and long-context workloads. It covers prefix matching, state loading and write-back, differences across model architectures, eviction and session affinity strategies, monitoring metrics, correctness validation, security isolation, and practical implementation guidance.

    1. Why Waiting for the First Token Becomes an Experience Bottleneck

    When using an AI coding assistant or a conversational development tool, fixing a defect often requires multiple rounds of interaction. A developer pastes logs, waits for the model to make a judgment, modifies the code, runs it again, and then submits new error information. In each round, what users care about most is how long it takes after submission before they see the first character of the response.

    This waiting period has a specific term: Time To First Token (TTFT). It refers to the time between the server receiving a request and the model outputting the first token. TTFT directly determines how fast the response feels to the user, while the speed of generating subsequent content mainly affects the experience of reading and waiting for the complete result. The two are related but should be considered separately.

    When evaluating service quality, teams usually look at percentiles rather than averages. For example, P90 TTFT is the value at the 90th percentile after sorting all request latencies in a period from lowest to highest. It means that 90% of requests can start outputting within that time. Averages are easily skewed by a small number of extreme requests. P90 better reflects the real experience of most users and is more suitable as a basis for service-level objectives.

    2. Two Request Processing Phases: Prefill and Decode

    An LLM processes a request in roughly two phases.

    Prefill: The model reads all input at once, including system instructions, conversation history, code files, and the current question, and computes intermediate states for each input token. The computation in this phase is roughly proportional to input length. It can be highly parallelized, but the longer the input, the more time it takes.

    Decode: After reading the input, the model generates output tokens one by one. Each generated token must reference all previous states. This phase is heavily affected by memory bandwidth. Each step takes a relatively short time, but it must be repeated many times.

    TTFT mainly consists of two components: the time a request waits in the queue and the prefill computation time. When the first token appears, decoding has only just begun. Therefore, in most scenarios, the TTFT bottleneck is prefill. When the input is very long, even with sufficient GPU compute, prefill may still take seconds or longer.

    This also explains why first-token latency grows with each round in multi-turn conversations. Each round resubmits the historical content, so the input size becomes larger and the prefill burden becomes heavier.

    3. Basic Principles of Prefix Caching

    The idea behind prefix caching is straightforward: if the beginning of a request is exactly the same as that of a previous request, the computation results for that earlier part can be reused, and only the new part needs to be processed.

    In attention mechanisms, the core product of prefill is the key-value cache (KV cache). It stores the key and value vectors corresponding to each input token in each attention layer. During subsequent generation, the model queries these vectors to understand the context. If the KV cache is saved, the next request with the same prefix does not need to recompute it.

    Implementing prefix caching usually requires three capabilities.

    1. Prefix matching: Determine which cached content has the same prefix as the new request. Common approaches include comparing token sequences segment by segment or using data structures such as radix trees or hash-based blocks.
    2. State loading: After finding the longest matching prefix, load the corresponding cache state into GPU memory as the starting point for the new round of computation.
    3. State write-back: After the current round of computation is complete, store the newly added state in the cache for the next round.

    In pseudocode, the logic looks roughly like this:

    1. function handle_request(tokens):
    2. matched = cache.longest_prefix_match(tokens)
    3. state = cache.load(matched.state_id)
    4. state = prefill(state, tokens[matched.length:])
    5. cache.store(tokens, state)
    6. return decode(state)

    The key point is that the input to prefill contains only the unmatched portion. The more hits there are, the faster prefill becomes.

    4. Why Adding Only One Sentence Can Still Shorten the Wait Significantly

    Consider an example of modifying a web page. In previous rounds, the user has already pasted a large amount of source code and error information. Each new request adds only a few dozen tokens, while the rest is identical to the previous round.

    Suppose the historical context is about 80,000 tokens and the new round adds about 40 tokens. If the prefix is fully matched, prefill only needs to process those 40 tokens, and the computation is only about 0.05% of the full computation. Even if the actual hit rate is not 100%, as long as most of the prefix can be reused, TTFT will drop significantly.

    Note that these example numbers are only used to illustrate the relationship between computation and newly added length. They do not represent measured results from any specific system. Actual benefits depend on model size, hardware configuration, cache capacity, and request similarity.

    5. Cache Differences Across Architectures

    Not all models have the same cache form. The following two categories require separate handling in engineering implementations.

    Token-by-token cache: The KV cache of standard attention structures grows linearly with input length, and each position stores its corresponding state. It supports truncating a prefix of any length, so matching is the most flexible.

    Recurrent state: Some efficient architectures maintain a fixed-size state vector and update it each time a segment of content is read. This state continuously accumulates historical information, but it cannot be truncated to an arbitrary position like a KV cache. To reuse it, checkpoints usually need to be saved at fixed positions, such as block boundaries every certain number of tokens. A request can hit only when it starts exactly from a checkpoint.

    If a model uses both types of state, the cache system must manage them separately and ensure they are aligned at the same position. Otherwise, a situation may occur where the KV cache hits but the recurrent state does not match, leading to incorrect output.

    6. Concurrency and Cache Management Strategies

    Real services usually handle multiple sessions at the same time, and GPU memory is limited, so the cache must make trade-offs.

    Eviction strategy: The most common approach is least recently used (LRU). Prefixes of active sessions are retained first, and caches that have not been accessed for a long time are reclaimed. Weighting can also be added based on factors such as session priority and prefix length.

    Session affinity: If requests from the same session are always routed to the same instance, the cache hit rate will be much higher. Conversely, if requests are randomly distributed, the cache will be scattered and the hit rate will decrease. The scheduling layer needs to balance load balancing and cache locality.

    Block alignment: Caches are usually managed in fixed-size blocks. Smaller blocks allow finer matching but incur higher management overhead; larger blocks are simpler to manage, but the partial block at the end cannot be reused. In practice, the choice should be based on typical input length.

    Capacity planning: The GPU memory occupied by the cache is proportional to prefix length and concurrency. The service needs to reserve enough space and set upper limits to prevent the cache from crowding out model weights and memory needed for computation.

    7. Monitoring Metrics and Validation Methods

    Optimization results need to be quantified. The following metrics are recommended for long-term monitoring.

    Metric Meaning What to Watch
    TTFT P50, P90, P99 Percentiles of time to first token Most users’ experience and the long tail
    Prefix hit rate Share of input tokens served from cache Whether the cache strategy is effective
    Output tokens per second Decode-phase throughput Whether optimization affects generation speed
    Cache usage and eviction count GPU memory usage and reclaim frequency Whether capacity is sufficient

    For validation, it is recommended to replay anonymized real session logs and compare metrics before and after optimization under the same hardware, model, and concurrency. Looking only at a single request or synthetic data can easily lead to overly optimistic conclusions.

    Correctness is equally important. After a cache hit, the output must be consistent with the result of full computation. Teams should write regression tests for cache logic, covering scenarios such as partial prefix hits, full hits, and recomputation after cache eviction, and compare output consistency.

    8. Security and Isolation Requirements

    The cache stores intermediate states of user input, which essentially contain user data. In a multi-tenant environment, the following principles must be followed.

    • Cache keys must include tenant or session isolation identifiers. Prefixes must not be shared across users unless the content is explicitly public and confirmed.
    • Set expiration times for cached data and clean it up promptly after a session ends.
    • Do not record cache content or raw input in logs; record only statistical metrics.
    • Access control and encryption policies should be consistent with other sensitive data in the service.

    9. Implementation Guidance

    When introducing prefix caching in a real project, proceed in the following order.

    1. First collect input lengths and prefix repetition rates from real requests to estimate the potential benefit. In scenarios with low repetition rates, the value of caching is limited.
    2. Define service objectives, such as a P90 TTFT threshold, and use them as acceptance criteria.
    3. Start with a simple token-by-token cache, validate correctness and hit rate, and then consider adaptation for more complex architectures.
    4. Include session affinity in scheduling design to prevent the cache from being invalidated by load balancing.
    5. After launch, continuously monitor metrics and periodically review eviction policies and capacity configuration.

    Prefix caching does not change the model’s capabilities. It changes how repeated work is handled. For multi-turn interaction, long-context workloads, and coding scenarios with frequent modifications, it is often an effective way to reduce first-token wait time.