---
title: KV cache
url: https://gurkanozkan.ai/learn/topics/kv-cache/
markdown: https://gurkanozkan.ai/learn/topics/kv-cache.md
kind: topic
tracks:
  - Applied LLM
  - ML engineering
  - Research
json: https://gurkanozkan.ai/api/learn/topics/kv-cache.json
---

# KV cache

During autoregressive decoding a transformer stores the key and value vectors of every past token in every layer, so each new token only computes its own projections and attends over the stored ones. The cache turns per-step attention from recomputing the whole prefix into a single read, but it grows linearly with context length and concurrency and usually becomes the binding constraint on how many users a GPU can serve. Interviewers use it to test whether you can do capacity arithmetic from a model config, explain why decode is memory-bandwidth-bound, and reason about GQA/MLA, paged allocation, prefix and prompt caching, and KV quantisation.

## Key concepts

### What is cached, and why

For each layer and each KV head the cache holds K and V for all previous tokens; queries are not cached because each step only needs the new token's query. Prefill processes the prompt in one parallel pass and writes the cache; each decode step appends one token's K and V per layer and reads the whole cache. Without it, step t would redo O(t) projections and the full prefix attention, making generation quadratic in compute for no benefit.

### Memory formula

Bytes per token = 2 (K and V) × layers × kv_heads × head_dim × bytes per element. Total = that × tokens per sequence × concurrent sequences. It depends on the number of KV heads, not query heads, and not directly on parameter count: a Llama-3-8B-style config (32 layers, 8 KV heads, head_dim 128, bf16) needs 128 KiB per token, whereas a head_dim-256 model with more KV heads can need far more despite being similar in size.

### MQA, GQA and latent attention

Multi-query attention shares one K/V head across all query heads (cache shrinks by the head count, with some quality loss); grouped-query attention uses an intermediate number of KV groups, e.g. 32 query heads sharing 8 KV heads cuts the cache 4× with little quality loss and can be uptrained from a multi-head checkpoint. DeepSeek's multi-head latent attention caches a low-rank latent (512 dimensions plus a 64-dimensional decoupled RoPE key per layer) and reconstructs K/V on the fly; DeepSeek-V2 reports a 93.3% smaller cache than its 67B dense predecessor.

### Paged allocation (PagedAttention)

Reserving a contiguous max-length buffer per request wastes memory through internal and external fragmentation; the vLLM paper found earlier systems used only about 20–40% of KV memory for real token state. PagedAttention splits the cache into fixed-size blocks (16 tokens by default in vLLM) mapped through a per-request block table, so waste is limited to the last partial block, and blocks can be shared copy-on-write across beams, parallel samples and common prefixes.

### Prefix caching and provider prompt caching

Self-hosted engines hash each full block together with its parent's hash (plus LoRA ID or image hashes) and reuse matching blocks across requests, evicting least-recently-used free blocks. Hosted APIs expose the same idea as prompt caching: an exact-prefix match within a TTL (Anthropic's default is 5 minutes) billed at a premium to write (1.25× for the 5-minute tier) and a steep discount to read (0.1× base input price as standard; as of November 2026 some newer models charge 0.05× or less). Any change early in the prompt invalidates everything after it, so put stable content (system prompt, tool definitions, documents) first and volatile content (timestamps, user turn) last. A semantic cache is different: it reuses whole responses for similar queries and can return wrong answers.

### Why decode is bandwidth-bound

Each decode step reads every weight once plus the entire KV cache of every sequence in the batch, while doing only about 2 FLOPs per weight per sequence. Batching amortises weight reads, but KV reads grow with batch × context, so at long context the attention part stays memory-bound and KV bytes, not FLOPs, set the per-token latency and the maximum batch size.

### Shrinking or moving the cache

FP8 KV halves memory (INT4 quarters it) at an accuracy cost that must be measured on long-context retrieval: vLLM saw 128k needle accuracy fall from 91% to 13% from attention accumulation precision before a fix, and for Llama-3.1-8B on one H100, FP8 KV only beat BF16 decode latency above about 7k tokens. Sliding-window or local attention layers cap per-layer cache at the window size (Gemma-style local:global layer mixes); attention-sink/eviction schemes (StreamingLLM, H2O) keep a subset of tokens; hybrid models with linear-attention or state-space layers keep a constant-size state in those layers. Offloading to CPU memory or SSD tiers trades capacity for transfer latency. Frontier designs now break the simple per-token formula: Qwen3.5 keeps KV in only one layer in four, and DeepSeek-V4's compressed sparse attention needs about 10% of V3.2's KV at 1M tokens. Offload tiers are first-class in vLLM connectors, LMCache, Mooncake and Dynamo.

### Capacity planning

Usable KV memory ≈ GPU memory − weights − activation workspace − runtime overhead (engines reserve a fraction, e.g. vLLM's gpu-memory-utilisation). Divide by bytes per token to get the token budget, then by the realistic context distribution, not the maximum, to get concurrency. When the budget is exhausted engines preempt (swap or recompute) requests, which shows up as latency spikes rather than errors.

## Worked examples

### Cache size for an 8B-class model serving 16 users at 8k tokens

A model has 32 layers, 8 KV heads and head dimension 128, with a bf16 cache. Estimate KV memory for 16 concurrent requests of 8,192 tokens each, and compare with full multi-head attention using 32 KV heads.

**Solution**

**Per token**: 2 × 32 layers × 8 heads × 128 dims × 2 bytes = 131,072 B = **128 KiB**.

**Per sequence**: 8,192 tokens × 128 KiB = 1,048,576 KiB = **1 GiB**.

**16 sequences**: 16 × 1 GiB = **16 GiB**, on top of ~16 GB of bf16 weights (8B × 2 bytes).

**Without GQA** (32 KV heads): 4× larger, 512 KiB per token, **64 GiB** for the same load, which
no longer fits next to the weights on an 80 GB card.

Takeaway: within the same 16 GiB KV budget, GQA's 4× saving is the difference between 16 and 4
concurrent 8k requests. FP8 KV would halve the GQA figure again to 8 GiB.


### Will a 70B model serve 32 users at 32k context on two 80 GB GPUs?

Llama-3-70B-like config: 80 layers, 8 KV heads, head_dim 128. Target: 32 concurrent users at 32k tokens on 2 × 80 GB GPUs with tensor parallelism. Check feasibility and propose a configuration.

**Solution**

**Weights**: 70e9 × 2 B = 140 GB in bf16, leaving ~20 GB of the 160 GB before any cache or
overhead. FP8 weights: ~70 GB.

**KV per token (bf16)**: 2 × 80 × 8 × 128 × 2 = 327,680 B = **320 KiB**.

**Demand**: 32 × 32,768 = 1,048,576 tokens × 320 KiB = **320 GiB**. Impossible as stated, even
before weights.

**Best case on this hardware**: FP8 weights (70 GB) + FP8 KV (160 KiB = 163,840 B per token). Allow
~15 GB for activations and runtime, leaving ~75 GB for KV: 75e9 / 163,840 ≈ **458k tokens**, i.e.
about 14 users at full 32k, or 32 users averaging ~14.3k tokens.

**Recommendation**: measure the real context-length distribution (most chats are far below the
maximum), cap context or use admission control, run FP8 weights and KV after an accuracy check, and
add replicas (data parallelism) or GPUs if the p95 context really is 32k. Tensor parallelism splits
both weights and KV heads across the two GPUs (4 KV heads each) and needs NVLink-class bandwidth.


### What prompt caching saves on a shared 6,000-token prefix

An assistant sends a 6,000-token system prompt plus tool definitions on every call, followed by a ~300-token user turn. 100 calls arrive within five minutes. Using cache multipliers of 1.25× for a write and 0.1× for a read, estimate the input-cost saving on the prefix, and the compute a self-hosted 8B model avoids.

**Solution**

**Without caching**: 100 × 6,000 = 600,000 billed prefix tokens.

**With caching**: first call writes, 6,000 × 1.25 = 7,500; the other 99 read, 99 × 6,000 × 0.1 =
59,400. Total **66,900** token-equivalents, an **≈89% saving** on the prefix.

**Self-hosted view**: prefill costs ≈ 2 × params × tokens = 2 × 8e9 × 6,000 ≈ 9.6e13 FLOPs per
request. At an effective 400 TFLOP/s that is ~0.24 s of GPU time and of time-to-first-token per call
saved by a prefix-cache hit.

**Design consequence**: keep the prefix byte-identical. A timestamp or user name injected at the top
of the system prompt makes every request a miss. Check the provider's minimum cacheable length and
read the cache-hit fields in the usage response to confirm hits.


## What changed recently

- **Jul 2026: Prefix caching for hybrid recurrent-state models.** For Kimi K3, whose Kimi Delta Attention layers keep a fixed-size recurrent state between periodic full-attention layers, vLLM caches prefixes by copying that state at chosen boundaries: snapshots at fixed intervals (such as every 32K tokens) plus prompt ends, or only once a prefix is seen twice; the feature is off by default for K3. Block-hash prefix caching does not carry over to recurrent state, so interviewers ask how you would place snapshots and what they cost. [Source](https://vllm.ai/blog/2026-07-27-k3)
- **Apr 2026: DeepSeek-V4 shrinks KV for million-token contexts.** DeepSeek-V4 combines compressed attention (token groups summarised at 1/4 and 1/128 granularity), top-k sparse selection and a 128-token local window; vLLM estimates about 9.6 GiB of bf16 KV per sequence at 1M tokens versus about 84 GiB for a V3.2-style stack, and the V4 paper reports V4-Pro needing 10% of V3.2's KV cache at that length. The per-token formula 2 × layers × kv_heads × head_dim no longer describes frontier models, so expect architecture-specific capacity questions. [Source](https://vllm.ai/blog/2026-04-24-deepseek-v4)
- **Apr 2026: FP8 KV cache: a long-context accuracy trap and a break-even point.** vLLM found that FP8 attention on Hopper dropped 128k needle-in-a-haystack accuracy from 91% to 13% because of imprecise accumulation over long contexts; two-level FP32 accumulation restored 89% at some prefill cost. Even after the fixes, single-request decode with FP8 KV only beat BF16 above roughly 7k tokens for Llama-3.1-8B on an H100. 'Quantise the KV cache' now needs long-context evals and a context-length threshold in the answer. [Source](https://vllm.ai/blog/2026-04-22-fp8-kvcache)
- **Oct 2025: LMCache: a KV layer outside the GPU.** LMCache stores KV caches from vLLM and SGLang in CPU memory, local storage or remote stores and shares them across requests and engines, serving both prefix reuse and prefill/decode transfer, with up to 15× throughput reported on multi-round QA and document analysis. KV caches are now a managed data tier with eviction, transfer bandwidth and hit-rate trade-offs. [Source](https://arxiv.org/abs/2510.09665)
- **Feb 2025: Mooncake wins FAST '25 with KV-centric disaggregation.** Moonshot AI's Mooncake, the serving platform behind Kimi, separates prefill and decode clusters and pools the cluster's under-used CPU, DRAM, SSD and NIC resources into a distributed KV cache with a cache-aware scheduler, handling 115% more requests on A800 and 107% more on H800 clusters in production. It is the canonical citation for trading storage for recomputation in long-context serving. [Source](https://www.usenix.org/conference/fast25/presentation/qin)

## Pitfalls

- Saying the cache stores queries or attention scores; it stores keys and values per layer and KV head.
- Sizing the cache with the number of query heads, or forgetting the factor of 2 for K and V or the layer count.
- Estimating cache size from parameter count; it is set by layers × kv_heads × head_dim, so similar-sized models can differ several-fold.
- Assuming every user sits at maximum context, or mixing GB and GiB in capacity sums.
- Believing the KV cache speeds up prefill of a new prompt; only cross-request prefix caching avoids recomputing a shared prefix.
- Confusing prompt/prefix caching (exact token prefix, same output distribution) with semantic response caching (similar query, reused answer).

## How interviewers probe it

- Give a config and ask for the cache size at a stated context and concurrency; then ask what changes with FP8 KV, GQA or a 128k window.
- Why is decode memory-bandwidth-bound, and why does batching help weights but not KV reads?
- Explain PagedAttention: the fragmentation problem, block tables, copy-on-write for beams and shared prefixes.
- How would you structure prompts and tools to maximise provider cache hits, and how do you verify hits in production?
- Coding follow-up: add a KV cache to a generation loop and prove it matches full recomputation (position offsets, causal mask, compare logits within tolerance in eval mode).
- Compare MQA, GQA and MLA for quality, cache size and serving complexity; why did most open-weight models adopt GQA?

## Reading

- [Transformer Inference Arithmetic](https://kipp.ly/transformer-inference-arithmetic/) (Blog, 40 min, Core): The canonical back-of-envelope treatment of KV memory, capacity and memory- vs compute-bound latency.
- [Efficient Memory Management for Large Language Model Serving with PagedAttention](https://arxiv.org/abs/2309.06180) (Paper, 45 min, Core): Origin of paged KV allocation and copy-on-write prefix sharing in vLLM.
- [GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints](https://arxiv.org/abs/2305.13245) (Paper, 25 min, Core): Defines grouped-query attention and shows how to uptrain it from a multi-head model.
- [Fast Transformer Decoding: One Write-Head is All You Need](https://arxiv.org/abs/1911.02150) (Paper, 30 min, Deep): The multi-query attention paper; frames decoding cost as memory traffic.
- [DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model](https://arxiv.org/abs/2405.04434) (Paper, 40 min, Deep): Read the multi-head latent attention section for the low-rank KV compression design.
- [Automatic Prefix Caching (vLLM design docs)](https://docs.vllm.ai/en/latest/design/prefix_caching.html) (Docs, 15 min, Core): Concise description of block hashing and LRU eviction for cross-request prefix reuse.
- [Prompt caching (Claude API docs)](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) (Docs, 20 min, Intro): A concrete hosted prompt-caching contract: prefix rules, TTLs, pricing multipliers and minimum lengths.
- [The State of FP8 KV-Cache and Attention Quantization in vLLM](https://vllm.ai/blog/2026-04-22-fp8-kvcache) (Blog, 20 min, Core): Real numbers on FP8 KV: a long-context accuracy collapse traced to accumulation precision, its fix, and the context length below which BF16 is faster.

## Practise this topic

- [Compare multi-head, multi-query and grouped-query attention, and latent attention if you know it. Why did most recent open-weight models adopt GQA, and what…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-04.md)
- [What is stored in the KV cache and why does it exist? Estimate the cache memory for a model with 32 layers, 8 KV heads and head dimension 128, in bf16, serving…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-05.md)
- [What problem does PagedAttention solve, and how does it enable prefix sharing?](https://gurkanozkan.ai/learn/questions/applied-llm-srv-03.md)
- [How do provider prompt caching and self-hosted prefix caching work, how do you structure prompts to benefit, and how is a semantic response cache different?](https://gurkanozkan.ai/learn/questions/applied-llm-srv-06.md)
- [Will a 70B dense model serve 32 concurrent users at 32k context on two 80 GB GPUs? Explain tensor, pipeline and data parallelism along the way.](https://gurkanozkan.ai/learn/questions/applied-llm-srv-12.md)
- [A PyTorch notebook trains a small transformer, but the loss plateaus high and evaluation numbers look wrong. Find the bugs. Follow-up: add a KV cache to its…](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-10.md)
- [What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually…](https://gurkanozkan.ai/learn/questions/research-kv-cache-035.md)
- [Write the attention formula. Explain the time and memory complexity in sequence length, why scaling by √d matters, and how a KV cache changes decoding cost.](https://gurkanozkan.ai/learn/questions/mle-self-attention-cost-and-the-kv-cache-15.md)
- [What limits LLM decode throughput, and how do continuous batching, paged KV cache, quantisation and speculative decoding help?](https://gurkanozkan.ai/learn/questions/mle-llm-serving-efficiency-63.md)
- [You are asked to serve a hybrid model with 48 layers: 36 Gated DeltaNet (linear-attention) layers and 12 full-attention layers with 2 KV heads of dimension…](https://gurkanozkan.ai/learn/questions/recent-a-kvcache-01.md)
- [Your team serves a large MoE reasoning model with long prompts and long outputs, and p95 inter-token latency spikes whenever big prompts arrive. Someone…](https://gurkanozkan.ai/learn/questions/recent-a-inference-01.md)
- [A document-QA product re-sends the same 60k-token contract across many sessions spread over hours, so GPU prefix-cache hits are rare. Would you offload KV…](https://gurkanozkan.ai/learn/questions/recent-a-kvcache-02.md)
- [Several 2025–2026 open models mix linear-attention layers (for example Gated DeltaNet or Kimi Delta Attention) with a minority of full-attention layers…](https://gurkanozkan.ai/learn/questions/recent-a-dl-03.md)
- [Compare DeepSeek's Native Sparse Attention and DeepSeek Sparse Attention (in V3.2-Exp). What does each make sparse, where does the speed-up come from, and how…](https://gurkanozkan.ai/learn/questions/recent-a-eff-01.md)
- [You are moving about 3,000 concurrent coding agents from a managed API to a self-hosted open model served with vLLM on Kubernetes. Why does a standard…](https://gurkanozkan.ai/learn/questions/recent-b-mlops-02.md)
- [You must serve a DeepSeek-style mixture-of-experts model (hundreds of billions of parameters, 256 routed experts, MLA attention) for an agentic coding product…](https://gurkanozkan.ai/learn/questions/recent-b-serving-01.md)
- [Qwen3-Next and Qwen3.5 follow every three Gated DeltaNet (linear-attention) layers with one gated full-attention layer. What does a linear-attention layer keep…](https://gurkanozkan.ai/learn/questions/recent-b-transformers-01.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
