KV Cache Explained: Why LLM Inference Is Memory-Bound and How to Optimize It
Serving a large language model feels like a GPU compute problem, but in practice inference spends most of its time waiting on memory. The reason has a name: the KV cache. It is the single biggest consumer of GPU memory during generation, and it is why your tokens-per-second number is set by memory bandwidth rather than floating-point throughput. This guide explains what the KV cache is, how to compute its size, why decoding is memory-bound, and the techniques that shrink it.
What the KV Cache Actually Is
Transformer attention works by comparing each new token against all previous tokens. For every token the model has processed, each attention layer computes a key vector and a value vector. When the next token arrives, attention scores it against all the stored keys and mixes the stored values. Without a cache, generating token 5,000 would recompute keys and values for all 4,999 earlier tokens — quadratic work on every step.
The KV cache simply stores those key and value vectors after computing them once. Generating the next token then only needs one forward pass for that token, reading the cached keys and values of everything before it. The cache trades memory for speed: linear memory growth in exchange for avoiding quadratic recomputation. Every production inference server — vLLM, TensorRT-LLM, TGI — maintains one; the differences are in how efficiently they manage it.
Prefill vs. Decode: Two Different Bottlenecks
Generation has two phases with opposite performance profiles. Prefill processes the entire prompt at once, computing keys and values for all prompt tokens in parallel. This phase is compute-heavy: big matrix multiplications, high GPU utilization, fast.
Decode then generates one token at a time. Each step runs a forward pass for a single token, but it must read the entire KV cache from memory to do so. One token of new computation against gigabytes of cached reads. This phase is memory-bandwidth-bound: the GPU’s arithmetic units sit idle while memory delivers the cache. Long generations and long contexts spend the vast majority of their time in decode, which is why decode performance decides your serving throughput.
How Big the Cache Gets
The cache size follows a simple formula:
bytes per token = 2 × layers × kv_heads × head_dim × bytes_per_value
The factor of 2 covers keys and values. Multiply by the sequence length for the full cache of one request.
A worked example with Llama 3.1 8B’s public architecture (32 layers, 8 key-value heads via grouped-query attention, head dimension 128, stored in 16-bit):
2 × 32 × 8 × 128 × 2 bytes = 131,072 bytes, roughly 128 KB per token. A 32k-token context therefore holds about 4 GB of KV cache — for a single request. Ten concurrent requests need 40 GB before the model weights are even counted. This is why batch size on a serving GPU is usually limited by memory, not compute: the cache eats the VRAM that larger batches would need.
Run this arithmetic for your own model before sizing a server. The architecture numbers are in the model’s config file; the only choice is the storage precision.
Why Decode Is Memory-Bound
Per decode step, the GPU reads the whole cache and performs a small amount of arithmetic per byte read — low arithmetic intensity. Hardware people describe this as being on the memory-bound side of the roofline: adding more FLOPs does nothing because the bottleneck is how fast bytes move from HBM to the compute units.
This has a practical consequence people find surprising: a GPU with twice the memory bandwidth serves tokens faster even with the same compute specs, and a smaller model on a high-bandwidth card can out-serve a larger model on a slower one. When you shop for inference hardware, bandwidth per dollar matters more than teraflops per dollar. That bandwidth-first logic is exactly what drives our ranking of the best GPUs for LLM inference.
Techniques That Shrink the Cache
Quantized KV cache
Store the cache in 8-bit instead of 16-bit and it halves in size. Frameworks like vLLM and TensorRT-LLM support quantized KV cache with a small, usually acceptable quality cost. This is the closest thing to a free lunch in the list: one configuration flag, roughly half the memory per request, noticeably larger feasible batch sizes.
PagedAttention: stop wasting memory on fragmentation
Naive implementations allocate one contiguous block per request sized for the maximum sequence length — most of which sits empty. PagedAttention, introduced with vLLM, allocates the cache in fixed-size blocks and maps them per request, like virtual memory paging in an OS. The win is not a smaller cache per token but far less wasted space, which translates directly into more concurrent requests on the same GPU.
Grouped-query attention (GQA)
Standard multi-head attention stores a key-value head per query head. GQA shares each key-value head across a group of query heads — Llama 2 and Llama 3 models use 8 KV heads against 32 or more query heads. Fewer KV heads means a proportionally smaller cache, baked into the model architecture. When comparing models for serving, the KV head count matters as much as the parameter count.
Sliding window attention
If attention only looks back a fixed window — say, the last 4,096 tokens — the cache stops growing once the window fills. Mistral’s models use this design. The tradeoff is real: the model genuinely cannot attend beyond the window, so it suits tasks where distant context matters less. For chat and code completion it is often a good trade; for whole-document analysis it is not.
Prefix caching
Many requests share a prefix: the same system prompt, the same few-shot examples, the same document being questioned repeatedly. Prefix caching computes the KV cache for the shared prefix once and reuses it across requests. If your workload has a long shared prompt, this skips the most expensive part of prefill for every request after the first — faster first tokens and less redundant computation. The hosted-API cousin of this trick is prompt caching, where providers discount the repeated prefix instead of recomputing it.
Chunked prefill and continuous batching
These are scheduling techniques rather than cache compression, but they attack the same bottleneck. Chunked prefill splits long prompts into pieces so one huge prefill does not stall everyone else’s decode steps. Continuous batching inserts new requests into freed slots instead of waiting for a whole batch to finish. Together they keep the GPU’s memory bandwidth saturated with useful work instead of idle gaps. On the decoding side, speculative decoding attacks the same bottleneck by drafting tokens with a smaller model and verifying them in batches.
Sizing Your Memory Budget
Do the arithmetic before you rent the GPU:
- Compute bytes per token from the model config using the formula above.
- Multiply by your target context length and concurrent requests.
- Add the model weights and a margin for activations and overhead.
- If it does not fit, apply the techniques above in order: quantized cache, prefix caching if your workload shares prompts, then a smaller-context or GQA-based model.
Most serving surprises come from skipping step one. A spreadsheet with the formula beats a guess about which GPU tier you need.
When the KV Cache Doesn’t Matter
Short contexts change the picture. With a few hundred tokens of context, the cache is megabytes and decode is fast regardless. Single-user latency on small models is dominated by other factors. And on CPU or unified-memory systems the tradeoff shifts — bandwidth is lower but so is the alternative. The KV cache is the central problem of high-throughput, long-context GPU serving specifically. Know which regime you are in before optimizing.
Where to Start
If you run an inference server today, three moves cover most of the win: enable prefix caching if your prompts share a system prompt, turn on 8-bit KV cache quantization in your serving framework, and compute the per-request cache size so your batch settings match your VRAM instead of fighting it. Measure tokens per second before and after — memory work is one of the few optimizations where the improvement shows up immediately and unambiguously.