KV cache explained: memory math, paging, and prefix reuse
The KV cache keeps attention keys and values so a model never recomputes old tokens. How big it gets, why it caps batch size, and how engines page and reuse it.
- Published
- Reading time
- 13 min read
In short
- The KV cache stores the attention keys and values of every token a model has already processed, so each new token costs one forward pass instead of a pass over the whole sequence.
- One token's cache takes 2 x layers x KV heads x head dimension x bytes per value. For Qwen2.5-72B in bf16 that is 320 KiB per token, or 10 GiB for one 32,768-token sequence.
- KV cache memory, not compute, usually decides how many requests a GPU can serve at once. PagedAttention raised that number by removing most of the memory older systems lost to reservation and fragmentation.
- Prefix caching keeps the KV cache of a shared prompt start and reuses it across requests. Provider prompt caching is the same reuse, sold to you as a discount on input tokens.
The KV cache is the memory where a transformer keeps the attention keys and values of every token it has already processed. When the model generates the next token, it computes keys and values for that one token, appends them, and reads everything else from the cache instead of recomputing the whole sequence. The cache trades GPU memory for compute, and on a serving GPU that memory is usually the resource that runs out first.
This deep dive covers what the KV cache stores, how to calculate its size, why it limits how many requests a GPU can serve, and how inference engines page it, share it, and shrink it. If you are choosing an engine, vLLM vs SGLang compares two widely used open-source options. This article explains the mechanism both are built around. For the tools built to run on a single machine, see vLLM vs Ollama.
What the KV cache stores
The KV cache stores two tensors per layer for every token in the sequence: the key and the value that attention computed for it. Every later token attends to those keys and values. Because a token's keys and values never change once computed, the model can keep them and compute only the newest token's pair on each step.
Inference runs in two phases, and the cache connects them.
- Prefill. The model processes every input token in one pass, computes their keys and values, and writes them to the cache. This phase is most of time to first token.
- Decode. The model produces one token per forward pass. Each pass computes the query, key, and value for the new token only, attends over everything in the cache, and appends the new pair.
Without a cache, decoding step n would recompute keys and values for all n previous tokens. With a cache, each step does a fixed amount of new work per layer and reads a growing amount of memory. That is the trade, and it is why decoding is a memory problem. Each step reads the model's weights plus the full cache of every sequence in the batch.
How big the KV cache gets
One token's KV cache takes 2 x layers x KV heads x head dimension x bytes per value. The 2 counts the key and the value. Multiply by the number of tokens for one request, and by the number of concurrent sequences for a batch. Every term comes from the model's config file, so you can size the cache before you rent a GPU.
Take Qwen2.5-7B-Instruct. Its published config lists 28 layers, 28 attention heads, 4 key-value heads, and a hidden size of 3,584, which gives a head dimension of 128. In bf16, each value takes 2 bytes.
per token = 2 x 28 layers x 4 KV heads x 128 dims x 2 bytes
= 57,344 bytes (56 KiB)
32,768 tokens = 57,344 x 32,768
= 1.75 GiB for one full-length sequenceQwen2.5-72B-Instruct has 80 layers, 64 attention heads, 8 key-value heads, and a hidden size of 8,192, according to its config. Its head dimension is also 128. The same formula gives 327,680 bytes, or 320 KiB, per token, and 10 GiB for one 32,768-token sequence.
The key-value head count is the term that architecture choices move most. Grouped-query attention (GQA) lets several query heads share one key-value head. The GQA paper describes "an intermediate (more than one, less than number of query heads) number of key-value heads" and reports quality close to full multi-head attention. Both Qwen models use it, and the saving is large.
| Model (bf16) | KV heads | Per token | One 32,768-token sequence | Same model with full multi-head attention |
|---|---|---|---|---|
| Qwen2.5-7B-Instruct | 4 of 28 | 56 KiB | 1.75 GiB | 12.25 GiB |
| Qwen2.5-72B-Instruct | 8 of 64 | 320 KiB | 10 GiB | 80 GiB |
The last column is the cost without GQA. For the 72B model, one long sequence would need more memory than an entire 80 GB H100 holds. Older models paid that price. The vLLM paper uses OPT-13B as its example, where "the KV cache of a single token demands 800 KB of space" and one 2,048-token request can need 1.6 GB.
Why KV cache memory sets your batch size
KV cache memory usually decides how many requests an engine can run at once. Weights are loaded once and shared by every request, but each request needs its own cache, sized by its own length. Whatever memory remains after the weights and working buffers is the budget for concurrent sequences.
Continue with Qwen2.5-7B. Suppose that after the weights and activation workspace, 40 GiB of GPU memory remains for the cache. At 56 KiB per token, that holds about 749,000 tokens.
| Average tokens per request (prompt plus output) | Requests that fit at once |
|---|---|
| 32,768 | 22 |
| 8,192 | 91 |
| 4,096 | 182 |
| 1,024 | 731 |
Batch size matters because each decoding step reads the weights once, however many sequences share that step. More sequences per step means more tokens produced per read of the weights, which is how a serving GPU turns memory bandwidth into throughput. When the cache is full, the engine has to hold new requests back or free space. vLLM's tuning guide says it "can preempt requests to free up KV cache space," and preempted requests are recomputed later.
Two consequences follow. Long contexts cost concurrency, not only money: one 32,768-token conversation takes the cache space of 32 requests of 1,024 tokens. And any memory the cache wastes lowers throughput directly. That second problem is what PagedAttention was built to solve.
Continuous batching is why cache management matters
Continuous batching schedules work one decoding step at a time, so requests join and leave the batch at every step instead of waiting for the whole batch to finish. It keeps the GPU busy, and it means the KV cache is allocated and freed constantly, at token granularity, while the engine runs.
The idea comes from Orca, presented at OSDI 2022. Orca proposed "iteration-level scheduling" and reported a 36.9x throughput improvement over NVIDIA FasterTransformer at the same latency on GPT-3 175B. Before it, a batch ran until its longest request finished, and short requests sat in the batch doing nothing.
Iteration-level scheduling turns cache management into a hard problem. A request's final length is unknown when it starts. It grows by one token per step, and it can finish at any step. A memory manager that handles this poorly either reserves too much per request or fragments memory as requests come and go.
Fragmentation and PagedAttention
PagedAttention stores the KV cache in fixed-size blocks that do not need to sit next to each other in GPU memory, the way an operating system pages virtual memory. A block table per request maps each logical block of the sequence to a physical block anywhere in the pool, so memory is allocated one block at a time as the sequence grows.
Earlier serving systems kept each request's cache in one contiguous region sized for the longest sequence it might reach. The vLLM paper names three kinds of waste that follow: slots reserved for tokens not yet generated, internal fragmentation from provisioning for the maximum length, and external fragmentation from the memory allocator.
It measured that "only 20.4% - 38.2% of the KV cache memory is used to store the actual token states in the existing systems." The vLLM launch post puts the same finding as 60% to 80% of memory wasted.
With paging, waste is limited to the unfilled part of each sequence's last block. The paper's default block size is 16 tokens, so a sequence wastes at most 15 token slots, and the launch post reports "a mere waste of under 4%." The paper reports 2 to 4 times the throughput of FasterTransformer and Orca at the same latency, with larger gains for longer sequences and larger models.
The block table also makes sharing cheap. Two sequences can point at the same physical block, and a block is copied only when one of them needs to change it. The launch post reports that sharing cut memory use for parallel sampling and beam search by up to 55%, which can mean up to 2.2 times the throughput.
Prefix caching and RadixAttention
Prefix caching keeps KV blocks after a request finishes and reuses them when a later request starts with the same tokens. A shared system prompt, a long document asked about repeatedly, or the earlier turns of a conversation are prefilled once, and later requests start from their new tokens.
vLLM identifies a reusable block by a hash. Its design docs list what goes into it: the hash of the preceding block, the exact tokens in the block, and extra keys such as LoRA adapter IDs, multimodal input hashes, and an optional cache salt. Chaining the parent hash means a block matches only when everything before it also matches, which is exactly the prefix rule. Only full blocks are cached, and when memory is needed, freed blocks are evicted least recently used first.
SGLang's version is RadixAttention. It keeps cached token sequences in a radix tree, so requests that share any prefix share a path through the tree, and it evicts the least recently used leaves. The SGLang paper reports "up to 6.4x higher throughput compared to state-of-the-art inference systems" across its workloads, which lean on structured, repeated prompts.
Prefix caching has firm limits. vLLM's feature docs state that it "only reduces the time of processing the queries (the prefilling phase) and does not reduce the time of generating new tokens." It does nothing when requests share no prefix, and cached blocks compete with live requests for memory, so they are the first thing evicted under load. That is why prompt order matters: context engineering puts stable content first so the shared prefix is as long as possible.
| Technique | What it saves | When it saves nothing |
|---|---|---|
| KV cache within a request | Recomputing past tokens at every decode step | Not applicable: every engine uses it |
| PagedAttention | Memory lost to reservation and fragmentation | One short request on an idle GPU |
| Prefix caching | Prefill time for repeated prompt starts | No shared prefix, or blocks evicted under load |
| Block sharing | Duplicate copies for parallel samples or beams | Requests that generate a single output |
Making the KV cache smaller: quantization and offloading
You can shrink the KV cache by storing it in fewer bits, or stretch it by moving cold blocks to CPU memory or storage. Quantization trades some accuracy for capacity. Offloading trades transfer time and bandwidth for capacity. Both raise the number of tokens you can keep without adding GPUs.
Quantization. vLLM accepts kv_cache_dtype="fp8", with fp8_e4m3 and fp8_e5m2 variants, according to its quantized KV cache docs. One byte per value instead of two halves the cache, which doubles every number in the batch-size table above. The docs are careful about accuracy. Without calibration, the scales default to 1.0. Calibrated scales from llm-compressor are recommended. Some layer types, such as sliding-window attention, are more sensitive and can be kept at full precision with --kv-cache-dtype-skip-layers.
Offloading. vLLM added native offloading of KV blocks to CPU memory in version 0.11.0. The vLLM team's post on the feature reports that loading cached KV from CPU instead of recomputing it reduced time to first token by 2 to 22 times on Llama-3.1-8B-Instruct, depending on prompt size. SGLang's HiCache extends RadixAttention across three tiers, GPU memory, host memory, and external storage, and is turned on with --enable-hierarchical-cache.
Offloading pays off when the same prefixes come back after they would have been evicted from the GPU: long multi-turn sessions, or many users asking about the same documents. It does not make decoding faster, and every transfer uses bandwidth that live requests also need.
Provider prompt caching is KV reuse with a price tag
Provider prompt caching is prefix caching run by the API provider and billed to you as a discount. Providers do not publish their serving internals, but the rules they document match prefix KV reuse: the prompt must match exactly from the first token, there is a minimum length, and entries expire after a few minutes without use.
The prices hint at the economics. Anthropic's prompt caching docs bill a five-minute cache write at 1.25 times the base input price, a one-hour write at 2 times, and a cache read at 0.1 times by default. Reads are cheap because the work of prefill is already done. Writes cost more, and longer retention costs more still, which is consistent with the provider holding memory for your prefix while it waits for you to return.
The rules that make prefix caching work on your own engine apply to the API too: stable content first, nothing that changes per request near the top, and each session sent to the same place. Prompt caching covers the provider-specific details.
What the KV cache means for you in production
If you self-host, KV cache memory is the capacity number to plan around, not GPU count. If you use an API, cached prefixes are the cheapest input tokens you will buy. In both cases, prompt length and prompt order are the controls you have, and they matter more than most model-level tuning.
- Size the cache before you size the fleet. Compute the per-token KV size from the config, multiply by your real average context length, and divide your free memory by it. That number, not the parameter count, predicts how many concurrent users one GPU can serve.
- Watch cache usage and preemption. When the cache fills, engines hold back or preempt requests. Rising time to first token at steady traffic is often a full cache, not a slow model.
- Cap context length on purpose. A 128K-token maximum that nobody needs lets any one request take a large share of the cache.
- Design prompts for prefix reuse. A shared system prompt and tool list at the top of every request is free throughput on an engine with prefix caching, and a discount on an API.
- Test a quantized KV cache on your own evaluation set. The memory gain is certain. The accuracy cost depends on the model and the task.
The cost of all this is complexity in the serving layer. Paging, prefix caching, quantization, and offloading each add settings, and their interactions show up as latency under load rather than as errors. Record cache usage alongside latency, or you will tune the wrong thing.
Frequently asked questions
What is a KV cache in an LLM?
A KV cache is GPU memory where a transformer stores the attention keys and values of every token it has already processed. On each decoding step, the model computes keys and values only for the new token and reads the rest from the cache. That avoids recomputing the whole sequence for every generated token, at the cost of memory that grows with sequence length.
How much memory does the KV cache use?
Per token, the KV cache uses 2 x layers x KV heads x head dimension x bytes per value. Qwen2.5-7B in bf16 needs 56 KiB per token, about 1.75 GiB for a 32,768-token sequence. Qwen2.5-72B needs 320 KiB per token, or 10 GiB for the same length. Multiply by the number of concurrent sequences to size a batch.
What is the difference between the KV cache and prompt caching?
The KV cache holds keys and values for the tokens of one running request. Prompt caching, also called prefix caching, keeps those entries after the request ends so a later request with the same opening tokens can reuse them and skip that part of prefill. Provider prompt caching is the same reuse, run by the API provider and billed as cheaper input tokens.
What is PagedAttention?
PagedAttention is the attention algorithm behind vLLM. It stores the KV cache in fixed-size blocks that can sit anywhere in GPU memory, with a block table per request that maps logical blocks to physical ones. That removes most of the waste from contiguous allocation and lets requests share blocks when they start with the same prefix.
Does the KV cache affect output quality?
A standard KV cache does not change outputs, because the cached keys and values are the same numbers the model would recompute. Techniques that change what is stored can affect quality. Quantizing the cache to fp8 is lossy, and schemes that compress or drop cached tokens change what the model attends to. Test those on your own evaluation set before enabling them.
Why does a longer context reduce throughput?
A longer context reduces throughput because each request occupies more KV cache memory, so fewer requests fit in a batch. Fewer requests per decoding step means fewer tokens produced per read of the model weights. Long prompts also lengthen prefill, which delays the first token for that request and for any request queued behind it.
Sources
- 01Efficient Memory Management for Large Language Model Serving with PagedAttentionarXiv:2309.06180
- 02vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttentionvLLM blog
- 03Orca: A Distributed Serving System for Transformer-Based Generative ModelsUSENIX OSDI 2022
- 04SGLang: Efficient Execution of Structured Language Model ProgramsarXiv:2312.07104
- 05GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsarXiv:2305.13245
- 06Qwen2.5-7B-Instruct configHugging Face
- 07Qwen2.5-72B-Instruct configHugging Face
- 08Automatic prefix caching (design)vLLM docs
- 09Automatic prefix cachingvLLM docs
- 10Optimization and tuningvLLM docs
- 11Quantized KV cachevLLM docs
- 12Inside vLLM's new KV offloading connectorvLLM blog
- 13SGLang HiCache best practicesSGLang docs
- 14Prompt cachingClaude API docs