Why LLM Servers Store Past Keys and Values During Decoding
Machine LearningModel answerLast updated
Describe how attention-state caching works in decoder-only LLM serving: what is stored, why it speeds up generation, memory costs, and the production techniques that manage it.
You are reviewing the serving stack for a decoder-only language model that generates text one token at a time (causal self-attention) on GPUs. A colleague asks why the server keeps a large block of GPU memory for "past keys and values" for every active request, and whether it is worth the cost.
Give a systems-level explanation of this mechanism, the key-value (KV) cache.
Notation
- $L$: number of layers
- $B$: batch size
- $P$: prompt length
- $S$: current sequence length (prompt plus generated tokens)
- $n_q$: number of query heads
- $n_{kv}$: number of key/value heads
- $d_h$: per-head dimension
Your answer should cover
- What is stored. Which tensors are kept, their rough shapes, and which parts of the network hold them.
- Why it helps. What redundant work it removes during autoregressive generation, and how the asymptotic cost changes.
- Prefill vs. decode. How processing the prompt differs from producing tokens one by one, and how the performance profile of each phase differs.
- Trade-offs and pitfalls. Memory growth, batching requests of different lengths, MHA vs. MQA vs. GQA, consistency of positional information, and very long contexts.
- Optimizations. At least two techniques used by real serving systems, with the mechanism behind each (for example paged attention, KV quantization, sliding-window or streaming attention, GQA).
Assumptions
- This is inference only: weights are frozen and there is no backward pass.
- "Production" means a multi-tenant system with many concurrent requests of different lengths, not a single-sequence demo script.
- You may state and justify any scoping assumptions you need, such as the positional scheme (RoPE, learned absolute, ALiBi), the optimization target (time-to-first-token, per-token latency, or concurrency), and typical context lengths.
Hints
Hint 1
Ask which quantities in attention depend on earlier tokens and which depend only on the newest token. Think about which of Q, K, V must be reused at each later step.
Hint 2
Separate the cost of projecting a token into K and V from the cost of scanning all cached keys. The cache removes the first kind of repeated work but not the second. Then compare arithmetic intensity in the prompt pass with that of a single-token step.
Hint 3
Write the memory formula as 2 x L x B x S x n_kv x d_h x bytes_per_element, and note what each term lets you change: GQA lowers n_kv, quantization lowers bytes, a sliding window caps S, and paged allocation reduces waste from fragmentation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. What is cached
In every attention layer, each token is projected into a query, a key and a value. With causal attention, the key and value of an earlier token never change once computed, because they depend only on that token and the tokens before it, and the weights are frozen. So the server stores K and V for every past position, in every layer.
- Per layer, per sequence: K and V each have shape roughly
[S, n_kv, d_h]. Batched, that is[B, S, n_kv, d_h](or an equivalent paged layout). - Queries are not cached. A query is used once, to produce the output of its own position, and is never needed again.
- Only attention layers hold a cache. Embeddings, MLPs, normalization and the LM head are stateless per token.
2. Why it speeds up decoding
Without a cache, producing token $t+1$ means re-running the whole prefix of length $t$ through the model, recomputing K and V for all earlier positions. Over $N$ generated tokens, the projection and MLP work for the prefix grows quadratically: $O(N^2)$ token-passes in total.
With a cache, each step processes only the one new token:
- Compute its Q, K, V.
- Append K and V to the cache.
- Attend the new query over all $S$ cached keys and values.
Per-step projection and MLP cost drops from $O(t)$ token-passes to $O(1)$, so the total across $N$ tokens is linear. The honest caveat is that the attention scan over the cache is still $O(S)$ per step, so total attention work stays $O(N^2)$. It is simply much cheaper than redoing full forward passes, and it is dominated by memory reads rather than arithmetic.
3. Prefill vs. decode
| Prefill | Decode | |
|---|---|---|
| Work | All $P$ prompt tokens in parallel, filling the cache | One token per sequence per step, reading the cache |
| Bottleneck | Compute-bound (large matmuls, high arithmetic intensity) | Memory-bandwidth-bound (reads all weights plus the whole cache for little arithmetic) |
| Metric | Time-to-first-token (TTFT) | Time-per-output-token (TPOT), tokens/sec |
| Scaling | Attention cost grows with $P^2$ | Cost per step grows with $S$ through cache reads |
Batching matters most in decode: the weights are read once per step regardless of $B$, so more sequences amortize that read and raise throughput. The cache reads, however, scale with $B \times S$ and cannot be shared across sequences. This is why long contexts and big batches eventually hit a bandwidth and capacity wall.
Because the two phases stress different resources, many systems use chunked prefill (splitting long prompts so they do not stall decoding) or even disaggregated prefill and decode workers.
4. Memory model and trade-offs
$$\text{KV bytes} = 2 \cdot L \cdot B \cdot S \cdot n_{kv} \cdot d_h \cdot b$$
where the 2 covers K and V, and $b$ is bytes per element (2 for FP16/BF16).
Example: a 32-layer model, $n_{kv}=32$, $d_h=128$, FP16 uses $2 \cdot 32 \cdot 32 \cdot 128 \cdot 2 \approx 0.5$ MB per token. At $S = 4096$ that is about 2 GB per sequence, so 32 concurrent sequences need roughly 64 GB. The cache is linear in $S \times B$, and in practice it, not the weights, usually limits how many requests fit on a GPU.
MHA vs. MQA vs. GQA. In multi-head attention $n_{kv} = n_q$. Multi-query attention uses $n_{kv}=1$, and grouped-query attention uses $1 < n_{kv} < n_q$ with several query heads sharing each KV head. The cache shrinks by the factor $n_q / n_{kv}$ (for example 8x with 64 query heads and 8 KV heads), with a small quality cost for MQA and usually little for GQA. This is an architecture-time choice and cannot be toggled at serving time.
Positional information. With RoPE, keys are stored after rotation by their absolute position, so cached entries stay valid only if positions are not changed. Evicting middle tokens or shifting a window without handling positions silently corrupts attention. Learned absolute embeddings have the same constraint, and ALiBi biases depend on relative distance, so eviction must respect that too.
Ragged batches. Requests have different lengths and finish at different times. Padding to the longest wastes memory, and packing sequences requires per-sequence causal masks so tokens never attend across requests.
Beam search and multi-sample generation can duplicate the prompt cache unless it is shared.
5. Production optimizations
- Paged attention. The cache is split into fixed-size blocks (for example 16 tokens), and a per-sequence block table maps logical positions to physical blocks. This removes fragmentation and over-reservation, allows growth on demand, and enables prefix sharing with copy-on-write for common system prompts, beams and parallel samples. Waste drops from a large fraction to a few percent.
- KV quantization. Storing K and V in INT8 or FP8 (or lower, with grouped scales) halves or quarters bytes per element, so about 2x or more sequences fit and decode reads fewer bytes. The trade-off is possible accuracy loss, especially for keys with outliers, so it needs validation on long-context tasks.
- Sliding-window or streaming attention. Keeping only the last $W$ tokens (plus a few initial "sink" tokens) bounds $S$ at a constant, giving fixed memory per sequence. The cost is losing direct access to distant context, which hurts retrieval-style tasks.
- GQA/MQA (above) and prefix caching across requests, which skips prefill entirely for shared prompt prefixes.
- Eviction or offloading to CPU memory or NVMe, trading latency for capacity.
6. Common mistakes
- Claiming Q is cached, or that the cache makes attention $O(1)$ per step. It makes projections $O(1)$, while attention remains $O(S)$.
- Ignoring that decode is bandwidth-bound, and so mis-reasoning about why batching helps.
- Forgetting the $n_{kv}$ term, and therefore overestimating memory for GQA models.
- Evicting tokens without regard for positional encoding.
- Treating all requests as equal length and ignoring fragmentation.
A good answer also says what to optimize: TTFT favors prefix caching and chunked prefill, TPOT favors bandwidth savings (quantization, GQA), and concurrency favors paging and compact caches.