KV cache and prefix caching
medium 40 minWhile a model writes, it saves the key and value vectors of every token it has already seen, so each new token costs one small step instead of a pass over the whole text.
Theory
Read or listen first. About 3 min.
What it is
A language model writes one token at a time. To choose the next token, every layer of the model runs attention: the newest token asks a question (its query) and compares it with a label (a key) of every earlier token, then mixes their contents (their values). The KV cache is the store of those keys and values, one pair per token, per layer, per key-value head.
Keys and values of an earlier token never change once they are computed, because a token can only look backwards. So the model computes them once, saves them, and on every later step computes keys and values for the one new token only. That is the whole trick.
Prefix caching stretches the same idea across requests. If many requests start with the same tokens, such as a long system prompt, the saved keys and values of that start can be kept and reused. Engines such as vLLM and SGLang do this inside one server. Model providers sell the same idea as prompt caching: cached input tokens are billed at a fraction of the normal price.
Why it exists
Without a cache, writing token 1,000 would mean recomputing keys and values for the 999 tokens before it, and then token 1,001 would repeat almost all of that again. Total work grows with the square of the length. With a cache, each step adds one token's worth of new work, and the old work is only read back from memory.
The price is memory. On Qwen3-8B, one token's cache takes 144 KiB, so one chat of 8,192 tokens takes 1.125 GiB. On an 80 GB GPU that leaves room for a few dozen such chats at once, and that number, not the weights, usually decides how many users one GPU can serve. Prefix caching then saves both compute and memory, because one copy of a shared start can serve many requests.
A short history
2017
"Attention Is All You Need" (arXiv, 12 June 2017) introduces the Transformer, where every token attends to keys and values of the others.
2019
Noam Shazeer's multi-query attention paper (arXiv, 6 November 2019) names the memory bandwidth of loading keys and values as the bottleneck of step-by-step decoding, and shares one key-value head across all query heads.
2023
The GQA paper (arXiv, 22 May 2023) proposes grouped-query attention, between one key-value head and one per query head. In June the vLLM blog introduces PagedAttention, and the paper follows on 12 September 2023 (SOSP 2023).
2023
SGLang's paper (arXiv, 12 December 2023) introduces RadixAttention: a radix tree of cached prefixes with least-recently-used eviction of leaves.
2024
DeepSeek-V2 (arXiv, 7 May 2024) introduces multi-head latent attention and reports a 93.3% smaller KV cache than its earlier 67B model. OpenAI announces automatic prompt caching on 1 October 2024, and Anthropic's prompt caching becomes generally available in December 2024.
Inside this chapter
Chapter sources- Token
- A piece of text the model reads or writes, often part of a word.
- Query, key, value
- Three vectors made from each token in each attention head. The query asks, keys are compared with it, values are mixed by the result.
- KV cache
- The saved keys and values of tokens already processed, kept in GPU memory for the rest of the request.
- Prefill
- The first phase: all prompt tokens are processed at once and their keys and values are written to the cache.
- Decode
- The second phase: one new token per step, reading the whole cache each time.
- KV head
- A set of keys and values shared by one or more query heads. Fewer KV heads mean a smaller cache.
- Block or page
- A fixed number of tokens' keys and values stored together, for example 16 tokens. Engines manage memory in blocks.
- Block table
- A list per request saying which physical blocks hold its tokens, in order. Like a page table in an operating system.
- Prefix cache hit
- Leading blocks of a new request that are already in the cache, so they need no prefill.
- TTFT and TPOT
- Time to first token, set mostly by prefill, and time per output token, set by decode.
How it works
Step through the idea, or press Play.
Prefill. All prompt tokens at once, keys and values written
Understand it
Start here
A paper chain workshop
Asha makes paper chains for a school fair. Every link carries one word, and a chain spells a message. To write the next word well, Asha reads every link already on the chain. Lee helps hang finished chains on a wall of hooks. Customers Noor, Sam and Max bring cards with the messages they want.
Reading the chain is cheap. Remaking it is what costs. A shared start hangs once.
Recall
Attention in one minute
Inside each layer, every token turns into three vectors through three learned matrices: a query, a key and a value. To update token t, the model takes token t's query, scores it against the keys of tokens 1 to t, turns the scores into weights with softmax, and adds up the values with those weights. A model has many heads doing this side by side, and dozens of layers stacked.
One head, one new token
Why do old keys and values not change? A model that writes text uses a causal mask: a token may look at itself and earlier tokens, never later ones. So the inputs of layer 1 for token 5 are the same at step 6, step 60 and step 600. The same holds layer by layer. That is what makes caching exact, not an approximation.
One decode step in one layer
The saving
Without and with a cache
Key and value projections for n new tokens after a prompt of p
# Count key and value projections, no model needed.def projections(prompt, new, cache): if cache: return prompt + new # each token once return sum(range(prompt, prompt + new)) # all earlier tokens, every stepfor p, n in [(32, 224), (1000, 500), (8000, 1000)]: a, b = projections(p, n, False), projections(p, n, True) print(f"prompt {p:5}, write {n:5}: no cache {a:12,} cache {b:7,} ratio {a / b:7.1f}")What the toy model in the Code tab measures
| Run | Multiplications | Same output? |
|---|---|---|
| No cache, 32 prompt tokens, 224 new | 4,643,072 | reference |
| KV cache, same run | 561,408 | yes, difference 0.0 |
Two phases
Prefill and decode
A request has two phases that behave very differently. Prefill processes all prompt tokens together. That is many large matrix multiplications, so the GPU's arithmetic units are busy: prefill is compute-bound. Decode makes one token per step. For each step the GPU must read every weight and the whole cache of each request in the batch, but does little arithmetic per byte read: decode is memory-bandwidth-bound.
One chat request
Prefill against decode
| Prefill | Decode | |
|---|---|---|
| Tokens per step | the whole prompt | one per request |
| Limited by | arithmetic | memory bandwidth |
| KV cache | written | read in full, one entry appended |
| User sees | time to first token | time per output token |
| Batching helps by | little: already full | a lot: one weight read serves many requests |
| Prefix caching saves | the matched part | nothing |
A floor for one decode step
Size
How big is the cache?
Bytes per token, then per request
Worked: Qwen2.5-72B-Instruct at 8,192 tokens
KV cache of open models, 16-bit, from their config.json
| Model | Layers | KV heads x size | Per token | 8,192 tokens | 32,768 tokens |
|---|---|---|---|---|---|
| Qwen3-8B | 36 | 8 x 128 | 144 KiB | 1.125 GiB | 4.5 GiB |
| Qwen3-32B | 64 | 8 x 128 | 256 KiB | 2 GiB | 8 GiB |
| Qwen2.5-72B | 80 | 8 x 128 | 320 KiB | 2.5 GiB | 10 GiB |
| Mistral-7B v0.1 | 32 | 8 x 128 | 128 KiB | 512 MiB, window 4,096 | 512 MiB |
| gpt-oss-120b | 36: 18 full, 18 window 128 | 8 x 64 | 36 KiB on full layers | about 0.29 GiB | about 1.13 GiB |
| DeepSeek-V3 | 61 | one latent of 512 + 64 | 68.6 KiB | 0.54 GiB | 2.1 GiB |
Shrink it
Fewer key-value heads: MHA, MQA, GQA, MLA
The formula has four factors, and each has an idea that attacks it. The oldest is to cut H_kv. In standard multi-head attention every query head has its own keys and values. Multi-query attention shares one key-value head across all query heads. Grouped-query attention sits in between: groups of query heads share one. The GQA paper reports quality close to multi-head attention at speed close to multi-query attention.
Who shares keys and values
Every factor has a lever
| Factor | Lever | Example | Cost |
|---|---|---|---|
| KV heads | grouped or multi-query attention | Qwen3: 8 KV heads for 32 query heads, 4 times smaller | set at training time |
| Head size x heads | latent attention: store one compressed vector | DeepSeek-V3: 576 numbers per layer instead of 40,960 | extra math, special kernels |
| Tokens | sliding window on some layers | gpt-oss: half the layers keep only 128 tokens | those layers forget older text |
| Bytes per number | 8-bit cache | FP8 in vLLM with kv_cache_dtype | small accuracy risk, calibrate scales |
| Copies | prefix sharing | one system prompt for many requests | only helps identical starts |
DeepSeek-V3: latent attention against plain multi-head
Deeper treatment of these variants and of attention kernels lives in attention kernels, KV heads and long context. Quantization formats are covered in quantization.
Capacity
Memory decides the batch size
A GPU's memory holds three things: the weights, the cache blocks of all running requests, and working space for the current step. Whatever is left after weights and working space is the cache pool. Divide it by the cache per request and you have the most requests that can run at once.
One GPU serving many chats
How many 8k chats fit? Qwen3-8B on one 80 GB GPU
Same GPU, same model, different plans
| Context per request | 16-bit cache | 8-bit cache |
|---|---|---|
| 2,048 tokens | about 177 requests | about 355 |
| 8,192 tokens | about 44 | about 88 |
| 32,768 tokens | about 11 | about 22 |
| 131,072 tokens | about 2 | about 5 |
Paging
PagedAttention and block tables
Early servers reserved one contiguous slab per request, sized for the longest possible answer. Most of it stayed empty, and free memory broke into gaps too small to use. The vLLM team's June 2023 post put the waste in existing systems at 60% to 80% of KV memory, and under 4% with their approach.
PagedAttention borrows from operating systems. The cache is cut into fixed blocks, each holding the keys and values of a fixed number of tokens. A request gets blocks one at a time as it grows, from anywhere in the pool, and a block table lists them in order. The attention kernel follows the table. A block can appear in several tables, which is how requests share a prefix or the branches of parallel sampling.
Sam's request, 40 tokens, blocks of 16
| Logical block | Tokens | Physical block | Filled |
|---|---|---|---|
| 0 | 1 to 16 | 3 | 16 of 16 |
| 1 | 17 to 32 | 9 | 16 of 16 |
| 2 | 33 to 40 | 4 | 8 of 16, grows as tokens arrive |
The life of one block
What if the pool runs out in the middle of decoding? The engine preempts a request: it frees that request's blocks and later either recomputes them with a fresh prefill or brings them back from CPU memory. Users see this as a sudden pause. A full cache shows up as latency spikes before it shows up as errors. Scheduling around a full pool is covered in batching, decoding and serving caches.
Reuse
Prefix caching: hash the blocks
Once the cache lives in blocks, reuse across requests is a lookup. vLLM's design gives every full block a hash made of three things: the hash of the block before it, the token IDs in the block, and extra keys such as a LoRA adapter ID, image hashes or a cache salt. Because each hash includes its parent, a block can only match when everything before it matched too.
import hashlibdef block_hashes(tokens, block=4, salt=""): parent, out = salt, [] for i in range(0, len(tokens) // block * block, block): text = parent + "|" + " ".join(tokens[i:i + block]) parent = hashlib.sha256(text.encode()).hexdigest()[:8] out.append(parent) return out # a partly filled last block gets no hasha = "you help a bike shop be kind my brake squeaks".split()b = "you help a bike shop be kind do you fix tyres".split()c = "09:41 you help a bike shop be kind my brake squeaks".split()print(block_hashes(a))print(block_hashes(b))print(block_hashes(c)) # one token in front: nothing matchesRequest B after request A
What one hit saves on Qwen3-8B
Lay out a prompt for hits
| Position | Put here | Never here |
|---|---|---|
| First | Tool definitions in a fixed order, system prompt, policy text | Timestamps, request IDs, user names |
| Middle | Long shared documents, examples | Lists shuffled per request, JSON with unstable key order |
| Last | The conversation, appended only | Edits to earlier turns |
| Very last | Today's date, the user's message, retrieved snippets |
Sharing patterns
Radix trees
SGLang stores cached prefixes in a radix tree: a tree whose edges are labelled with runs of tokens. A path from the root spells a prefix, and the node at its end points at the cached keys and values. A new request walks down as far as its tokens match, reuses everything on that path, and adds a new branch for the rest. Agent loops, few-shot prompts, tree search and multi-turn chat all produce this shape.
Three conversations in one tree
Two ways to find a cached prefix
| vLLM | SGLang | |
|---|---|---|
| Index | hash table from block hash to block | radix tree of token runs |
| Unit | full blocks | pages of one token in the paper |
| Match | leading blocks, one by one | walk down the tree |
| Eviction | LRU free queue, a request's last block first | LRU, leaves first |
| Isolation | cache salt in the first block's hash | not covered in the paper |
| Scheduling idea | not part of the hashing design | longer matches first for batch work |
Both reach the same goal by different roads. The SGLang paper reports up to 6.4 times higher throughput than other systems of the time across its workloads.
Eviction
When the pool is full
What a typical engine does
- 1
Count users per block
Every block has a reference count: the number of running requests reading it. A block with a count above zero is never evicted.
- 2
Free means cached
When a request ends, its full blocks keep their hashes and join a free queue. They are free to reuse and still match until someone takes them.
- 3
Oldest unused first
New allocations take from the front of that queue: the least recently used block. If it was cached, its hash is dropped.
- 4
Ends before starts
vLLM adds a finished request's blocks to the queue in reverse order, so its last blocks go first. SGLang evicts leaves first. Both keep shared starts longest.
- 5
Still full
If every block is in use, the scheduler waits, or preempts a running request and recomputes it later.
Too little pool
Hits fall as soon as traffic rises, because shared blocks are evicted between requests.
Too many tenants
500 different 6,000-token prompts on Qwen3-8B need about 442 GB of cache. No single GPU holds that.
Bursty traffic
A prompt used once an hour is gone by its next use unless a slower tier keeps it.
Long answers
Decode-heavy work gains little: prefix caching only removes prefill.
Providers
Prompt caching in model APIs
Hosted APIs run the same mechanism on their own servers and pass part of the saving on. You pay less for input tokens that hit, and the first token arrives sooner. The rules differ in three ways: whether caching is automatic, how long entries live, and what a write and a hit cost. These change often, so every fact below carries the date we read it.
Prompt caching rules, last checked 27 November 2026
| Anthropic | OpenAI | Google Gemini | |
|---|---|---|---|
| Turn it on | cache_control on blocks, or one top-level field for automatic | automatic on supported models | implicit by default on 2.5 and newer; explicit caches on some models |
| Order | tools, then system, then messages | hash of the first tokens, tools included | common content first |
| Smallest prompt | 512 to 4,096 tokens by model | 1,024 visible tokens on GPT-5.6 and later | 2,048 on 2.5 models, 4,096 on newer |
| Lifetime | 5 minutes, or 1 hour; refreshed on each hit | 30 minutes default on GPT-5.6 and later, 12 hours option | explicit: 60 minutes by default, settable |
| Cache read price | 0.1x input on most models, lower on some | 0.1x on GPT-5.6 and later | cached tokens 90% off on Vertex AI |
| Cache write price | 1.25x for 5 minutes, 2x for 1 hour | no surcharge stated | standard input; explicit adds storage per hour |
| Isolation | never across organizations; per workspace on the Claude API | never across organizations | never across projects on Vertex AI |
| Shown in | cache_read_input_tokens, cache_creation_input_tokens | cached_tokens | total_cached_tokens |
Worked cost: 10,000 requests in an hour, 6,000 shared tokens each
Caching was enabled but the bill did not drop
Tiers
Quantised caches and offloading
Two more levers make room. An 8-bit cache stores each number in one byte instead of two, which halves the per-token size and doubles the tokens that fit. vLLM supports FP8 caches with kv_cache_dtype and recommends calibrated scales for the best accuracy. Offloading moves blocks that are not needed right now to CPU memory, local disk or a shared store, and brings them back instead of prefilling again.
Hot, warm and cold blocks
Where cached blocks can live
| Tier | Reach | Shared by | Example |
|---|---|---|---|
| GPU memory | the running step | one replica | vLLM and SGLang prefix caches |
| CPU memory | a copy over PCIe | one machine | SGLang HiCache level 2 |
| Disk or remote store | network or local disk | many replicas, if configured | SGLang HiCache level 3 with Mooncake and others, LMCache |
Routing
Send each request to its cache
A cache only helps the replica that holds it. With ten replicas and random routing, a shared prefix gets computed ten times and each replica keeps its own copy. A cache-aware router looks at the first blocks of a prompt, or at a session or tenant ID, and sends the request where those blocks already are, unless that replica is overloaded. OpenAI's guide says the same about its own service: requests are routed by a hash of the first tokens, and very busy prefixes overflow to other machines.
Many tenants, one system prompt each
Safety
Shared caches can leak
A cache hit is faster than a miss, and that timing difference can reveal what someone else sent. In "Auditing Prompt Caching in Language Model APIs" (ICML 2025), Gu and co-authors detected caching through timing and found global cache sharing across users at seven providers, including OpenAI at the time. Providers now state their isolation, as the table above shows.
Bugs in cache memory are worse than timing. Cloudflare reported on 26 October 2026 that, from 27 August to 9 September 2026, 155 responses from one model on Workers AI contained data from other customers' requests. Their write-up names two causes: a prefill cache pool smaller than the model's context window, and an SGLang bug in disaggregated mode where an over-length request read stale cache pages. They resized the pool, patched SGLang to reject such requests before any transfer, and sent the fix upstream.
Do
- Salt the cache per tenant, as vLLM's cache_salt does
- Check that the cache pool can hold the longest allowed request
- Clear or overwrite blocks before reuse where the engine allows it
- Use a cryptographic block hash in multi-tenant setups
Avoid
- One global cache across customers with secrets in prompts
- Non-cryptographic block hashes when tenants share a server
- Trusting that a rejected request read nothing
- Assuming the KV cache is a response cache that stores answers
Debugging
Failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Hit rate near zero | Changing text early in the prompt: time, IDs, tool order | Stable first, volatile last; sort tools and JSON keys |
| Out of memory under load | Planned for weights only | Budget cache per request times concurrency |
| Sudden pauses mid-answer | Pool full: preemption and recompute | Fewer concurrent requests, smaller cache, more memory |
| Hits fall at peak | Shared blocks evicted between uses | Bigger pool, offload tier, cache-aware routing |
| Agent gets slower and dearer each turn | History rewritten, so the cache resets | Append-only context; summarise at the end, not in place |
| Answers contain someone else's data | Stale blocks read after a bug | Isolation per tenant, pool sized for max context, patch the engine |
Tools today
What to reach for
Tools, last checked 27 November 2026
| Tool | What it does for the cache |
|---|---|
| vLLM | Paged blocks, automatic prefix caching, FP8 cache, hit-rate metrics |
| SGLang | RadixAttention, HiCache tiers, cache-aware scheduling |
| LMCache | Moves caches out of vLLM and SGLang for reuse and transfer |
| Mooncake | Distributed KV store used as an SGLang HiCache back end |
| NVIDIA Dynamo and llm-d | Disaggregated serving and KV-aware routing |
Measure before you tune. vLLM exposes the counters vllm:prefix_cache_hits and vllm:prefix_cache_queries, both in tokens: the hit rate is the rise in the first divided by the rise in the second. Started with --enable-prompt-tokens-details, it also returns cached_tokens per request.
Summary
The whole topic in one minute.
Attention compares each new token's query with the keys of all earlier tokens and mixes their values. Those keys and values never change, so the model saves them: that is the KV cache. Prefill writes the whole prompt into it at once. Decode adds one token per step and reads everything back, so decode is limited by memory bandwidth, not arithmetic.
The cache size is 2 x layers x KV heads x head size x bytes per number x tokens. Read the first four from the model's config.json. Grouped-query attention, latent attention, sliding windows and 8-bit caches all attack one of those factors. Whatever is left decides how many requests fit next to the weights.
Engines store the cache in fixed blocks with a block table, which ends fragmentation and lets requests share blocks. A prefix cache keys each full block by a hash of its tokens and everything before it, so a hit needs an identical start. Put stable content first and changing content last, evict unused blocks least recently used first, isolate tenants, and route each request to the replica that already holds its prefix.
- Keys and values of earlier tokens never change, so the model saves them: the KV cache.
- Prefill writes the prompt into the cache at once and is compute-bound. Decode adds one token per step, reads the whole cache, and is memory-bound.
- Bytes per token = 2 x layers x KV heads x head size x bytes. Qwen3-8B: 144 KiB, so 1.125 GiB for 8,192 tokens.
- GQA, MQA, latent attention, sliding windows and 8-bit caches each shrink one factor.
- Free memory after weights, divided by cache per request, is your concurrency.
- PagedAttention stores the cache in blocks with a block table: little waste, easy sharing.
- Prefix caching hashes each full block with everything before it. Same prefix, same blocks, free prefill.
- Stable content first, volatile content last, history append-only.
- Evict least recently used blocks that no running request holds. Route each request to its cache, and isolate tenants.
Sources
- Kwon et al., PagedAttention and vLLM (arXiv 2309.06180, SOSP 2023)
- vLLM blog: easy, fast and cheap LLM serving with PagedAttention (20 June 2023)
- vLLM docs: automatic prefix caching design
- vLLM docs: automatic prefix caching
- vLLM docs: quantized KV cache
- Zheng et al., SGLang and RadixAttention (arXiv 2312.07104)
- SGLang docs: HiCache design
- Vaswani et al., Attention Is All You Need (arXiv 1706.03762)
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (arXiv 1911.02150)
- Ainslie et al., GQA (arXiv 2305.13245)
- DeepSeek-V2 and multi-head latent attention (arXiv 2405.04434)
- LMCache (arXiv 2510.09665)
- Qwen3-8B config.json
- Qwen3-32B config.json
- Qwen2.5-72B-Instruct config.json
- Mistral-7B-v0.1 config.json
- gpt-oss-120b config.json
- DeepSeek-V3 config.json
- Anthropic: prompt caching (read 27 November 2026)
- OpenAI: prompt caching guide (read 27 November 2026)
- OpenAI: prompt caching in the API (1 October 2024)
- Google: Gemini API context caching (read 27 November 2026)
- Google: Gemini API pricing (read 27 November 2026)
- Google Cloud: Vertex AI context cache overview (read 27 November 2026)
- Manus: context engineering for AI agents (18 July 2025)
- Gu et al., Auditing Prompt Caching in Language Model APIs (arXiv 2502.07776)
- Cloudflare: cross-request KV cache exposure and remediation (26 October 2026)
- NVIDIA H100 specifications