# KV Cache and Inference Performance

> Understand how the KV cache removes repeated computation from autoregressive decoding, and master the trade-offs between latency, throughput, memory and request scheduling.

- URL: https://dmxsf.com/en/wiki/inference/kv-cache/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-15
- Tags: KV cache, Inference, Serving

## After this page you will be able to

- Explain why autoregressive generation is inherently slow.
- Say what exactly the KV cache stores and which repeated computation it saves.
- Explain why the cache reduces latency but increases memory use significantly.
- Say which bottleneck each of PagedAttention, continuous batching and quantization addresses.

If you have already read [Attention Basics](https://dmxsf.com/en/wiki/architecture/attention-basics/), this article connects the "attention formula" to the "online inference system".

## Background: why each new token costs more

LLM inference is usually autoregressive: it generates one new token at a time, appends it to the context, and goes on to predict the next token.

Without any caching mechanism, at step `t` the model has to reprocess the whole prefix of length `t`. The problems with this are:

- The `K/V` of the historical tokens are computed again and again.
- The longer the sequence, the higher the cost of a single step.
- The total generation cost grows quickly with the output length.

From a systems point of view, inference is not just "run one forward pass" but "run many highly redundant forward passes over the same prefix". The KV cache exists to eliminate exactly this waste.

## What the KV cache actually stores

In self-attention, every layer projects its hidden states into `Q`, `K` and `V`. For tokens that have already been generated:

- Their `K/V` do not change in later steps.
- What really changes is only "the query of the current new token" and its new `K/V`.

So we can save the `K/V` that each layer produced for the historical tokens. At the next generation step:

1. Compute `Q/K/V` of this layer only for the new token.
2. Append the new `K/V` to the cache.
3. Use the new token's `Q` to attend to all the `K` in the cache.
4. Then read the `V` in the cache according to the weights.

That is the core of the KV cache: `don't recompute history, only update incrementally.`

## Why it saves so much time

Without a KV cache, every generation step redoes the projections and in-layer propagation for the whole prefix; with a KV cache, most intermediate results of historical tokens can be reused.

Roughly:

- Without a cache: step 1 processes 1 token, step 2 reprocesses 2, step 3 reprocesses 3...
- With a cache: step 1 processes 1 token, step 2 adds just 1, step 3 adds just 1...

Of course, computing the attention scores still requires the current query to look at all historical keys, so the per-step cost of the decode phase still grows as the sequence gets longer. But compared with recomputing the whole prefix, the saving from caching is still very large.

## Prefill and decode: two completely different phases

To understand the KV cache you must distinguish two phases:

### Prefill

The model reads the whole prompt for the first time and builds the `K/V` of all historical tokens. This phase usually has high parallelism and high throughput, but a large amount of computation.

### Decode

The model starts generating token by token, adding one token per step and using the cache repeatedly. The compute granularity of this phase is small and memory access is frequent, so the system bottleneck is very different from prefill.

Many optimizations in real services are designed separately for these two phases. For example:

- Prefill cares more about large-batch throughput and the efficiency of handling long prompts.
- Decode cares more about per-token latency, scheduling and cache management.

Putting the two phases and the growth of the cache in one picture makes it easier to see why the inference bottleneck does not disappear once there is a KV cache, but moves somewhere else:

*Figure: Prefill "reads the history in one go and builds the cache", while decode "adds only a little computation each time". The KV cache removes the repeated projections, but makes memory management, memory-access efficiency and scheduling policy the new core of the system.*

## The memory formula: why the cache eats so much memory

The speed gain of the KV cache is not free; it costs a lot of memory. A common rough estimate is:

$$
\text{KV cache bytes} \approx 2 \times L \times B \times S \times H_{kv} \times d_{\text{head}} \times b
$$

Here $L$ is the number of layers, $B$ is the number of concurrent sequences (batch), $S$ is the sequence length, $H_{kv}$ is the number of KV heads, $d_{\text{head}}$ is the dimension of each head, and $b$ is the number of bytes per element; the leading $2$ accounts for storing both keys and values.

The formula shows directly that the cache cost scales linearly with:

- The number of layers: more layers, a larger cache.
- The batch size: a larger batch, a larger cache.
- The context length: a longer context, a larger cache.
- The precision: for example FP16 takes more space than INT8.

A concrete example gives a feel for the magnitude: Llama 3 8B has 32 layers, 8 KV heads and a head dimension of 128. Stored in FP16, each token needs

$$
2 \times 32 \times 8 \times 128 \times 2\ \text{bytes} = 131{,}072\ \text{bytes} = 128\ \text{KiB}
$$

A sequence of 8192 tokens is $128\ \text{KiB} \times 8192 = 1\ \text{GiB}$; serving 32 such sequences at once needs 32 GiB for the cache alone, which already exceeds the model weights (about 16 GB). By comparison, Llama 2 7B, of the same size but with traditional multi-head attention (32 KV heads), needs 512 KiB per token, so the same 8192-token sequence takes 4 GiB, four times as much.

### Work it out yourself

Choose different models, cache precisions, sequence lengths and concurrency, watch how the cache size changes, and compare it with the model weights:

So many engineering problems in an inference system are really asking: how can this cache be managed more economically, more stably and more flexibly without noticeably hurting quality?

## How MHA, MQA and GQA affect the cache

The size of the KV cache is closely tied to the attention head design.

### MHA

In traditional multi-head attention every head has its own `K/V`, which gives strong expressiveness but a large cache cost.

### MQA

Multi-query attention lets several query heads share one set of `K/V`, which noticeably reduces the cache size and the memory-access cost and is friendly to inference.

### GQA

Grouped-query attention sits between the two: several query heads share one set of `K/V`, balancing quality and efficiency.

That is why many models optimized for deployment today prefer GQA or MQA instead of keeping the MHA design of the original Transformer. What shrinking the K/V heads costs in quality depends on the setup, and DeepSeek-V2's MLA takes another route by caching only a compressed latent vector; see [Efficient Attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/), which also has a widget comparing MHA, GQA, MQA and MLA.

## PagedAttention: why "the cache fits" is not enough

Having a cache is not enough; what matters is how it is managed. In real services request lengths vary widely, and reserving one large contiguous block of memory for each request easily leads to:

- Lots of fragmentation
- Memory that is allocated but not fully used
- Low utilization when long and short requests run together

The core idea of PagedAttention is to manage the KV cache in smaller pages instead of requiring every request to occupy one large contiguous region. The benefits are:

- More flexible memory allocation
- Less fragmentation
- Easier reclamation when a request finishes
- Better suited to many concurrent requests

This kind of optimization does not change the model's output logic, yet it noticeably improves real throughput, and is a typical case in inference-systems engineering of "changing the low-level machinery for a big gain". The block size, the block table and the memory arithmetic of reserving the maximum length versus paging are in [Continuous Batching and PagedAttention](https://dmxsf.com/en/wiki/inference/continuous-batching/).

## Continuous batching: don't let the GPU wait

Static batches have a common problem: you often have to wait for a whole batch of requests to assemble before computing them together, or the longest request in a batch holds up the others.

The idea of continuous batching is:

- When a new request arrives, you don't have to wait for the current batch to finish entirely.
- Requests that have finished can leave at any time.
- The compute slots they free up can be filled by new requests immediately.

This noticeably raises GPU utilization and is especially suited to online serving. The price is a more complex scheduler, and higher demands on cache management, sequence-state bookkeeping and fairness policy. A comparison of static and continuous batching on a real inference server, and a scheduling simulator whose parameters you can drag, are in [Continuous Batching and PagedAttention](https://dmxsf.com/en/wiki/inference/continuous-batching/).

## Why quantization is closely tied to the KV cache

Many people think of quantization as "mainly saving the memory of the model weights", but for long-context inference the KV cache matters just as much.

When sequences are long and concurrency is high, the bottleneck may not be the model weights but the cache itself. Representing the cache with fewer bits, or using a more space-efficient head design, then directly affects:

- How many concurrent requests fit
- How long a context can be supported
- Whether pages must be swapped or reclaimed frequently

Of course, quantization brings a trade-off in accuracy and stability, so it usually has to be evaluated together with the task type, the model architecture and the service goals.

## What to look at when choosing a framework

Whether you end up with vLLM, SGLang, llama.cpp, Ollama or a self-built service, the criterion should not be just "can it run", but how it performs along these dimensions:

- Does it support efficient KV cache management?
- Does it have continuous batching?
- Are throughput and latency stable with long contexts?
- Is resource isolation clear in multi-model, multi-tenant scenarios?
- Are monitoring, logging and replay capabilities sufficient?

Inference optimization in a production environment is essentially a systems problem, not a single-algorithm problem.

## Metrics worth watching online

If you are responsible for service stability, keep an eye on these metrics over the long term:

- Time to first token (TTFT)
- Average generation speed (tokens/s)
- p95 / p99 latency
- Memory usage and fragmentation rate
- Request queueing time
- Throughput changes when long and short prompts run together

Many performance problems are not caused by a slow model, but by the combined effect of cache allocation, batch scheduling and request shape.

Linking these metrics with the usual symptoms looks more like the troubleshooting order in a real service:

*Figure: The worst way to troubleshoot KV-cache issues is to treat them all alike. Mapping TTFT, tokens/s, OOM and tail latency separately to prefill, decode, cache size and paging or scheduling usually finds the real bottleneck faster.*

## When the KV cache becomes a burden

The KV cache is not something you can simply switch on and forget. Be especially careful in these scenarios:

1. With extremely long contexts and very high concurrency, cache memory becomes the bottleneck before the weights do.
2. When requests are very short, the cache gains are limited, but scheduling complexity and memory-management overhead go up.
3. With many multi-turn chat sessions, poor management of cache lifetime lets old sessions hold on to memory for a long time.
4. In some edge deployments memory is extremely tight, and you should first consider quantization, trimming the context or tiered offloading.

Another route is to stop the cache from growing with length: linear attention, state space models and hybrids replace the KV cache of most layers with a fixed-size state, at the price of lossy memory; [State Space Models and Hybrid Architectures](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid/) works out the cache ledger of Jamba, Nemotron-H and Qwen3-Next.

What matters in systems optimization is not "how advanced a technique is", but "whether it solves your most expensive bottleneck right now".

## Suggested reading order

To tie this knowledge together, continue in this order:

1. [Attention Basics](https://dmxsf.com/en/wiki/architecture/attention-basics/)
2. [Attention Is All You Need](https://dmxsf.com/en/blog/attention-is-all-you-need/)
3. [Lost in the Middle](https://dmxsf.com/en/blog/lost-in-the-middle/) (paper explainer)

That way you will understand three things together: how attention works, why long context is expensive, and why, even after paying that high cost, a model does not necessarily use the context well.

The idea is not limited to language models: the robot policy π0 uses a block-causal mask so that the keys and values of its image-and-language prefix are computed once for all 10 flow-matching steps, an instance of prefix caching; see the [π0 breakdown](https://dmxsf.com/en/blog/pi0-a-vision-language-action-flow-model-for-general-robot-control/).

A recent example of pushing the cache to the limit is DeepSeek-V4.1-Flash: its global KV cache takes 890 bytes per token (389,120 for DeepSeek-V1), the product of cross-layer sharing, sequence compression and FP4; the [paper breakdown](https://dmxsf.com/en/blog/deepseek-v41-flash-pushing-the-limits-of-kv-cache-compression/) rebuilds those numbers from the public configs.

## Summary and exercises

**Key points of this page:**

1. The KV cache stores the key and value of every processed token at every layer, so past information is not recomputed but only updated incrementally.
2. It trades memory for time: the cache size is about $2 \times L \times B \times S \times H_{kv} \times d_{\text{head}} \times b$ bytes, growing linearly with layers, concurrency and length; GQA/MQA and quantization shrink it.
3. Prefill processes the whole prompt in parallel and is compute-heavy; decode generates token by token and keeps reading the cache, so it is memory-bound; the two phases have different bottlenecks.
4. PagedAttention solves how the cache is managed and continuous batching keeps the GPU from waiting; neither changes the model's output logic.

### Quick self-check

**1. What does the KV cache store?**

- [ ] The query vectors of every layer
- [x] The key and value vectors of every processed token at every layer
- [ ] The attention weight matrices
- [ ] The model's weight parameters

> The K/V of past tokens do not change in later steps, so they can be saved and reused; only the query of the new token and its new K/V change. The attention weights depend on the new query at every step, so caching them is pointless.

**2. Llama 3 8B (32 layers, 8 KV heads, head dimension 128) stores its cache in FP16 and serves 32 sequences of 8192 tokens at once. How much memory does the KV cache alone need?**

- [ ] About 1 GiB
- [ ] About 4 GiB
- [x] About 32 GiB
- [ ] About 128 GiB

> Each token needs 2×32×8×128×2 bytes, which is 128 KiB; one 8192-token sequence is 1 GiB; 32 of them are 32 GiB, already more than the model weights (about 16 GB) themselves.

**3. In the previous question, change the number of KV heads from 8 to 32 (back to MHA) and keep everything else. How large is the cache of one 8192-token sequence?**

- [ ] 1 GiB
- [ ] 2 GiB
- [x] 4 GiB
- [ ] 8 GiB

> The cache is proportional to the number of KV heads, and 32/8 = 4, so it grows from 1 GiB to 4 GiB, 512 KiB per token. This is why GQA became the default choice for deployment.

**4. Which statement about prefill and decode is correct?**

- [ ] Prefill generates token by token, decode reads the whole prompt at once
- [ ] The two phases have the same bottleneck, so they are optimized in the same way
- [x] Prefill processes the whole prompt in parallel and is compute-heavy; decode adds one token per step with small compute granularity but has to read the whole cache at every step
- [ ] With a KV cache, the per-step cost of decode no longer depends on the sequence length

> The cache saves the repeated projection of historical tokens, but the new token's query still has to look at all historical keys, so the per-step cost of decode still grows with the sequence length, and the bottleneck is mostly the memory bandwidth for reading the cache (see [GPUs and the Roofline Model](https://dmxsf.com/en/wiki/systems/gpu-and-roofline/) for why that is the bottleneck).

**5. Which of these statements are correct? (multiple answers)**

- [x] PagedAttention manages the KV cache in small pages, which reduces fragmentation and improves memory utilization
- [x] Continuous batching lets finished requests leave at any time, and the freed slots are immediately filled by new requests
- [ ] PagedAttention uses approximate attention to cut compute and slightly changes the model output
- [ ] Continuous batching waits until a whole batch of requests has finished before starting the next one

> Both optimizations work at the system level: they do not change the logic of the model's output, only how memory and compute are used. The last two options describe the problems of static batching.

**6. A service has a very long context and high concurrency, and its GPU memory is filled mostly by the KV cache. Which of these directly shrink the cache? (multiple answers)**

- [x] Switch to a model with fewer KV heads, such as GQA or MQA
- [x] Quantize the KV cache to low bit-widths such as INT8
- [ ] Quantize only the model weights to 4 bits
- [ ] Increase the batch size so that each request gets a smaller cache

> The cache is determined by the number of layers, the concurrency, the length, the number of KV heads and the bytes per element. Quantizing the weights does not shrink the cache, and a larger batch only makes the cache bigger.

**Exercises:**

1. Why can the KV cache avoid "re-projecting historical tokens" and yet not make the decode phase a constant-cost operation?
2. Why is GQA often better suited to deployment than traditional MHA in long-context online services?
3. If a service has a normal TTFT but a poor p99 latency, which cache or scheduling problems would you check first?
4. When the memory bottleneck comes mainly from the KV cache and not from the model weights, which optimizations rise in priority?
5. Qwen2.5 7B has 28 layers, 4 KV heads, head dimension 128 and about 7.6B parameters. With an FP16 cache: how many bytes does the cache of one token take? After the FP16 weights are loaded on a 24 GiB GPU, and giving all the remaining memory to the KV cache (ignoring activations and framework overhead), how many 8192-token sequences can be served at once? What if the cache is INT8?

<details>
<summary>Reference answers</summary>

1. With the cache, the K/V of historical tokens are not projected again; each step runs one Q/K/V projection and forward pass for the new token only, which saves the repeated computation over the whole prefix. The attention itself cannot be saved: the new token's query must score against all historical keys and then read all historical values by those weights, and both the compute and the memory traffic of this part are proportional to the sequence length, so the per-step cost of decode still grows with length. In addition, every step reads the whole cache from GPU memory, so the bottleneck is mostly memory bandwidth.

2. GQA lets several query heads share one set of K/V, reducing the number of KV heads from $H$ to $G$, so the cache and the memory traffic of reading it at every decode step shrink to $G/H$ of the original (Llama 3 8B has 32 query heads for 8 KV heads, only 1/4 of MHA). In long-context, high-concurrency services the cache becomes the memory bottleneck before the weights do, and a smaller cache means more concurrent requests and longer contexts, at a quality cost that is usually small.

3. A normal TTFT says requests start on time and prefill is generally fine, so a bad p99 more likely comes from the decode phase and from scheduling. Look at three kinds of signals first: memory usage and fragmentation (are cache paging and reclamation timely), the change in throughput and tail latency when long and short prompts run together, and the continuous-batching schedule, for example whether the batch is held back by a few long requests. A strongly fluctuating tail latency is most often caused by cache paging, reclamation and the continuous-batching policy not being coordinated.

4. The optimizations that rise in priority are those that make the cache itself smaller or better managed: a head design that saves cache, such as GQA, MQA (or MLA); low-bit quantization of the KV cache such as INT8; PagedAttention to reduce fragmentation and waste; and, where necessary, trimming the context length or offloading the cache in tiers. Quantizing only the weights helps little, because the weights are not the bottleneck.

5. The cache of one token is $2 \times 28 \times 4 \times 128 \times 2 = 57{,}344$ bytes, that is 56 KiB; one 8192-token sequence takes 448 MiB. After about 14.2 GiB of weights ($7.6 \times 10^9$ parameters at 2 bytes each) are loaded on the 24 GiB GPU, about 9.8 GiB remain, which fits 22 sequences; with an INT8 cache each takes only 224 MiB, which fits 44. A real service also has to leave room for activations and the framework, so the number that fits is smaller. Verification code:

   ```python
   def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_elem):
       return 2 * layers * kv_heads * head_dim * bytes_per_elem

   per_token = kv_bytes_per_token(28, 4, 128, 2)
   per_seq_mib = per_token * 8192 / 2**20
   free_mib = (24 - 14.2) * 1024
   print(per_token, per_seq_mib)  # 57344 448.0
   fp16 = int(free_mib // per_seq_mib)
   int8 = int(free_mib // (per_seq_mib / 2))
   print(fp16, int8)  # 22 44
   ```

</details>

## Further thoughts

Inference optimization easily creates the illusion of "piling up jargon", but the criterion that is really useful is simple:

> Where is your system's bottleneck: compute, memory access, memory capacity, or scheduling?

The KV cache is only the starting point. Once you understand it, you have truly entered the core of LLM systems engineering.

- Two routes shrink the KV cache without touching the weights: Liu et al.'s [KIVI](https://arxiv.org/abs/2402.02750) (2024, asymmetric quantization with precise keys and low-bit values) and Zhang et al.'s [ZipCache](https://arxiv.org/abs/2405.14256) (2024, importance-based token-level compression); [CLA](https://arxiv.org/abs/2405.12981) (2024) and [YOCO](https://arxiv.org/abs/2405.05254) (2024) instead let adjacent layers share K/V, removing the layer dimension of the cache outright.
- For cross-request reuse and cluster-scale cache organization, see [prefix caching and PD disaggregation](https://dmxsf.com/en/wiki/inference/prefix-caching/): RadixAttention, CacheBlend, DistServe, Mooncake.

## Companion code

[KV cache: the memory formula, exactness, the saving, prefill against decode](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/kv-cache): The memory formula against real cache tensors, cached and uncached decoding agreeing exactly, and the saving counted two ways: token positions processed (exact) and time on a CPU (read the ratios), plus the prefill and decode split.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/kv-cache`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/kv-cache/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/kv-cache/README.en.md)
- [`kv_cache.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/inference/kv_cache.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#kv-cache)

## FAQ

### What does the KV cache store?

It stores the key and value vectors of every already-processed token at every layer of self-attention. To generate a new token, only the query, key and value of the new token need to be computed, and the cached historical K/V are reused for attention, which avoids redoing the linear projections over the whole history.

### How much memory does the KV cache take, and how do I estimate it?

The cache bytes per token are about 2 × layers × KV heads × head dimension × bytes per element, multiplied by the sequence length and the number of concurrent sequences. Llama 3 8B (32 layers, 8 KV heads, head dimension 128), for example, needs about 128 KiB per token in FP16, so a sequence of 8192 tokens needs about 1 GiB.

### Why do GQA and MQA reduce memory?

In standard multi-head attention every query head has its own K/V head. MQA lets all query heads share one set of K/V and GQA lets several query heads share one set, so there are fewer KV heads, the cache and the memory traffic shrink proportionally, and the effect on model quality is small.
