KV Cache Explained: How It Works and How to Estimate GPU Memory Usage
KV Cache stores the key and value vectors of previously processed tokens, eliminating redundant computation in autoregressive generation but consuming GPU memory that grows with sequence length and batch size. This article explains why caching is needed during inference, how KV Cache works, provides a practical formula for estimating its memory footprint with worked examples, and covers common optimization techniques such as GQA/MQA, quantization, paged memory management, and prefix caching—including how cache hit rate affects serving cost.
KV Cache Explained: How It Works and How to Estimate GPU Memory Usage
Why Inference Needs Caching
The inference process of a large language model can be split into two phases. The first phase processes the user’s entire input; the second phase generates output tokens one at a time. These two phases have very different computational characteristics, and the efficiency of an inference framework depends largely on how it handles the redundant computation in the second phase.
Without any caching mechanism, the model must re-process the entire existing sequence every time it generates a new token. The longer the sequence, the more computation is repeated. For responses spanning hundreds or thousands of tokens, this overhead quickly accumulates into noticeable latency and wasted compute. KV Cache is a general-purpose technique designed to solve exactly this problem.
Redundant Computation in Autoregressive Generation
Mainstream LLMs generate text autoregressively: the model predicts only the next token at each step, appends it to the sequence, and predicts again.
Consider a simple example. Suppose the input is “Write a poem about spring,” and the model outputs words one by one.
- Step 1: The model processes “Write a poem about spring” and outputs “The.”
- Step 2: The model processes “Write a poem about spring. The” and outputs “breeze.”
- Step 3: The model processes “Write a poem about spring. The breeze” and outputs “touches.”
The problem lies in steps 2 and 3. In the attention computation, the model computes three sets of vectors for every token in the sequence: the Query (Q), Key (K), and Value (V) vectors. From step 1 to step 2, the K and V vectors of all earlier tokens are completely unchanged—yet they are recomputed from scratch. The longer the sequence, the worse this waste becomes.
How KV Cache Works
The idea behind KV Cache is straightforward: store the K and V vectors of already-processed tokens and read them directly in subsequent steps instead of recomputing them.
The workflow is as follows:
- When processing the input sequence, compute the K and V vectors for each token and write them into the cache.
- When generating a new token, compute Q, K, and V only for that new token.
- Append the new K and V to the cache.
- Compute attention scores between the new token’s Q and all cached K vectors, then take a weighted sum over all cached V vectors to produce the output at the current position.
With this change, the per-step computation drops from “processing the entire sequence” to “processing only the newest token and reading the historical cache.” The compute savings are significant, but the trade-off is that memory usage grows with sequence length. In essence, KV Cache trades space for time.
Estimating KV Cache Memory Usage
KV Cache size can be estimated with the following formula:
KV Cache size = 2 × num_layers × num_attention_heads × head_dim × seq_len × batch_size × bytes_per_element
The factor of 2 accounts for storing both K and V for each token. Bytes per element depend on the precision: FP16 and BF16 typically use 2 bytes, FP32 uses 4 bytes, and INT8 uses 1 byte.
Here is a concrete example. Assume a model with 32 layers, 32 attention heads per layer, a head dimension of 128, a sequence length of 4096, FP16 precision, and a batch size of 1.
KV usage per token per layer:
2 × 32 × 128 × 2 = 16,384 bytes ≈ 16 KB
For a single sequence across all 32 layers:
16 KB × 32 layers × 4,096 tokens = 2 GiB
If 10 sequences are processed concurrently (batch size = 10), memory usage rises to 20 GiB—and this figure excludes the model weights themselves. For long-context or high-concurrency scenarios, KV Cache often exceeds the memory footprint of the model weights and becomes the dominant memory bottleneck.
You can run a quick estimate with the following code:
def kv_cache_gib(layers, heads, head_dim, seq_len, batch, bytes_per_elem=2):total_bytes = 2 * layers * heads * head_dim * seq_len * batch * bytes_per_elemreturn total_bytes / (1024 ** 3)print(kv_cache_gib(32, 32, 128, 4096, 1)) # 2.0print(kv_cache_gib(32, 32, 128, 4096, 10)) # 20.0
Common Memory Optimization Approaches
Once you understand where the memory goes, the optimization opportunities become clear. Common approaches in the industry include:
- Reduce the number of KV heads. Grouped-Query Attention (GQA) and Multi-Query Attention (MQA) let multiple query heads share a smaller set of K and V heads, directly reducing the data cached per token.
- Lower numerical precision. Quantizing the KV Cache from FP16 to INT8 cuts memory usage in half. Be aware of the impact of precision loss on output quality, which should normally be validated through evaluation.
- Paged memory management. Organizing the cache into fixed-size blocks—similar to virtual memory paging in operating systems—reduces memory fragmentation and improves concurrency capacity.
- Cap the maximum context length. Set an upper limit on input lengths that your business scenario does not actually need, preventing a single request from occupying too much memory.
These methods can usually be combined. Which one to choose depends on whether your bottleneck is memory capacity, compute speed, or concurrent throughput.
From Memory to Cost: Prefix Caching and Hit Rate
KV Cache has an important extension at the serving layer: Prefix Caching. In many chat and application scenarios, multiple requests share the same opening portion—such as a system prompt, a fixed document context, or the history of a multi-turn conversation. If the inference service can recognize this shared prefix and reuse its already-computed KV cache, it does not need to reprocess that part of the input.
Cache hit rate can be defined as:
Cache hit rate = prefix tokens served from cache ÷ total input tokens of the request
Here is a hypothetical example. A request has 2,500 input tokens in total, of which the first 2,000 tokens are a fixed system prompt identical to previous requests and can hit the cache. The hit rate is therefore 2,000 ÷ 2,500 = 80%.
Hit rate directly affects cost. If the provider applies different pricing or resource allocation for cached versus uncached input tokens, then the higher the hit rate, the lower the effective cost per request. The exact price difference depends on the provider’s billing rules—developers should refer to the official documentation for details.
To improve your hit rate, keep the following in mind:
- Put stable content at the beginning of the prompt and variable content (such as the user’s question) at the end. The prefix must match character for character—even a single punctuation change invalidates everything after it.
- In multi-turn conversations, keep the order and formatting of historical messages unchanged and avoid unnecessary rewrites.
- When asking multiple questions about the same long document, place the document content in a fixed position so subsequent questions can reuse its cache.
Engineering Considerations in Production
In real deployments, cache management strategy matters just as much.
Cache space is finite. When memory runs short, the system must evict part of the cache, and the most common strategy is Least Recently Used (LRU). Evicted prefixes must be recomputed on the next request, so hit rates can fluctuate under high concurrency.
Cache lifetime also needs to be clearly defined. After a request finishes, whether to keep its KV cache—and for how long—depends on your memory budget and your workload’s reuse patterns. Keeping caches too long crowds out other requests; keeping them too short forfeits the benefits of reuse.
When evaluating optimizations, monitor four metrics together: time-to-first-token, overall throughput, peak memory usage, and cost. Looking at any single metric in isolation can lead to misleading conclusions. For example, a higher cache hit rate that also drives up peak memory usage is not necessarily a better outcome.
Summary
KV Cache stores the key and value vectors of historical tokens, converting the redundant computation of autoregressive generation into memory usage. Its cost is memory that grows linearly with sequence length and batch size. Understanding this relationship lets you estimate capacity requirements with the formula above and choose appropriate optimizations—precision, head-count design, paged management, and more. Prefix caching extends memory reuse across requests, making cache hit rate an important lever on serving cost. Factoring these into your prompt design and inference strategy will help you control both latency and cost more precisely.
