Skip to content
Inference Academy

The KV cache explained: what it is, how big it gets, and why it limits your users

Why LLMs keep a key-value cache, what exactly is stored, the formula for its size, worked numbers for Llama 3.1 8B and 70B at 8K and 128K tokens, how it grows during a request, how many users fit on common GPUs, how it slows decode at long context, how grouped-query attention shrinks it 8 times, and the techniques engines use to fit more of it in memory.

Key takeaways

  • The KV cache stores keys and values of past tokens so they aren't recomputed for every new token.
  • KV bytes per token = 2 × layers × KV heads × head dim × bytes per value.
  • Llama 3.1 8B needs about 1 GiB of BF16 cache per 8K tokens; 70B with GQA about 2.5 GiB.
  • Memory left after the weights caps how many requests can run at once, and reading the cache slows every decode step at long context.
  • Paged allocation, prefix caching, FP8 KV quantisation, offloading and preemption fit more cache in memory.

By

8 min read

Share
On this page

If you've ever served an LLM and watched it run out of memory long before the GPU looked busy, the KV cache was almost certainly the reason. It's the hidden second consumer of GPU memory after the weights, and for long conversations or many users it's often the bigger one.

This guide explains what the cache is, how to calculate its size, how it limits concurrency and speed, and every major technique for shrinking it or fitting more of it.

#Why the cache exists

A transformer generates text one token at a time. To produce each new token, every attention layer compares the new token's query with the keys of all previous tokens, then mixes their values. Without a cache, you'd recompute the keys and values of the whole conversation for every new token: generation would get slower and slower as the text grew.

So instead, each layer stores the keys and values of every token it has already seen. A new token only computes its own key and value, adds them to the cache, and reads the rest. That store is the KV cache.

How much memory does the context window really cost?
Interactive

Model (Q4 weights)

KV cache precision

GPU memory

16 GB limit

Weights 4.9 GBKV cache 4.0 GB (128 KB/token)Overhead 0.8 GB

Fits with 6.3 GB to spare (9.7 GB total).

KV bytes per token = 2 × layers × KV heads × head dim × bytes per value. The cache grows linearly with context and is on top of the weights.

The trade-off is plain: the cache turns repeated computation into memory. And memory is the resource you run out of first.

#How much work it saves

Without a cache, generating token number nn would mean recomputing keys and values for all n−1n - 1 earlier tokens in every layer. Over a 1,000-token answer, that's about 1+2+⋯+1,000≈500,0001 + 2 + \dots + 1{,}000 \approx 500{,}000 token-passes of key and value computation, instead of 1,000 with the cache. No practical system generates text without one.

#What exactly is stored

For every token, in every layer, for every KV head:

  • one key vector of length head dimension (128 is typical), and
  • one value vector of the same length.

Keys are stored after rotary position encoding has been applied, so each key "knows" its position. Nothing else is cached: queries are used once and thrown away, and the MLP layers keep no state.

#How big it is

For each token, each layer stores one key vector and one value vector per KV head. So:

KV bytes per token=2×layers×KV heads×head dim×bytes per value\text{KV bytes per token} = 2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times \text{bytes per value}

The 2 is for keys and values. "Bytes per value" is 2 for FP16 or BF16, 1 for FP8.

Worked numbers in BF16:

Model Layers KV heads Head dim Per token 8K tokens 128K tokens
Llama 3.1 8B 32 8 128 128 KiB 1 GiB 16 GiB
Llama 3.1 70B 80 8 128 320 KiB 2.5 GiB 40 GiB
70B with full multi-head attention (64 KV heads) 80 64 128 2.5 MiB 20 GiB 320 GiB

Check the first row: 2×32×8×128×2=131,0722 \times 32 \times 8 \times 128 \times 2 = 131{,}072 bytes, which is 128 KiB per token.

Look at what that means in practice. Llama 3.1 8B's weights are about 16 GB in BF16. A single 128K-token conversation needs another 16 GiB of cache: as much as the whole model. Ten users at 8K tokens each need 10 GiB.

#How it grows during a request

The cache for a request starts at the size of its prompt and grows by one token's worth with every generated token. For Llama 3.1 70B in FP8 (160 KiB per token), a request with a 4,000-token prompt and a 2,000-token answer:

Moment Tokens cached Cache size
After prefill 4,000 about 0.66 GB
Halfway through the answer 5,000 about 0.82 GB
Last token 6,000 about 0.98 GB

Two consequences. Memory planning must use prompt plus output length; reasoning models that "think" for 10,000 tokens build very large caches. And because requests grow at different rates, the engine can't know in advance exactly how much memory a request will need, which is why on-demand allocation matters (PagedAttention explained).

#Why it limits concurrency

On a GPU, memory goes to three things: weights, KV cache and working space. Whatever is left after the weights is your KV budget, and it decides how many requests can run at once.

Take Llama 3.1 70B in FP8 (about 70 GB of weights) on two 80 GB GPUs: 160 GB in all. Leave roughly 15 GB for activations and other overhead, and about 75 GB remains for KV cache. At 2.5 GiB per 8K-token request in BF16, that's about 28 concurrent requests. Batching is how you make serving cheap (continuous batching), and here memory caps the batch at 28 no matter how fast the GPUs are.

More examples, each with an FP8 KV cache and requests averaging 4,000 live tokens:

Setup KV budget (rough) KV per request Concurrent requests
Llama 3.1 8B in FP8 on one 24 GB GPU about 12 GB about 0.26 GB about 45
Llama 3.1 8B in FP8 on one 80 GB H100 about 62 GB about 0.26 GB about 230
Llama 3.1 70B in FP8 on 2 × 80 GB about 75 GB about 0.66 GB about 110
Llama 3.1 70B in FP8 on 8 × 80 GB about 500 GB about 0.66 GB about 760

Compute and latency targets may cap the batch earlier, but memory sets the ceiling. That's why so much inference engineering is really KV cache engineering.

#It also slows decode

Every decode step reads the whole cache of every sequence in the batch, as well as the weights (why memory bandwidth decides LLM speed). For Llama 3.1 8B in BF16 at a 32K-token context, that's about 4.3 GB of cache per step on top of 16 GB of weights: about 27% more bytes, so each token takes about 27% longer. In a big batch of long conversations, the cache reads can exceed the weight reads several times over. Shrinking the cache helps speed as well as capacity.

#How models shrink it: GQA, MQA and MLA

The biggest lever is architectural. The third row of the size table shows a 70B model where every attention head has its own keys and values (multi-head attention). It needs 8 times the cache of the real Llama 3.1 70B, which uses grouped-query attention (GQA): 64 query heads share 8 KV heads.

  • MHA: one KV head per query head. Largest cache.
  • GQA: groups of query heads share a KV head (8 KV heads is common). Cache shrinks by the group size, with little quality loss.
  • MQA: all query heads share one KV head. Smallest cache, more quality risk.
  • MLA (DeepSeek's multi-head latent attention): stores a compressed latent vector per token and reconstructs keys and values from it. Very small cache with MHA-like quality: about 69 KiB per token for DeepSeek-V3, a 671B model.

Sliding-window layers (which only keep the last few thousand tokens) and hybrid models (some layers with a fixed-size state instead of a cache) shrink it further. There's a full comparison in GQA vs MQA vs MLA.

#How engines fit more in

On top of the architecture, serving engines have several tricks:

  1. Paged allocation. Instead of reserving space for each request's maximum length, vLLM-style engines allocate the cache in small fixed-size blocks as tokens arrive, which nearly eliminates waste (PagedAttention explained).
  2. Prefix caching. Requests that share a prefix (a system prompt, earlier turns of a chat, a shared document) share the cached blocks for it instead of storing copies.
  3. KV cache quantisation. Storing keys and values in FP8 halves the cache, usually with small quality impact. Lower precisions save more but need care.
  4. Offloading. Moving cold blocks to CPU memory or SSD and bringing them back when needed. Useful for long idle conversations and agents that pause for tools.
  5. Preemption. When memory runs out, the engine pauses some requests, either freeing and later recomputing their cache or swapping it out.

In vLLM, for example, --kv-cache-dtype fp8 enables the FP8 cache, prefix caching is on by default in recent versions, and the startup log reports how many tokens of cache fit. In llama.cpp, --cache-type-k q8_0 --cache-type-v q8_0 (with flash attention) does the same job locally.

#The cache across requests

The cache normally lives only as long as a request. Keeping it longer is where big savings hide:

  • Multi-turn chat: turn 5 of a conversation repeats turns 1 to 4. If their cache is still in memory (or can be fetched from an offload tier), only the new turn needs prefilling.
  • Agents: an agent loop sends the same system prompt and tool definitions dozens of times.
  • API pricing: hosted APIs discount "cached input tokens" for exactly this reason: reusing a cache is far cheaper than recomputing it (prompt cache calculator).

The rule for getting these savings is the same everywhere: put stable content first and variable content last, so the shared prefix is as long as possible.

#Quick estimation rules

  • Llama-style 8B with GQA: about 0.125 MiB per token in BF16, so about 1 GiB per 8K tokens.
  • Llama-style 70B with GQA: about 0.3 MiB per token, so about 2.5 GiB per 8K tokens.
  • FP8 KV cache: halve those numbers.
  • Concurrency ceiling: (GPU memory minus weights minus overhead) divided by (KV per token times average tokens per request).

Use the average live length of requests, not the maximum context window. A model with a 128K window serving 4K-token chats needs 4K tokens of cache per request.

#Common mistakes

  • Sizing a deployment from weights alone. Weights fit, then the first busy hour runs out of KV memory.
  • Using the maximum context length for every request in your maths. You'll buy far more GPUs than you need.
  • Ignoring output length. The cache grows with every generated token; long reasoning outputs make it much bigger.
  • Assuming MHA numbers for a GQA model, or the reverse. Check num_key_value_heads in the model's config.
  • Breaking prefix sharing with a timestamp or user ID at the start of every prompt.

#FAQ

Is the KV cache the same as prompt caching? Prompt caching is reusing a KV cache across requests. The KV cache itself exists within every request regardless.

Does a bigger context window cost memory if I don't use it? Not with paged allocation: memory follows the tokens actually present. Some engines still check at startup that one maximum-length request would fit.

Does quantising the cache hurt quality? FP8 usually has a small effect; check on your own tasks, especially long-context ones. Lower than 8 bits needs more care.

#Go deeper

The VRAM calculator works these numbers out for any model and context length. To understand how attention kernels read the cache, and how engines manage it, start with attention optimisations and long-context serving in the Inference Engineering course.

kv-cachememoryfundamentalsinference-engineering

Found this useful?

Send it to someone who is learning the same thing.

Share this article

Next: learn it step by step, free

Prefill, decode and the roofline

Why decode is memory-bound, with worked numbers for real GPUs. The idea the rest builds on. A free lesson with step-through diagrams and a quiz.

Get new articles by email

One short email when a new guide is out. Unsubscribe any time.