KV Cache in LLM Inference: How It Works and How to Improve Hit Rates
This article explains why autoregressive LLM generation repeats prefix computation, how KV caching avoids that repetition by storing keys and values, and how to estimate KV cache memory. It then examines what determines cache hit rates, why hits affect inference cost, and practical ways to improve hit rates through stable prompt structure, append-only conversation histories, standardized shared documents, and monitoring. It also covers memory pressure, cache eviction, MQA/GQA optimizations, and privacy isolation.
1. The Starting Point: Repeated Computation in Autoregressive Generation
Large language models generate text autoregressively. At each step, the model produces one token, appends it to the existing sequence, and then proceeds to the next step. For example, given the input “Today’s weather,” the model may first output “is,” then take “Today’s weather is” as input and output “nice.” Every step requires attention computation, and attention depends on the representations of all tokens already in the sequence.
If the entire sequence were processed from scratch at every step, the same prefix would be recomputed repeatedly. In the second step, the keys (K) and values (V) for “Today’s” and “weather” are exactly the same as in the first step, yet they would be calculated again. The longer the sequence, the more severe this repetition becomes, and inference latency increases accordingly.
2. The Basic Idea Behind KV Cache
The attention mechanism generates three sets of vectors for each token: query (Q), key (K), and value (V). The query of the current token is compared with the keys of all historical tokens to compute similarity scores, which are then used to produce a weighted sum of the corresponding values. The keys and values of historical tokens do not change during generation, so they can be stored and reused later.
KV cache works as follows: each time a token is generated, its K and V are written to GPU memory. In the next step, only the Q, K, and V for the new token are computed. The new Q is then used with all cached K values to calculate attention scores, and those scores are used to weight all cached V values.
This changes the per-step computation from “process the entire sequence” to “process one new token and read the cache.” The tradeoff is increased GPU memory usage. The speedup in inference is essentially a trade of memory for computation.
3. How to Estimate Memory Usage
The size of the KV cache can be estimated with the following formula:
KV cache size = 2 × layers × heads × head_dim × sequence length × batch size × bytes per element
The coefficient 2 means that one copy is stored for K and one for V. The number of bytes per element depends on precision: FP16 and BF16 use 2 bytes, while FP32 uses 4 bytes.
Consider a hypothetical configuration: 32 layers, 32 attention heads, head dimension 128, sequence length 4096, FP16 precision, and a single request.
- KV size for one token in one layer: 2 × 32 × 128 × 2 = 16,384 bytes, or 16 KB.
- KV size for one token across all 32 layers: 16 KB × 32 = 512 KB.
- Total for 4096 tokens: 512 KB × 4096 = 2 GB.
If 10 requests of equal length are processed concurrently, the memory requirement becomes 20 GB. In long-context or large-batch scenarios, the KV cache can exceed the memory used by the model parameters themselves and become the main deployment bottleneck.
The following code performs this calculation quickly:
def kv_cache_bytes(layers, heads, head_dim, seq_len, batch, dtype_bytes=2):"""Return KV cache size in bytes (one copy each for K and V)."""return 2 * layers * heads * head_dim * seq_len * batch * dtype_bytessingle = kv_cache_bytes(32, 32, 128, 4096, batch=1)multi = kv_cache_bytes(32, 32, 128, 4096, batch=10)print(f"Single request: {single / 1024**3:.1f} GB") # 2.0 GBprint(f"10 requests: {multi / 1024**3:.1f} GB") # 20.0 GB
4. Why Cache Hit Rate Affects Cost
The value of KV cache is not limited to a single request. If multiple requests share the same prefix, such as the same system prompt, the same long document, or the history of a multi-turn conversation, the KV state corresponding to that prefix can be reused without recomputation. This saves compute for the service provider, and some inference services apply a lower billing rate to input tokens that hit the cache.
A hit requires the prefix to be exactly identical. The model generates KV in token order, so if any earlier token differs, the later cache cannot be used. As a result, multi-turn conversations and scenarios that repeatedly call the same template usually have higher hit rates, while scenarios in which every request contains different content usually have lower hit rates.
Cache hit rate should be discussed in the context of a specific workload. Individual user behavior, prompt design, and request intervals all affect the result. There is no fixed number that applies to every scenario.
5. Engineering Practices for Improving Cache Hit Rate
- Keep prefixes fixed and place stable content first. System instructions, role settings, tool definitions, and reference documents should be placed at the beginning of the prompt, while dynamic content should be placed at the end.
- Avoid unstable fields in the prefix. For example, writing a timestamp with millisecond precision at the beginning of the system prompt will cause the prefix to differ on every request.
- Keep conversation history append-only. In multi-turn conversations, append messages only at the end. Do not modify or reorder historical messages arbitrarily.
- Standardize shared documents. The same document must use a consistent segmentation method and concatenation order so that it can be reused repeatedly.
- Monitor hit metrics. Record the number of input tokens and the number of hit tokens for each request, calculate the hit rate, and compare it with cost data.
A recommended prompt structure is shown below:
[System instructions: fixed, reusable][Tool definitions: fixed, reusable][Reference documents: concatenated in a fixed order][Conversation history: append-only][Current user input: dynamic]
6. Limitations and Caveats
- Memory pressure. KV cache grows linearly with sequence length and batch size. Long-context services need to reserve space for the cache or limit the maximum context length.
- Cache eviction. When memory is limited, the system must evict old cache entries according to a policy, such as least recently used (LRU). An evicted prefix must be recomputed when it is requested again.
- Architectural optimizations. Common variants such as multi-query attention (MQA) and grouped-query attention (GQA) reduce the number of KV heads, thereby lowering the cache size per token. These designs are implemented in the model architecture and work together with inference-time cache policies.
- Privacy and isolation. When reusing cache across requests, it is essential to ensure that data from different users is not exposed. The cache index should include tenant or session identifiers to prevent sensitive content from being matched by other requests.
7. Summary
KV cache avoids repeated computation in autoregressive generation by storing the keys and values of historical tokens, trading memory for speed. Understanding the memory formula helps estimate deployment cost, while understanding the conditions for a cache hit helps design prompt structure and evaluate service billing. Together, these two perspectives provide a complete view of inference service performance and cost.
