Sub topic 13
Reusing shared prompt prefixes
This chapter covers automatic prefix caching in vLLM. It assumes you can already run vllm serve, call it with the OpenAI client, and read the KV cache and PagedAttention chapters. You should know that prefill computes key and value tensors for every prompt token, and that vLLM stores them in fixed-size blocks.
The problem: repeated prefill work
Many real workloads send requests that begin with the same text:
- A system prompt of several hundred tokens that every chat request carries.
- A long document followed by many different questions about it.
- A few-shot prompt with the same examples in front of each new input.
- A multi-turn chat where each request resends the whole history.
Without caching, vLLM runs prefill on the full prompt every time. Prefill is compute-bound, so repeating it for identical text wastes GPU time and raises time to first token (TTFT). The key and value vectors for a token depend only on that token and the tokens before it. The same prefix therefore always produces the same KV values, and recomputing them is unnecessary.
How automatic prefix caching works
PagedAttention stores the KV cache in blocks of a fixed number of tokens (16 by default in many configurations). Prefix caching builds on this. When a block is full, vLLM computes a hash for it. The hash covers the tokens in the block and the hash of the block before it. This chaining means a block's identity depends on the entire prefix up to that point, not just its own tokens.
When a new request arrives, the scheduler splits the prompt into blocks and looks up each block hash in a table of cached blocks. Every leading block that matches is reused. Prefill then runs only on the remaining tokens.
Important details of this design:
- Only full blocks are cached. If the shared prefix is 40 tokens and the block size is 16, the first 32 tokens (two blocks) can be reused. The last 8 tokens are recomputed.
- Matching stops at the first difference. Because hashes chain, one changed token invalidates that block and every block after it.
- Reused blocks are shared. Several running requests can point at the same physical block. vLLM tracks a reference count for each block.
- Freed blocks stay cached. When a request finishes, its blocks go into an eviction pool but keep their hashes. A later request can still hit them. When free memory is needed, vLLM evicts the least recently used cached blocks first.
Prefix caching changes only the cost of prefill. It does not change the model output. The reused KV values are the ones prefill would have produced, so results match what you would get without the cache, apart from small numerical differences from different batch shapes.
Enabling it
Recent vLLM releases enable automatic prefix caching by default in the V1 engine. Older releases or some configurations require the flag. Passing it explicitly is harmless and documents your intent:
vllm serve Qwen/Qwen2.5-32B-Instruct \
--tensor-parallel-size 4 \
--max-model-len 8192 \
--enable-prefix-cachingCheck your installed version's vllm serve --help output to see whether the flag is on by default and whether a --no-enable-prefix-caching form exists.
The same switch exists in the offline API:
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
enable_prefix_caching=True,
)
system = "You are a support assistant for Acme Cloud. " * 40
questions = ["How do I reset my password?", "How do I delete my account?"]
params = SamplingParams(temperature=0.0, max_tokens=64)
prompts = [f"{system}\nUser: {q}\nAssistant:" for q in questions]
outputs = llm.generate(prompts, params)
for out in outputs:
print(out.outputs[0].text.strip())Both prompts start with the same long system text. The second prompt reuses the blocks the first one filled, so only the question and the few tokens after the last full block are prefilled.
Structuring prompts to get cache hits
The cache can only match a prefix, so prompt layout decides your hit rate. Put stable content first and variable content last.
| Layout | Cache effect |
|---|---|
| System prompt, then documents, then user question | The system prompt and documents are reused across requests. |
| User question first, then shared documents | No reuse, because the first block already differs. |
| Timestamp or request ID at the top of the system prompt | No reuse, because the first block differs on every request. |
| Few-shot examples in a fixed order | Reused. Reordering the examples breaks the match from the first changed example onward. |
Common mistakes that silently destroy hits:
- Inserting the current date, a session ID, or a user name near the start of the prompt.
- Building the system prompt from a template that varies whitespace or ordering of fields.
- Randomizing the order of retrieved documents in a retrieval-augmented prompt.
- Changing the chat template or the system message between versions of your application. Tokens differ, so hashes differ.
Tokenization also matters. Hashes are computed on token IDs, not text. A prefix that looks identical to a human can tokenize differently at the boundary where the variable text begins, for example when a word merges with a following character. Keep a clean separator such as a newline between the shared part and the variable part.
Measuring the benefit
Do not assume caching helps. Measure it with the metrics endpoint from the monitoring chapter. In V1 builds, look for prefix cache query and hit counters:
curl -s http://localhost:8000/metrics | grep -i 'prefix_cache'The exact names vary by version, but you typically see a count of queried tokens and a count of hit tokens. The hit rate is hits divided by queries. A rate near zero on a workload you expected to share prefixes points to a prompt layout problem from the previous section.
To see the latency effect, send the same long-prefix request twice and compare time to first token:
import time
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
model = "Qwen/Qwen2.5-1.5B-Instruct"
document = "vLLM stores the KV cache in fixed-size blocks. " * 300
def ttft(question: str) -> float:
start = time.perf_counter()
stream = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": document},
{"role": "user", "content": question},
],
max_tokens=16,
temperature=0.0,
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
return time.perf_counter() - start
return time.perf_counter() - start
print("cold:", round(ttft("What is stored in blocks?"), 3))
print("warm:", round(ttft("How big are the blocks?"), 3))The second call shares the system message, so its prefill covers only the new question. Expect a clear TTFT drop for long shared prefixes. For short prompts the difference is within noise, because prefill is already cheap.
Trade-offs and limits
- It uses the same memory pool. Cached blocks live in the KV cache, so they compete with active requests. Under heavy load, cached blocks are evicted quickly and the hit rate falls. Prefix caching does not add memory. If the cache is too small to hold your working set of prefixes, increase
gpu_memory_utilizationor reducemax_model_lenas covered in the memory tuning chapter. - It helps prefill, not decode. If your requests have short prompts and long outputs, the gain is small.
- There is a small bookkeeping cost. Hashing and lookups add overhead. On workloads with no shared prefixes it is usually negligible, but it is not zero.
- Cache scope is one server instance. Each replica keeps its own cache. A load balancer that spreads requests with the same prefix across replicas lowers hit rates. Route by a prefix or session key if you can.
- Isolation between users. A cache hit is faster than a miss, so timing can reveal whether someone else sent a given prefix. In a multi-tenant service, consider whether that leak matters for you. Some vLLM versions support salting the hash per tenant, so check your version's documentation.
- Adapters and other inputs affect hashes. Requests for different LoRA adapters, or with multimodal inputs, do not share blocks unless the hash includes the same adapter and input identity. vLLM accounts for this, so you should not expect cross-adapter reuse.
Summary
Automatic prefix caching hashes full KV blocks, chained to their parent blocks, and reuses any leading blocks that match a new prompt. It cuts prefill work and TTFT for workloads with shared system prompts, documents, or chat history. It does not change outputs. Your main levers are prompt layout (stable content first), enough KV memory to keep prefixes resident, and routing that keeps similar requests on the same replica.
Exercise
A service sends requests that begin with "Current time: <timestamp>" followed by a 1,500-token shared system prompt and then the user question. The prefix cache hit rate is near zero. Why, and how do you fix it?
Show answer
The timestamp is in the first block, so the first block hash differs on every request. Because block hashes chain from the parent, every later block hash differs too, and no block matches. Move the timestamp after the shared system prompt (or into the user message at the end), so the 1,500-token shared prefix is identical and its full blocks are reused.
Exercise
Your block size is 16 tokens. Two requests share exactly the same first 50 tokens and then differ. How many tokens can the second request skip prefilling, and why?
Show answer
48 tokens. Only full blocks are cached. 50 tokens fill three full blocks (48 tokens) plus 2 extra tokens in a partial block. The three full blocks can be reused and the remaining tokens are prefilled.
Exercise
You run three replicas behind a round-robin load balancer, and prefix cache hit rates are lower than on a single replica under the same traffic. What causes this, and what can you change?
Show answer
Each replica has its own cache, and round-robin sends requests with the same prefix to different replicas, so each replica sees fewer repeats and must fill its own cache. Route requests with the same prefix or session to the same replica, for example by hashing a session or prefix key in the load balancer.