The KV cache and prefix caching
The KV cache stores each earlier token's attention keys and values so a model computes one new token per step; prefix caching shares that stored state across requests that begin with the same tokens, like a shared system prompt.
What it is
An autoregressive transformer, the decoder-style model behind chat assistants, generates one token at a time, and each new token attends to all the tokens before it. Attention works on three projections of each token: a query, a key and a value. With causal masking, an earlier token's key and value don't change when later tokens arrive, so the model can keep them instead of recomputing them. That store is the KV cache. At each step the model computes the key and value for the newest token, appends them to the cache in each layer (attention runs per layer, so the cache is kept per layer too), and runs the newest token's query against the whole cache. Without it, each step recomputes all earlier keys and values and the per-step cost grows with the square of the sequence length; with it, the per-step cost grows linearly, and so does the memory the cache takes. The Hugging Face Transformers documentation adds that the cache is for inference: enabling it during training can cause errors.
Serving a request has two phases. First the server processes the prompt, which fills the cache before the first output token appears. Then it decodes, one token per step, each step reading the cache and appending one entry. Reusing cached state aims at the first phase: when two requests begin with the same tokens, the state computed for the first can serve the second, which cuts the time to the first token, and the saving grows with the share of the prompt that is common. In the extreme case of two identical prompts run back to back, the first token can arrive about as fast as the later ones.
Paged blocks and hashing. vLLM 0.9.2 splits each request's KV cache into blocks that hold a fixed number of tokens, and PagedAttention lets those blocks sit anywhere in GPU memory, allocated on demand, which avoids the fragmentation of reserving one contiguous region per request. The observation behind prefix caching is that a block's contents are fixed by its own tokens plus all the tokens before it, so a hash of the prefix plus the block's tokens identifies the block. A global table maps each hash to a physical block, and two requests whose hashes match share that block rather than each computing a copy. Blocks are independent, allocated and freed on their own, so no tree over the prefixes is needed and the cache is managed much like an operating system's. When no free block is left, the engine evicts a block no running request holds (reference count zero), the least recently used among those, and among equal timestamps the one deepest in its prefix. Serving several LoRA adapters works by folding the adapter's id into the hash, so a prompt under one adapter doesn't match the same prompt under another.
| System | Unit that is shared | When it becomes reusable | How it leaves |
|---|---|---|---|
vLLM 0.9.2 | A KV block keyed by a hash of prefix plus block tokens, in a global table | Once a block is in the table and a later request's hash matches | Reference count zero first, then least recently used, then deepest in its prefix |
TensorRT-LLM | Full blocks, 128 tokens each by default (tokens_per_block, a power of 2) | After the request that computed the block has terminated | LRU when memory is needed for a new or running request; optionally copied to host memory instead |
Claude API | The prefix up to a cache_control breakpoint, in the order tools, system, messages | After the first response using that prefix starts | A 5-minute lifetime by default, refreshed on each use; 1 hour at a higher write price |
OpenAI API (announcement, Oct 2024) | The longest previously computed prefix, from 1,024 tokens in 128-token steps, applied automatically | On a later request within the entry's lifetime | Typically cleared after 5 to 10 minutes without use, and within an hour of the last use |
Three properties follow from the mechanism, with details that differ by system. State becomes reusable after the request that computed it has progressed far enough (its termination in TensorRT-LLM; the start of its response in the Claude API), not when it is scheduled, so a burst of parallel requests carrying a brand-new system prompt can miss and compute it several times over, while requests scheduled after that point can reuse it if the blocks are still resident. Reuse is by exact prefix: the hash is cumulative, so a change anywhere before a block changes its hash and each later block's hash with it, and a prompt below a minimum length may not be cached at all. And the blocks live in GPU memory and are found through the engine's own table, so in a fleet of several engines we'd expect a request to benefit when it reaches the one holding its prefix; our advice is to route a conversation's turns to the same instance rather than spreading them at random.
When to use it
Prefix caching pays off when many requests begin the same way and that beginning is long. The common shapes: a system prompt shared by thousands of users; a chat where each turn is the previous request plus two messages; prompts that carry many examples or a long document; and agent loops that resend the same tool definitions on each step. The structure follows from the cumulative hash, and it applies as much to a server you run as to a hosted API: put the stable material first (tool definitions, instructions, reference text), put anything that varies per request (a timestamp, the user's name, their locale) at the end or in a later message, append new messages instead of editing earlier ones, and keep tool definitions and their order unchanged between calls, since tools sit at the front of the prefix and a change there misses from the first block on.
For a chat that runs to hundreds of turns, the history up to the last reply is an unchanged prefix of the next request, so with prefix caching the prefill for a turn mostly pays for the tokens added since the previous one: the assistant's last reply and the user's new message. A hosted API with automatic caching moves the cache point forward as the conversation grows and bills the earlier part at the cached rate. What this doesn't fix is memory and per-token attention cost: the KV state still covers the whole conversation and still grows a token at a time, and in a serving engine those blocks hold GPU memory until they're evicted. Trimming the context (summarizing old turns, dropping the middle) shrinks that, but it also rewrites the prefix, and reuse stops from the first changed token. Our advice: summarize rarely and in large steps rather than a little each turn, keep the summary and system prompt ahead of the live tail so the new prefix is itself stable for the next many turns, and budget a recompute from the first changed token each time you do it.
When not to
Skip it, or expect little from it, when the shared part is short relative to the whole prompt: the saving scales with the shared fraction, and hosted APIs don't cache below a minimum length at all (1,024 tokens on the OpenAI API; 512 to 4,096 tokens, by model, on the Claude API). A partly filled block isn't shared in a block-based engine, so with 128-token blocks a 100-token common prefix shares nothing. Unrelated one-off prompts gain nothing, and where writes carry a premium (a 5-minute cache write can cost 25 percent more than a plain input token) they cost more than they would without caching.
Don't count on it when GPU memory is already the constraint. Retained blocks compete with running requests: in TensorRT-LLM a new request, or a running one that needs room, takes priority and reusable blocks go first, least recently used, so a large batch or long outputs lower the odds of a hit. Copying evicted blocks to host memory raises those odds at the cost of the transfer, with a net gain expected mainly on recent hardware with a fast link to the host. Don't expect hits across a fleet with random routing either: the block table described above belongs to one engine instance, so we'd expect a turn that lands on a different instance to prefill from scratch; route conversations consistently or accept the misses. Don't treat the cache as the conversation's memory: the client still sends the full history, and a miss changes cost and latency, not the answer. And for a short prompt with a long generated reply, decoding dominates and prefix reuse does little; GPU batching and scheduling matter more there.
Compared
| Approach | What is reused | When it's the right choice | Cost or limit |
|---|---|---|---|
No cache, recompute each step | Nothing | Training, or a toy model where simplicity wins | Per-step cost grows with the square of the context |
KV cache per request | The request's own earlier tokens, during decode | Our default for autoregressive generation | GPU memory grows with the context length |
Prefix caching in the engine (hashed blocks) | Blocks shared by requests with identical prefixes | Shared system prompts, multi-turn chat, few-shot prompts on servers you run | Whole blocks, not partial ones; evicted under memory pressure; a changed prefix misses |
Hosted API prompt caching | Prefix state across API calls for a lifetime | You don't run the model and the stable prefix clears the minimum length | Writes may cost more than plain input; entries live minutes by default; minimum lengths |
Shorter context (summaries, truncation) | Nothing; fewer tokens to process and hold | History outgrows the window, or memory matters more than exact recall | Rewrites the prefix, so reuse resets from the first changed token |
In a picture
Step 1 of 4
The first request fills the cache
Request A carries the system prompt and a question. The server prefills both, writing a key and a value per token per layer into KV blocks, then decodes A's reply one token at a time against those blocks.