KV cache: reusing attention work during generation
The KV cache stores the keys and values a model has already computed, so each new token needs only a small amount of new work. It is on by default, and its memory use often decides how many requests a GPU can serve.
KV cache in 60 seconds
- What: saved keys and values, the intermediate results of attention, for every token already processed in a sequence.
- Why: without it, generating each new token would recompute attention inputs for the whole prompt and all earlier output.
- How: prefill computes and stores keys and values for the prompt. Each decode step reads them, adds one more entry, and emits a token.
- Cost: it lives in GPU memory, and grows with tokens, layers, and heads for every active sequence. It often limits how many requests fit.
- Who controls it: the model server, not the application. You influence it through prompt length, output limits, and batching.
Where this type fits
The KV cache is the first of the caches that live inside the model server. It is automatic and has nothing to do with the answer text. The other two members of this family, KV cache compression and the prefix cache, build on it. Caches that the application controls, such as the response and semantic caches, sit above it. The Types of caching in AI systems hub shows the whole map.
The problem it solves
A transformer language model (LLM) generates text one token at a time. A token is a small piece of text, often a word or part of a word. To choose the next token, the model runs an operation called attention. In attention, each token looks at all earlier tokens to decide what matters. To do that, every earlier token is represented by two vectors: a key, which says what the token offers, and a value, which carries its content.
Here is what goes wrong without a cache. To produce token 501, the model needs keys and values for tokens 1 to 500. If it recomputed them from scratch, then token 502 would recompute 501 of them, and so on. The work for each new token grows with the length so far, and the total work for a long answer grows roughly with the square of the length. Replies would get slower and slower, and costs would climb.
The key insight is that keys and values for earlier tokens do not change when a new token is added. A token's key and value depend only on the tokens before it. So they can be computed once and reused. This is what the KV cache does. It turns a quadratic amount of repeated work into a linear amount of new work, at the price of memory.
How it works
- Prefill: the server processes the whole prompt in parallel. For every token and every layer, it computes a key and a value and writes them into the cache.
- First token: the model uses the filled cache to compute the first output token. The time up to this point is the time to first token.
- Decode step: for the next token, the model computes the keys and values of only the newest token, appends them to the cache, and attends over the whole cache to choose the next token.
- Repeat: each step reads the cache, extends it by one position, and emits one token, until the model stops or hits a length limit.
- Release: when the request ends, the cache for that sequence is freed so the memory can be reused.
- Memory management: the server packs many sequences' caches into GPU memory. How it allocates that memory decides how many requests can run together.
The top row is prefill. It is compute-heavy, because many tokens are processed at once, and it fills the cache. The bottom row is decode, which is a loop. Each pass is light on compute but heavy on memory reads, because the whole cache is read to produce a single token. That is why decode speed is often limited by memory bandwidth rather than arithmetic.
The note at the right is the practical point. The cache size is roughly: tokens times layers times heads times head size, times two (for keys and values), times the bytes per number. Double the context length and the cache doubles. Serve twice as many users at once and it doubles again. For long prompts and many users, the cache can take more GPU memory than the model weights.
The PagedAttention paper (Kwon et al., 2023) tackles how this memory is organised. It stores the cache in fixed-size blocks, like pages of virtual memory. That reduces wasted space and lets requests share blocks. Before that kind of design, servers often reserved a large contiguous slab per request, sized for the longest possible answer, and most of it sat unused.
A worked example
Acme runs a model server on one GPU with 40 GB of memory. The model weights take 16 GB, leaving about 24 GB for the cache and working space. Assume, for illustration, that one token of cache costs 0.5 MB across all layers.
A user sends a prompt of 1 500 tokens asking for a summary. Prefill processes all 1 500 tokens in one pass and stores 1 500 cache entries, about 750 MB. The first output token appears after the prefill finishes. Then decode begins. The model writes 300 tokens of summary. At step 1 it reads 1 500 entries and adds one. At step 300 it reads 1 799 entries and adds one. Each step does the work for one new token only, not for 1 800.
At the end, the sequence holds 1 800 entries, about 900 MB. With about 20 GB usable for cache, the server can hold roughly 22 such sequences at the same time. If the average request were three times longer, only about 7 would fit. This is why long prompts reduce throughput, even when each one is fast. When memory runs short, the server must queue requests, shrink batches, or evict and later recompute a cache. All of those raise latency.
Prompt: 1 500 tokens | Output: 300 tokens
Cache per token (assumed): 0.5 MB
After prefill: 1 500 x 0.5 MB = 750 MB
After decoding: 1 800 x 0.5 MB = 900 MB
Usable cache memory: 20 GB (20 000 MB)
Concurrent sequences ~ 20 000 / 900 = 22Building it
You rarely write a KV cache yourself. The model server does. But a small sketch shows what it holds and why it grows. The code below is a toy with placeholder maths. It stores keys and values per layer, appends one entry per step, and enforces a hard length limit, because an unbounded cache is the main way servers run out of memory.
# Placeholders: model.layer_kv(layer, token, past) and model.next_token(...)
# stand in for real attention maths. The structure is what matters here.
MAX_TOKENS = 4096 # hard cap on prompt + output; protects GPU memory
NUM_LAYERS = 32
class KVCache:
def __init__(self):
# One list of (key, value) per layer, appended to as tokens arrive.
self.layers = [[] for _ in range(NUM_LAYERS)]
def length(self):
return len(self.layers[0])
def append(self, layer, key, value):
self.layers[layer].append((key, value))
def free(self):
self.layers = [[] for _ in range(NUM_LAYERS)] # release on completion
def generate(prompt_tokens, max_new_tokens):
cache = KVCache()
try:
# Prefill: compute keys and values for every prompt token once.
for tok in prompt_tokens:
for layer in range(NUM_LAYERS):
k, v = model.layer_kv(layer, tok, past=cache.layers[layer])
cache.append(layer, k, v)
out = []
for _ in range(max_new_tokens): # decode loop is bounded
if cache.length() >= MAX_TOKENS:
break # stop rather than exhaust memory
nxt = model.next_token(cache.layers) # reads the whole cache
out.append(nxt)
for layer in range(NUM_LAYERS): # only the NEW token is computed
k, v = model.layer_kv(layer, nxt, past=cache.layers[layer])
cache.append(layer, k, v)
if nxt == model.eos_token:
break
return out
finally:
cache.free() # always release, even on errordef cache_bytes(tokens, layers, kv_heads, head_dim, bytes_per_value=2):
# Rough size of the cache for one sequence. The factor 2 is keys plus values.
return 2 * tokens * layers * kv_heads * head_dim * bytes_per_value
def max_concurrent(free_bytes, tokens_per_request, **model):
return free_bytes // cache_bytes(tokens_per_request, **model)Design decisions
- Memory layout: use a server that allocates the cache in blocks instead of one slab per request. Default: block-based allocation, because it wastes far less memory and lets requests share blocks.
- Context and output limits: set a maximum prompt length and a maximum output length. Default: limits tied to what your use case needs, not the model's maximum, since every extra token costs memory.
- Batching: serve many sequences together to use the GPU well. Default: continuous batching, which adds new requests as others finish, within the cache memory you have.
- Precision: keys and values are stored as numbers of a chosen size. Default: the model's standard precision first, and compression only after measuring (see KV cache compression).
- Model architecture: the number of key and value heads sets the cache size per token. Grouped-query attention (Ainslie et al., 2023) shares them across groups of query heads and shrinks the cache. Default: prefer models that use it when long contexts or many users matter.
- Failure handling: when memory is full, the server queues, rejects, or evicts. Default: reject early with a clear error and a retry hint, rather than letting latency grow without bound.
- Isolation: one request's cache must never be readable by another. Default: rely on the server's per-sequence isolation, and treat any shared-block feature as intentional and limited to identical prompts.
Measuring it
- Time to first token: from request received to first token sent. It is dominated by prefill, so it rises with prompt length.
- Inter-token latency: the time between output tokens during decode. It rises as the cache grows and when memory bandwidth is under pressure.
- Cache memory use: the share of GPU memory used by the cache, and how much of the allocated cache is actually in use. Low use of allocated memory means waste.
- Concurrent sequences and queue time: how many sequences run at once, and how long requests wait for cache space. Rising queue time is the early warning that memory is the limit.
- Eviction and recompute rate: how often a cache is dropped and rebuilt. Each one costs a repeated prefill.
def summarise_latency(requests):
# requests: dicts with t_sent, t_first_token, t_done, output_tokens.
ttft = sorted(r["t_first_token"] - r["t_sent"] for r in requests)
itl = [(r["t_done"] - r["t_first_token"]) / max(r["output_tokens"] - 1, 1)
for r in requests]
p95 = lambda xs: xs[int(0.95 * (len(xs) - 1))]
return {"ttft_p95": p95(ttft), "itl_mean": sum(itl) / len(itl)}When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Any normal text generation with a transformer model | Yes | It is on by default and generation would be far slower without it. |
| Long prompts or long outputs | Yes, and plan memory | The cache grows with length, so size your servers for it. |
| Many users served at once on one GPU | Yes, and plan memory | Cache memory per user decides how many fit. |
| Single short requests with plenty of free memory | Yes, with nothing to tune | The server handles it and the cost is small. |
| You want to avoid recomputing a shared prompt start | Add a prefix cache | The plain KV cache lives only for one request. |
| You want to reuse whole answers to repeated questions | No, use another cache | An exact or semantic response cache serves answers without running the model. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | None in the standard form, the answer is the same | Measure quality again if you add compression or eviction. |
| Latency | Much faster decode, but long prompts slow time to first token | Trim prompts, stream output, and cap lengths. |
| Cost | Saves compute, but takes scarce GPU memory | Pick the model and limits that fit your memory, and measure concurrency. |
| Complexity | Invisible to the application, visible to operators | Use a server with block-based memory and watch cache metrics. |
| Failure modes | Out-of-memory errors, queues, and recompute after eviction | Set limits, reject early, and alert on queue time. |
Compared with related types
The plain KV cache lives for one request and one sequence. The prefix cache keeps the cache for a shared start of prompts, such as a long system prompt, so later requests skip that prefill. KV cache compression shrinks the cache, using lower precision, eviction of rarely used tokens, or architecture choices.
Application-level caches work differently. They store answers or retrieved results and can skip the model entirely. See the caching component page for general ideas and inference serving for how servers manage this memory.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems: the hub page for all caching types.
- PagedAttention, Kwon et al., 2023: stores the KV cache in fixed-size blocks, like pages of virtual memory, which reduces wasted memory and lets requests share blocks.
- Inference serving: how model servers batch requests and manage memory.
- Prefix cache: reusing the cache across requests that share a start.
The KV cache is why generation is fast, and why memory is the usual limit on how many users a GPU can serve. You rarely tune it directly, but prompt and output limits shape it every day.