Automatic Prefix Caching in vLLM, Explained

vLLM reuses the KV cache of a shared prompt prefix across requests. How automatic prefix caching hashes blocks, when it hits and misses, and how to tune it.

Every turn of an agent sends the model almost the same thing. A long system prompt, a block of few-shot examples, maybe a retrieved document, and then one short new instruction at the end. The new part is a few dozen tokens. The part in front of it can be ten or twenty thousand. On a stateless server the model reads all of it from scratch on every request, and reading it is not free: the prefill pass computes a key and value vector for every token before the first output token appears.

Prefix caching is the engine noticing that it already did that work. If a new request starts with the same tokens as one it processed a moment ago, it keeps the earlier KV cache around and reuses it instead of recomputing. The second request skips most of its prefill and jumps to generating.

This post is for engineers serving open models on their own hardware, usually with vLLM, who want to understand what prefix caching reuses, why a hit rate that looks great in a benchmark collapses in production, and the handful of knobs that matter. It is a companion to my notes on what an inference engineer actually does and on serving many LoRA adapters from one GPU; prefix caching is another feature that is one flag to turn on and a lot of detail to use well.

Two requests share a system prompt and few-shot prefix. Request A prefills all its blocks and caches the prefix; Request B reuses the cached prefix blocks and only prefills its own tail.

What is actually being reused

A request to an LLM has two phases. Prefill reads the whole prompt in one forward pass and builds the KV cache for it. Decode then generates one token at a time, each step attending to that cache. Prefill is compute-bound and scales with prompt length; a long prompt means a long wait before the first token.

Prefix caching only touches prefill. It does not make decode faster and it does not change a single output token, because the KV vectors for a given span of tokens are the same whether you compute them now or computed them a second ago. The vLLM design doc calls it close to a free lunch for that reason. What it saves is the prefill you would otherwise repeat for the shared head of the prompt.

The reason vLLM can do this cheaply is PagedAttention. The KV cache is already stored in fixed-size blocks that do not have to sit next to each other in memory, the idea from the PagedAttention paper (Kwon et al., SOSP 2023). A block holds the keys and values for a fixed number of tokens. If two requests share a prefix, they can point at the same physical blocks. Caching a prefix is then just keeping some blocks around and letting more than one sequence reference them.

How vLLM knows two prefixes match

The engine cannot compare whole prompts token by token on every request; that would cost what it is trying to save. Instead it hashes each block, and it chains the hashes so a block’s identity depends on everything before it.

The hash of a block folds in the hash of the parent block plus the token IDs in this block, roughly hash(parent_hash, block_token_ids). Block 0 has no parent, so it mixes in the raw tokens (and, as I will get to, a salt and any extra keys). Block 1’s hash depends on block 0’s hash and block 1’s tokens. Block 2 depends on block 1, and so on down the sequence. The vLLM design doc includes the exact tokens in the hash on purpose, to cut the chance of a collision mapping two different prefixes to the same cache entry.

Each block's hash folds in the hash of the block before it, so two requests that agree on the first three blocks produce the same hashes for those blocks and diverge at the first block whose tokens differ.

Two consequences fall out of the chain, and both matter in practice.

First, a match is a prefix match, not a substring match. Because block 3’s hash depends on block 2 depends on block 1, two prompts that agree on their first three blocks produce identical hashes for those three. The reuse walks the chain from the front and stops at the first block whose hash differs. Shared text in the middle of two otherwise-different prompts buys you nothing.

Second, only full blocks are cached. A block is hashed once it is complete. The last, partially filled block of a prompt is not a cache entry, so the useful unit of reuse is the block size, not the token. With the default block size this is rarely something you tune, but it is why a 10-token shared prefix saves nothing while a 2,000-token one saves a lot.

As of vLLM v0.11 the default hash is SHA-256, chosen over the older default to make collisions a non-issue; you can pick the algorithm with --prefix-caching-hash-algo on vllm serve.

Turning it on

In vLLM’s older V0 engine, prefix caching was off by default because the bookkeeping added measurable overhead even when nothing hit. The V1 engine redesigned those data structures for constant-time eviction and near-zero cost at a 0% hit rate, and so turned it on by default. You opt out, not in:

# V1: prefix caching is already on. This disables it.
vllm serve meta-llama/Meta-Llama-3-8B-Instruct \
  --no-enable-prefix-caching

So on a current vLLM you usually do not configure anything to get it. The work is making sure your prompts can actually hit, and measuring whether they do. Red Hat’s writeup of the V1 switch frames this as a win most users get with no extra config, which is true, and also why it is easy to leave hit rate on the table without noticing.

Where the hits really come from

The pattern that pays off is a large, repeated head followed by a small, varying tail. A few workloads fit it naturally:

A shared system prompt and few-shot block across every request is the cleanest case. Classifiers and extractors that prepend the same instructions and examples to every input reuse that entire head on every call after the first. The longer and more stable the instructions, the bigger the saving.

Multi-turn chat is the other classic. Turn two of a conversation is turn one plus the model’s reply plus the new message. The whole of turn one is a shared prefix, so each turn only prefills what is new since the last. This is the same arithmetic behind provider-side prompt caching; automatic prefix caching is the self-hosted mechanism that does it without you marking breakpoints.

RAG has a narrower version. If many questions are asked against the same retrieved document, and the document sits before the question in the prompt, the document’s blocks are shared. The catch is that retrieval usually returns different chunks per query, so the hit is on whatever static framing sits above the retrieved context, not on the context itself.

The layout mistake that kills your hit rate

Here is the failure I have watched surprise people. The reuse walks from the front of the prompt and stops at the first block that differs. So anything that changes per request and sits early in the prompt moves the divergence point to the front and throws away the whole cache.

The usual culprit is a timestamp or a per-request ID injected at the top of the system prompt. "The current time is 2026-11-24 14:02:11." as the first line means block 0 is different on every single request. Every downstream hash changes with it, the match ends at token zero, and your beautifully stable system prompt below it is recomputed every time. The hit rate reads near zero and nobody can see why, because the prompt looks mostly identical.

The same prompt with the variable timestamp first gives zero reuse because block 0 differs; moving the timestamp to the tail keeps the static head identical, so its blocks hit the cache.

The fix is to order the prompt by how often each part changes: most stable first, most variable last. Static instructions and schema at the top, then any shared context, then the volatile bits and the user’s actual input at the end. Same tokens, same information, better cache behavior. This is worth doing even on a provider API, where the same ordering is what lets their prompt cache hit.

Isolation, and why it is a security property

Shared KV blocks across requests raise an obvious question: whose requests get to share? If reuse were purely content-based, a careful attacker could measure latency to learn whether their prefix was already cached, which leaks something about other users’ prompts.

vLLM’s answer is to mix extra keys into the block hash. A per-request cache_salt is folded into the first block’s hash, so only requests carrying the same salt can reuse each other’s blocks; give each tenant its own salt and their caches are disjoint. The same mechanism keeps caches distinct across things that should not share: a LoRA adapter ID and multimodal input hashes go into the key too, so a prefix computed under one adapter is never handed to a request using another. If you serve multiple tenants from one engine, treat cache_salt as the boundary, not an afterthought.

Where it breaks, and the tradeoffs

Cache space is not free, and it gets evicted. Cached blocks live in the same GPU KV memory that running requests need. When a new request needs blocks and none are free, vLLM evicts cached-but-unreferenced blocks, in V1 on an LRU basis. Under memory pressure a prefix you expected to hit may already be gone. Prefix caching does not let you serve longer contexts; it reuses work within the memory you already budgeted, which is the usual GPU memory math.

A benchmark hit rate lies. Load tests tend to replay the same prompt, which hits constantly. Production traffic is spread across many prefixes with different volatility, so the real hit rate is lower and sometimes much lower. Measure it on real traffic. vLLM exposes prefix cache hit metrics; a dashboard on them, the kind of thing I wire up with OpenSearch for workflow monitoring, tells you whether the feature is doing anything before you reason about why.

It does nothing for decode-bound work. If your requests have short prompts and long generations, prefill was never the bottleneck and caching it saves little. The feature pays off when prompts are long and repeated, not when they are short.

The block-size granularity rounds down. Because only full blocks are hashed, a shared prefix that does not fill a whole block on the boundary wastes the remainder. For most prompts this is noise, but it is why micro-prompts see less benefit than the token counts suggest.

Some features still conflict. Prompt logprobs, for one, have historically required caching off; vLLM has been closing these gaps, but if you depend on a feature like that, check the behavior on your installed version rather than assuming. Flags and defaults in vLLM move between releases, so confirm against the version you actually run.

What I would reach for

On a current vLLM you get prefix caching for free, so the real work is upstream of the flag. Write prompts stable-part-first so the cache has a long head to match. Give each tenant a cache_salt and stop worrying about cross-user leakage. Put a hit-rate metric on a dashboard so you are reasoning from numbers, not hope. And remember what it does not do: it will not lengthen your context, speed up decode, or rescue a workload whose prompts are short.

The broader idea reaches past vLLM. SGLang organizes shared prefixes as a radix tree so many requests branch off one cached trunk, which is the same insight with a different data structure. Whichever engine you run, the move is the same: find the part of the prompt that does not change, make sure it sits at the front, and stop paying to compute it twice. That is most of what inference platform work on open models comes down to, one repeated cost at a time.

FAQ

Does prefix caching change the model’s output?

No. It reuses the KV cache for tokens it already processed, and those vectors are identical whether computed now or a moment ago. Sampling still runs normally, so outputs match what you would get with caching off.

Why is my prefix cache hit rate near zero?

Almost always because something variable sits early in the prompt. A timestamp, a request ID, or a user ID in the first block changes block 0’s hash, and the chained hashing throws away every block after it. Move volatile content to the end of the prompt.

Is automatic prefix caching the same as provider prompt caching?

The goal is the same, reusing a prompt prefix to skip prefill, but the mechanism differs. Provider prompt caching is a managed API feature where you place breakpoints. Automatic prefix caching is what a self-hosted engine like vLLM does transparently by hashing KV blocks.

Do I need to enable it in vLLM?

On the V1 engine it is on by default; you disable it with --no-enable-prefix-caching. On the older V0 engine it was off by default and enabled explicitly. Check which engine and version you are running.

How do I keep one tenant’s cache from being reused by another?

Set a distinct cache_salt per tenant. vLLM folds it into the first block’s hash, so only requests with the same salt can share cached blocks.


Diagrams by M. Hassan Ahmed, released under CC0. No external image was used for this post; the figures are original work by the author.