When vLLM's prefix cache stops hitting on multi-turn agent traffic, there are two families of cause, and they need opposite fixes. Capacity and routing: in May 2026 vLLM published 610 Codex traces from SWE-bench Pro (median 33 turns, context growing from 12K to 80K tokens) where the hit rate was 1.7 percent, because long prefixes were evicted and turns landed on instances that had never seen them; a shared KV pool took it to 92.2 percent. Render divergence: the prompt vLLM builds for turn N plus 1 is not a prefix-extension of turn N, because Qwen3 templates drop earlier reasoning blocks, gpt-oss templates drop analysis messages and inject today's date, or your framework re-serializes tool arguments. No amount of KV memory fixes the second family. Block hashes chain through the parent block, so one changed token voids every block after it, and hits only land on full blocks (64 tokens by default in v0.34.0, 16 in v0.27.1). Start by rendering two consecutive turns with return_token_ids and printing the first index where the token IDs differ.
A vLLM prefix cache that stops hitting on multi-turn agent requests has one of two problems, and they need opposite fixes. Either the blocks are gone (evicted during a tool call, or the next turn landed on a different engine), or the prompt vLLM renders for turn N plus 1 is not a prefix-extension of the prompt it rendered for turn N, so there was never anything to hit. The first is a capacity and routing problem. The second is a chat template problem that no amount of GPU memory fixes.
vLLM measured the first kind on its own traces. In a May 2026 post on serving agentic workloads, 610 Codex traces from SWE-bench Pro, median 33 turns each, with context growing from 12K to 80K tokens per trace, hit the prefix cache 1.7 percent of the time: only the system prompt survived, because long prefixes were evicted on busy instances and the router sent later turns to instances that had never seen them. A shared KV pool took the same traces to 92.2 percent, with 3.8x throughput and 46x lower P50 TTFT, on a prefill-decode disaggregated setup of 12 GB200 GPUs. That is the expensive fix, and it only works if the render is stable. Check the render first: it takes ten minutes and it decides which half of this post you need.
Code references below are to vLLM v0.34.0 (released 16 November 2026) unless a line says otherwise. The post was first written against v0.27.1, and several defaults changed in between; those changes are called out where they matter. The parse direction of the same pipeline, how output tokens become tool calls, has its own post on empty tool_calls and missing reasoning content. Both sit in the AI agents pillar.
What the hit rate in your log actually measures
The log line Prefix cache hit rate: %.1f%% comes from vllm/v1/metrics/loggers.py. It is token-weighted, so a hundred short requests that hit perfectly and one 180K-token turn that misses do not average the way intuition says. It is also windowed: CachingMetrics defaults max_recent_requests to 1,000, which on a busy server can be under a minute of mixed traffic.
The per-request field is the one that answers diagnostic questions, and it is the one most deployments do not have. enable_prompt_tokens_details defaults to False (in v0.34.0 it lives in vllm/entrypoints/common/cli_args.py), so cached_tokens is simply absent. Turn it on before you change anything else, because every step below is easier with a per-request number.
| Signal | Granularity | Default state in v0.34.0 |
|---|---|---|
Prefix cache hit rate log line | Token-weighted, last 1,000 requests | On with log stats |
vllm:prefix_cache_queries_total, vllm:prefix_cache_hits_total | Tokens, cumulative since start | On |
usage.prompt_tokens_details.cached_tokens | One request | Off, needs --enable-prompt-tokens-details |
vllm:kv_block_idle_before_evict_seconds | Sampled blocks (1 percent by default) | Off, needs --kv-cache-metrics |
One changed token near the front costs the whole conversation
vLLM's prefix cache hashes fixed-size blocks rather than walking a prefix tree, which is why the failure is all-or-nothing past the divergence point. A tree-based cache belongs to a different engine, compared in SGLang vs vLLM.
Each block hash covers the parent block's hash, the tokens in this block, and extra keys such as the LoRA adapter, multimodal input hashes and the cache salt. The parent hash is the whole story: change one token in block 2, and block 3's parent changes, and so on to the end of the prompt.
Only full blocks are cached, and the default block got bigger. A request whose first 100 tokens match a cached prompt reuses only the full blocks inside those 100 tokens. DEFAULT_BLOCK_SIZE in vllm/config/cache.py is 64 in v0.34.0; it was 16 in v0.27.1. With 64-token blocks, one changed token at position 40 means the first block is lost and nothing is reused at all. The finest boundary a hit can land on is now its own knob, --prefix-match-unit, documented as valid only when every KV cache group's block size is divisible by it, and controlling matching granularity only, not how often state is stored. If your system prompt is short and your divergence sits early, measure what a smaller match unit buys on your own traffic before touching the physical block size.
Some extra keys apply to every block. In vllm/v1/core/kv_cache_utils.py, the LoRA key is ("lora", lora_name, lora_path) on every block, so switching adapters mid-session, or re-pointing an adapter name at a new path, voids the entire conversation. How to version adapters around that is in vLLM multi-LoRA serving and its silent failures. The cache salt is added to block 0 only, and the chain carries it to every block after.
Your chat template rewrites conversation history
On agent workloads this is the cause to check first, because it breaks the prefix on every turn regardless of memory, routing or offload.
Open the chat_template in Qwen/Qwen3-8B's tokenizer_config.json. It sets ns.last_query_index by scanning backwards for the last user message whose content is not wrapped in <tool_response>. Assistant messages after that index keep their reasoning:
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}Assistant messages at or before that index render as '<|im_start|>' + message.role + '\n' + content, with the think block dropped.
Walk it through an agent loop. At turn N the last user message is at index 4, and the assistant message at index 5 renders with its reasoning. Turn N plus 1 arrives, last_query_index moves to 6, and index 5 now renders without it. The new prompt is shorter in the middle than the old one, diverging at the first assistant message, and everything after recomputes on every turn.
gpt-oss does the same in a different place. Its chat_template.jinja sets future_final_message by scanning later messages for an assistant reply without tool calls, and drops the analysis message when one exists. Once a final answer arrives, that turn's analysis disappears from the render.
The same template has a blunter problem inside build_system_message():
{{- "Knowledge cutoff: 2024-06\n" }}
{{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }}strftime_now is a Jinja global that transformers installs to format the current time. It sits in the first block of every prompt, so at midnight in the server's timezone block 0 changes and the entire prefix cache goes cold in one step, with no config change and no log line.
The fourth variant lives in your framework, not the template. Qwen3 passes tool_call.arguments through tojson when it is not already a string, and transformers' tojson uses json.dumps defaults, so separators come out as ", " and ": ". If your agent framework parses the model's arguments into a dict and hands them back, {"city":"Boston"} replays as {"city": "Boston"}: two extra spaces, and a miss from that tool call to the end of the prompt on every later turn.
Prove it in ten minutes: diff two renders
Do not reason about your template. Render both turns and compare token IDs.
return_token_ids on a normal chat completion request returns the prompt token IDs alongside the output, and works on any server. Send each turn with max_tokens set to 1 and compare:
import json, urllib.request
BASE = "http://localhost:8000"
BLOCK_SIZE = 64 # v0.34.0 default; use your --block-size, or --prefix-match-unit if set
def find(obj, key):
if isinstance(obj, dict):
if obj.get(key) is not None:
return obj[key]
for value in obj.values():
hit = find(value, key)
if hit is not None:
return hit
if isinstance(obj, list):
for value in obj:
hit = find(value, key)
if hit is not None:
return hit
return None
def prompt_tokens(messages, tools=None):
body = {
"model": "your-served-model-name",
"messages": messages,
"max_tokens": 1,
"temperature": 0,
"return_token_ids": True,
}
if tools:
body["tools"] = tools
request = urllib.request.Request(
f"{BASE}/v1/chat/completions",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request) as response:
return find(json.load(response), "prompt_token_ids")
turn_n = prompt_tokens(history)
turn_n_plus_1 = prompt_tokens(history + new_turn)
for i, (a, b) in enumerate(zip(turn_n, turn_n_plus_1)):
if a != b:
print(f"first divergence at token {i} of {len(turn_n)}")
print(f"reusable: {(i // BLOCK_SIZE) * BLOCK_SIZE} tokens, full blocks only")
break
else:
print(f"clean prefix extension, all {len(turn_n)} tokens reusable")Pass the exact history your agent sends, including the tool schemas, not a tidied copy. The divergence index names the cause. Near zero is the system message: a live date, a rotating salt, or a tool list your framework reorders. At the first assistant message it is history rewriting. At a tool call it is argument re-serialization. Past the end of the previous turn, the render is clean and you have a capacity or routing problem.
If you would rather not generate a token at all, v0.34.0 ships /v1/chat/completions/render, which returns the token-in request the engine would run. On a standard server it is off by default: start vllm serve with --enable-scale-out to expose it. To measure from a cold cache between experiments, /reset_prefix_cache exists, but in v0.34.0 it is a development endpoint, registered only when VLLM_SERVER_DEV_MODE is set, so use it on a test server, never in production. It returns {"success": false} while blocks are held by running requests or in-flight offload transfers, so read the body, not the status code.
For load rather than a single diff, vLLM ships benchmarks/multi_turn/benchmark_serving_multi_turn.py with a sample generate_multi_turn.json input file.
Seven causes, ranked by how much prefix they cost
The first row changed between releases. In v0.27.1 the serve path enabled prefix caching only for models that supported it and were not hybrid, and logged the decision at debug level, so a Jamba, Bamba or Nemotron-H deployment ran without it unless you passed the flag. In v0.34.0 the default comes from is_prefix_caching_supported alone, which returns true for generative hybrid models and false for attention-free ones. If you upgraded across that boundary and the hit rate jumped, that is why.
Two behaviours cap reuse before any of the table applies. Sliding-window layers need only the last window of tokens resident for a hit, and models mixing window and full attention take the intersection; why those layers are hard to checkpoint is in prompt reprocessing on SWA and hybrid models. And every context compaction is a deliberate total flush, because it rewrites history from the first message: the cost side of context compaction for long-running agents.
| Cause | Prefix lost | The signal that identifies it | The fix |
|---|---|---|---|
| Caching off for this model or release | 100% | Hit rate exactly 0.0%; attention-free model, or a hybrid on an older release where it was opt-in | --enable-prefix-caching where supported; upgrade if you run a hybrid on an old release |
Per-request cache_salt, or an adapter switch mid-session | 100% | Salt varies per request, or LoRA name or path changed between turns | One stable salt per tenant per session; no mid-conversation adapter swaps |
| Live date in the system message | 100%, once a day | Hit rate falls to near zero at midnight server time | Pinned template with a frozen date via --chat-template |
| Template rewrites assistant history | Everything after the first assistant message | First divergence lands at the first assistant turn | Pin the render server-side with --chat-template |
| Tool arguments re-serialized by your framework | Everything after the first tool call | Divergence is whitespace-only inside a JSON argument object | Replay the model's original argument string, not a re-encoded dict |
| Session scattered across data-parallel engines | Everything, on each reroute | -dp N set, hit rate falling as N rises | Session-sticky routing with --data-parallel-external-lb, or a shared KV pool |
| Blocks evicted during tool-call pauses | The tail of a long session | vllm:kv_block_idle_before_evict_seconds clusters at your tool latency | --kv-offloading-size, more KV memory, fewer concurrent sessions |
Eviction: your blocks die while the agent waits on a tool
Fix the render and you meet the capacity problem the vLLM traces showed. An agent turn reuses almost all of the previous turn's prefix, then the agent waits on a tool call, and during that wait its blocks are unreferenced and eligible for LRU eviction by other sessions. When the tool returns, the whole context recomputes.
The free queue makes this worse for single sessions. Freed blocks go to the tail in reverse order, on the reasoning that a request's last block hashes more tokens and is less likely to be shared. Eviction pops from the head. For a shared system prompt that ordering is right. For one agent's long session it means the newest, most context-rich blocks go first.
vLLM ships the histograms that show this, off by default. kv_cache_metrics is False in vllm/config/observability.py, sampling 1 percent of blocks when on. --kv-cache-metrics exposes vllm:kv_block_lifetime_seconds, vllm:kv_block_idle_before_evict_seconds and vllm:kv_block_reuse_gap_seconds. Mass in the idle-before-evict histogram at your typical tool latency means the cache dies while the tool runs.
There is still no TTL or pinning argument for ordinary attention blocks in v0.34.0. The newer prefix_cache_retention_interval setting controls how densely sliding-window and Mamba checkpoints are kept, and applies only to those cache groups. What exists for full attention is offload: --kv-offloading-size in GiB (summed across tensor-parallel ranks) with --kv-offloading-backend set to native or lmcache, which moves blocks to CPU memory instead of dropping them. The research the eviction discussion leans on is worth reading first: workload-aware eviction against LRU (arXiv:2506.02634), time-to-live scheduling for multi-turn sessions (arXiv:2511.02230), and KV reuse across multi-agent workflows (arXiv:2507.07400).
If the cache cannot hold one session at all, none of this helps and you have a sizing problem, worked through in vLLM KV cache OOM.
On-prem: you own the router, the template and the side channel
A hosted API hides its router and eviction policy; on your own cluster both are yours. That is a trade, not a free lunch, and it is where most of the work in self-hosted agent serving sits.
The default data-parallel router scatters sessions. In vllm/v1/engine/core_client.py, the DP load balancer scores each engine as max(self.client_count * inflight, waiting + running), adds waiting * 6.0 * max(0.0, kv_cache_usage - 0.5), and picks the minimum. It has no notion of which engine holds your conversation. There are two ways out. Route by session: --data-parallel-external-lb (or --data-parallel-hybrid-lb) hands routing to a front end you control, where session affinity is a few lines of config, and prefix-aware schedulers compared in llm-d vs Dynamo vs vLLM production stack go further by reading KV events (--kv-events-config). Or share the KV: the May 2026 traces held above 95 percent hit rate while scaling from 12 to 60 GPUs with plain round-robin routing, because every engine could read the pooled store. Sticky routing is cheaper to run; a shared pool survives node loss and rebalancing.
A shared prefix cache is a cross-tenant timing side channel. If two tenants share a server, one can probe for the other's cached content by measuring time to first token. cache_salt is the documented control: one random, unpredictable value per tenant, held for the session. Before v0.31.0, a salt equal to a LoRA adapter name collided with that adapter's first block (GHSA-rh6f-3x46-j33q), so on a server that also serves adapters, 0.31.0 is the floor. Expect salted and LoRA blocks to miss once after upgrading past it, because their hashes changed.
Your hash algorithm is a reproducibility decision. prefix_caching_hash_algo defaults to sha256, and the allowed values are exactly sha256, sha256_cbor, xxhash and xxhash_cbor.
vLLM's own docstring warns that the xxHash variants theoretically raise collision risk, which can leak private information in multi-tenant environments. In a regulated deployment where tenants are separate business units or clients, that warning settles it: use sha256_cbor when hashes must agree across nodes, and plain sha256 otherwise. On an air-gapped fleet rebuilt from a local mirror, CBOR is what makes a hash computed on one node valid on another; mirror mechanics are in air-gapped vLLM deployment. If you need someone to own this end to end inside your perimeter, it is the kind of serving work our AI development team does.
| Algorithm | Serialization | Reproducible across environments | Notes |
|---|---|---|---|
sha256 (default) | Python pickle | No | Fine on one homogeneous pool |
sha256_cbor | Canonical CBOR | Yes, cross-language | The choice for mixed-version or multi-node pools |
xxhash | Python pickle | No | 128-bit, non-cryptographic, needs the xxhash package |
xxhash_cbor | Canonical CBOR | Yes | 128-bit, non-cryptographic |
The triage order
--enable-prompt-tokens-details and read cached_tokens per request. Every later step needs a per-request number.--chat-template plus --default-chat-template-kwargs takes the decision away from every client. Put the divergence script in CI so a template or framework upgrade cannot silently halve throughput.--kv-cache-metrics and read vllm:kv_block_idle_before_evict_seconds. Mass at your tool-call latency means eviction; offload or fewer concurrent sessions is the lever.The one thing to do this week is step 3: take your two most recent agent turns, render both, and print the index where the token IDs first differ. If that number is smaller than your system prompt plus your first assistant message, a bigger cache will not fix your hit rate.
FAQ
Quick answers to the questions this post tends to raise.



