The KV cache is the short-term memory a transformer builds for every token it has already read, and it is the reason a 128k context window is a memory bill and not just a pricing tier. Once you can compute how many bytes one token costs, a surprising number of product questions answer themselves: why long chats slow down, why concurrency drops when prompts grow, and why a provider charges differently for cached input.
This is the KV cache explained for people who ship applications, not people who write attention kernels. You do not need the matrix algebra. You need the formula, three worked sizes, and a list of symptoms that point back to the cache. If the transformer vocabulary is new, skim Transformers explained for builders first.
What is actually stored
In each attention layer, every token produces a key vector and a value vector. When the model generates the next token, it compares a new query against the keys of all previous tokens and mixes their values. The previous tokens’ keys and values never change, so instead of recomputing them at every step the engine keeps them in GPU memory. That stored collection is the KV cache.
Two clarifications save a lot of confusion. The cache does not store your text; it stores per-layer tensors derived from the text. And it is per request: two users with different prompts have separate caches, which is why serving many users at once is mostly a memory-allocation problem.
Why decoding without it would be painful
Without a cache, generating token 1,000 would require re-running attention projections for all 999 earlier tokens, then again for token 1,001. Work per step grows with sequence length and total work grows roughly quadratically. With the cache, each step computes keys and values only for the newest token and reads the rest from memory. You trade compute for memory, and memory is the scarcer resource on a GPU.
The per-token formula and three worked sizes
Bytes per token = 2 (K and V) × layers × KV heads × head dimension × bytes per element. The number of KV heads is the lever that changed in recent architectures: grouped-query attention shares each key/value head among several query heads, which shrinks the cache without changing the model’s width much. All sizes below assume an FP16 cache (2 bytes per element) and are illustrative, so read your model’s config for exact values.
| Architecture (illustrative) | Layers × KV heads × head dim | Per token | At 32k tokens, one request |
|---|---|---|---|
| 7B-class, full multi-head attention | 32 × 32 × 128 | 512 KiB | 16 GiB |
| 8B-class, grouped-query (8 KV heads) | 32 × 8 × 128 | 128 KiB | 4 GiB |
| 70B-class, grouped-query (8 KV heads) | 80 × 8 × 128 | 320 KiB | 10 GiB |
Read that last column carefully. A single 32k-token conversation on an older multi-head 7B model can hold more memory than the model’s own weights occupy in FP8. On a 70B model, ten such conversations need 100 GiB of cache before you count weights, which is why large-context workloads end up on multi-GPU replicas.
From here, concurrency is division. If 50 GiB of an 80 GiB card is free for cache and the 8B-class model above holds an average of 6,000 tokens per live request (about 750 MiB each), you can keep roughly 65 requests resident. Change the average prompt to 20,000 tokens and the number falls to about 20.
Paging: why memory fragmentation mattered
Early servers reserved one contiguous buffer per request sized for the maximum possible length. Most requests finished far short of that, so large fractions of memory sat reserved but unused. The PagedAttention paper borrowed the operating-system idea of fixed-size pages: the cache is split into blocks, allocated as the sequence grows, and looked up through a block table. Waste drops to the unfilled tail of the last block, and sequences that share a prefix can point to the same blocks.
That sharing is the foundation of prefix caching. vLLM’s automatic prefix caching keeps the blocks of finished requests around and reuses them when a new request starts with the same tokens, so the shared prompt part skips prefill. The docs are explicit that this speeds up processing of the prompt, not the generation of new tokens. Hosted equivalents are covered in the prompt caching guide.
Ways to shrink or stretch the cache
- Pick a GQA or multi-query model. The cheapest saving is chosen before you deploy: a model with 8 KV heads has a quarter of the cache of one with 32.
- Quantize the cache. Storing keys and values in FP8 halves the footprint relative to FP16, with a quality cost you must measure on long-context tasks. See quantization for LLM inference for the evaluation protocol.
- Cap context honestly. Set the server’s maximum length to your real p99 plus a margin, not to the model’s advertised limit.
- Trim history. Summarize or drop old turns and tool outputs. A 40-turn agent trace with 8 KB of tool JSON per turn is 320 KB of text before the next question.
- Share prefixes. Put static instructions first so that the system prompt and tool schema are cached once, not recomputed for every request.
- Shard across GPUs. Tensor parallelism splits heads, and with them the cache, across cards; it raises capacity at the cost of interconnect traffic.
If you are weighing a long-context model against retrieval, remember that the answer has a hardware term: stuffing 100k tokens per request multiplies cache pressure by roughly 16 compared to a 6k-token RAG prompt. LLM context windows explained covers the quality side of the same trade.
Symptoms that point back to the cache
| What you see | Likely cache cause | First move |
|---|---|---|
| Throughput collapses when users paste long documents | Average tokens per request rose; fewer sequences fit | Lower max length or route long inputs to their own pool |
| Sporadic multi-second pauses on running streams | Preemption: evicted sequences are recomputed | Reduce concurrency cap; add replica |
| Time to first token is great on warm prompts, bad on new ones | Prefix cache hit on static prefix, miss on dynamic part | Move volatile text to the end of the prompt |
| OOM at startup with a big context setting | Cache pre-allocation sized to max length | Lower the max model length or raise memory utilization carefully |
| Agent latency grows linearly with turn count | History is re-prefilled every turn | Keep prefix stable; trim tool outputs |
What to take back to your team
- Ask your inference owner for the bytes-per-token figure of every model you run. It should live next to the model card in your registry.
- Plot live KV usage and preemptions on the same dashboard as latency, as outlined in the observability stack guide.
- Budget context per feature: a support bot with a 6k-token cap and a contract-review tool with a 60k cap should not share a pool.
- When someone proposes “just use the longer context model,” ask what it does to resident sequences per GPU before you ask what it does to quality.
For the operational side, the settings that turn this arithmetic into flags are in the vLLM serving guide, and the latency consequences of a full cache are traced in LLM batching and latency.
FAQ
What is a KV cache in an LLM?
It is stored key and value tensors for every token the model has already processed, kept per layer in GPU memory so that generating each new token does not recompute attention inputs for the whole history.
How do I calculate KV cache size?
Multiply 2 (keys and values) by the number of layers, KV heads, head dimension, and bytes per element, then by the number of tokens. An 8B-class grouped-query model in FP16 uses about 128 KiB per token, so 32k tokens take roughly 4 GiB.
Why does a longer context window reduce how many users a GPU can serve?
Cache size grows linearly with tokens per request. Longer prompts mean each live request holds more memory, so fewer fit alongside the model weights, and the server must queue or preempt the rest.
Is the KV cache the same as prompt caching?
No. The KV cache is the in-memory structure the model uses during a request. Prompt caching is a feature that keeps and reuses the cache for a repeated prefix across requests, lowering latency and, on hosted APIs, input cost.
Can I quantize the KV cache?
Many inference engines support lower-precision cache formats such as FP8, which halves memory versus FP16. The effect on accuracy depends on the model and task, so test long-context and retrieval-heavy prompts before enabling it.
AI Generated Apps AI Code Learning Technology
