Open an Agent request log and you find something odd: the start of every turn is almost identical — the same system prompt, the same tool definitions, and the conversation history accumulated along the way. Every time, the model dutifully reads them from the beginning (Prefill), and the bill charges them as “new input” every time.
On the pricing page, cached input is 10–50 times cheaper than a cache miss. This essay answers: on what basis can the model say “I already read this”? How does it find the stretch it read last time, within milliseconds? And which ways of writing break the cache?
This is a follow-up to Illustrated KV Cache. That essay explained why K and V can be stored. This one explains continuing to use them across requests. Reading the KV Cache essay first makes this smoother. If you have not read it, that is fine: the parts you need are repeated here.
Let us look from the outside first. In an Agent session, the user asks one thing, the model answers, and the next request has to send the whole conversation again. The figure below is three turns. Each block is one stretch of content, and the number under a block is the token count (illustrative).
Three turns. Click the switch above to toggle “without / with prefix caching”, and look at “how many tokens were computed” on the right. Green = cache hit, pink = needs Prefill.
Note: without a cache, the three turns must Prefill 3,200 + 3,700 + 4,200 = 11,100 tokens in total. With a cache, only 3,200 + 500 + 500 = 4,200. The newly added content is only about 500 tokens. The rest is recomputing work that was already done. As the conversation grows, this gap keeps getting wider.
Prefix caching does something plain: keep the K and V computed by the last Prefill. If the next request starts the same way, use them directly, and compute only the new part.
Why does the cache accept a match only at the start, and not “a matching stretch in the middle is fine too”? Because K and V depend not only on the word itself, but also on every word to its left.
Criterion: a word's K and V at one layer are determined by “this word and every word to its left”.
Click any word to change it: its K and V, and the K and V of every word to its right, all have to be recomputed (pink). The ones to the left can still be reused (green).
This rule decides everything that follows: how the cache matches, how you write the prompt, and why a single timestamp can destroy the hit rate.
The most naive way is to compare the new request's tokens, one by one, with past requests. Too slow. This section is what the open-source engine vLLM does. The blocks come from its PagedAttention (Kwon et al., SOSP 2023). Matching a prefix automatically by hash is Automatic Prefix Caching, built by vLLM on top of that. It cuts the prompt into fixed-size blocks (a block; the typical value in vLLM is 16 tokens per block; the figure below puts only 3 in a block so it fits), then computes a hash for each block.
The key: each block's hash also folds in the previous block's hash (the vLLM docs put it this way: hash using the tokens in the block and the tokens before this block). So the hash of block $i$ stands for the whole prefix “from the start through this block”, not only this block's own content. Besides the tokens, the hash also carries extra information that “makes this block unique”, such as a LoRA ID, the hash of multimodal inputs, and a cache salt, so different things do not collide.
$$h_i = H\big(h_{i-1},\ \text{tokens of block } i\big),\qquad h_0 = \varnothing$$
Request A is already cached. Click a word in request B to change it: this block's hash changes, and the hashes of every later block change with it. Even if the later content is not changed by a single character, it is a MISS. Words in a trailing partial block do not enter the cache.
vLLM manages this with a “hash → block” hash table plus a free-block queue. Each block has a reference count. Only full blocks are cached. A cache lookup is a table lookup by hash: is B's $h_1$ in the table? Yes, cache hit. Is $h_2$? … up to the first one that is missing. After that there is no need to look further. This process is a few hash-table lookups, $O(\text{number of blocks})$, so it is on the order of milliseconds.
Criterion: the tradeoff between management cost and reuse granularity.
A service receives thousands of requests at the same time. There is a lot of shared prefix between them: every user of the same product shares one system prompt. If each request stored its own copy, GPU memory would run out fast.
SGLang's approach is called RadixAttention (the SGLang paper, Section 3, Zheng et al., 2023): a prefix tree (radix tree) manages “token sequence → the corresponding KV”, and an edge is labeled with a token sequence. A shared prefix is stored once, as the “trunk”. The part that differs for each request is a “branch” that splits off. vLLM does not use a tree, but the effect is the same: a shared prefix has the same hash, points at the same blocks, and is stored only once.
Look at this tree with a small example. Three requests, one word per token:
A: You are helpful . Fix this bug
B: You are helpful . Summarize the doc
C: You are helpful . Fix this typo
Their opening You are helpful . is the same. The tree merges a run of tokens with no branch into one edge. Each edge stores the KV for that stretch of tokens:
root ──[You are helpful .]──○──[Fix this]──○──[bug]
│ └──[typo]
└──[Summarize the doc]
Click Replay or Next step: first the three requests, then an ordinary prefix tree with one node per token, then the compressed radix tree, and finally how a new request splits one edge in two.
The shared You are helpful . has only one copy of the KV, used by A, B, and C. That is “the trunk is stored once”. The parts that differ, bug, typo, and Summarize the doc, are branches that split off.
A cache lookup starts at the root and compares along the edges, segment by segment. The hit runs as far as the match goes. Given You are helpful . Fix this bug, all three edges match, and the whole path is a cache hit. Given You are helpful . Fix that, the first segment matches. On the second edge, Fix this, only Fix matches, and the tree splits that edge in two: Fix stays in the shared part, and this and that each become a branch. That is the difference between a radix tree and an ordinary trie (a prefix tree with one token per node): a long run with no branch is merged into one edge, and the edge is split only when there is a branch.
vLLM does not use a tree: each block has one hash, and the lookup is a hash table. The first few blocks of A, B, and C have the same content, so the same hash, so they find the same block, and it is stored only once. The only difference: SGLang finds the shared part from the structure of the tree, and vLLM finds the shared part because the hashes are the same.
So a prefix tree and a block hash do the same job. Both exist to find the longest common prefix already in the cache, and to store that common prefix only once. Only the method differs:
| Prefix tree (SGLang) | Block hash (vLLM) | |
|---|---|---|
| How it recognizes “this is the same prefix” | Walk down the tree from the root, comparing tokens segment by segment | Compute each block's hash, and look it up in the hash table |
| Structure | A tree. Edges store the token sequence and the corresponding KV | A “hash → block” table, not a tree |
| Granularity | Each token | Each block (for example 16 tokens) |
| What makes a common prefix stored only once | They follow the same edge in the tree | They compute the same hash and find the same block |
| Eviction | Evict the leaf unused the longest, first | Evict the block unused the longest in the free queue |
A block hash can do the job of a prefix tree, because each block's hash carries the previous block's hash: “the same hash” means “everything from the start through this block is the same”. That itself is a prefix relationship. The hash chain implies a tree. It is just not stored as a tree structure.
The real difference is in two places: match precision (the tree matches per token, so the hit length can be any number of tokens; vLLM caches only full blocks, so the hit length is a multiple of the block size, and a trailing partial block has to be recomputed) and implementation cost (a hash-table lookup is simple; a tree is finer, but splitting an edge means editing the structure). For someone using it, the effect is the same: a matching start is a cache hit, a different start is a cache miss. So “static first, dynamic last” holds for both.
100 users share one system prompt of 10,000 tokens, stored once as the trunk (green). Each person's question is a small branch (orange). Click “+ New request” to add a user, click a branch to mark it as just used, and click “Evict LRU leaf” to evict the branch nobody has used for the longest time.
What if GPU memory is full? Both evict by LRU (Least Recently Used), but the details differ:
Either way, a popular trunk keeps being used by new requests, so it is the hardest to evict.
As for how OpenAI, Anthropic, and DeepSeek implement this internally, the official docs do not publish it. They only describe the external behavior (prefix matching, the whole stretch must match). The above is what the open-source engines do. Closed-source services most likely follow a similar idea (speculative). Do not take this as the implementation of those services.
Put the pieces above together. An engine handles one cached request in roughly these six steps. The figure below is drawn in vLLM's block-hash style. SGLang finds the longest prefix in the tree. The other steps are the same.
Take a prompt of 10,050 tokens as an example (block size 16): 625 blocks are a cache hit, and only the remaining 50 tokens need Prefill.
Note step 4: the cache-miss “tail” still has to go through Prefill, but its attention computation reads the K and V of the 10,000 cached words, as if those K and V had just been computed. What the cache-hit part saves is recomputing K and V (and the forward computation of every layer before them), not the read done by the whole attention.
One more point: step 6 registers the new blocks into the cache, including the part generated this time. So in a multi-turn conversation, turn 2 can hit not only turn 1's prompt, but usually also turn 1's answer (by turn 2 it has already become input).
Because of the hash chain, a cache hit is “the longest common prefix from the start”. Change a single character at the start and the hash chain breaks at the root. Even if ten thousand characters after that are completely the same, they are all a cache miss.
Each block is one stretch of content. Click a block in the bottom row to mean “this block changed”. Toggle “Timestamp first / last” and see, for the same amount of content, how much the hit rate differs when the timestamp sits at the start or at the end.
This is “prefix pollution”: writing something that changes at the very front of the prompt, such as the current time, a user ID, session state, or a random number. A few common traps follow:
| What you write | Result | Fix |
|---|---|---|
Write Current time: 2026-11-24 14:03:21 at the start of the system prompt | The start of every request differs, and the whole cache is invalid | Put the time in the last user message |
| Add or remove tool definitions in the middle of a conversation | The tool list is in the prefix. Change one tool and everything after it breaks | Keep the tool list fixed, and control it with an “enabled or not” field |
| Unstable key order when serializing JSON | The same content, different bytes, a different hash | Fix the key order (sorted serialization) |
| “Compress and rewrite” history messages | A block in the middle changed, so everything after it is a cache miss | Only append at the end. When you must compress, accept one invalidation |
| Put a static document after the user question | Each question pushes the document to a different position | Document first, question last |
Is picking tools dynamically (giving the model only some of the tools each turn) always faster? Not necessarily. It trades “compute a little less” for “the cache becomes invalid”:
| Fixed full tool list | Dynamic tool selection | |
|---|---|---|
| Tokens in the tool section | More (for example 5,000) | Fewer (for example 1,000) |
| Cache | The tools and the system prompt can both hit | Once the tool list changes, the whole prefix is a cache miss from the start |
| Tokens to Prefill each turn | Only the new part, very few | The whole prefix has to be recomputed (for example about 4,000 tokens) |
An example: the system prompt plus tools is 8,000 tokens, of which the tools are 5,000. With a fixed tool list, after a cache hit each turn computes only the few hundred new tokens. With dynamic tool selection the tools are down to 1,000, but each turn has to Prefill the whole prefix of about 4,000 again. That is slower, and the input cost is higher. Sending fewer tools can win only when the tool list is very large (hundreds or thousands of them) and the cache would miss anyway (for example the gap between requests is so long that the cache has expired). (derived from the mechanism, not from a vendor document; the numbers are illustrative)
When you do not want the model to use some tools, do not delete them. “Cover” them. The approach in Lessons from Manus on context engineering (source: Manus's blog) is: do not change a single character of the tool list in the prompt. The prefix stays the same, and the cache still hits. Restrict the model at the step where it generates the output. At each step the model scores every possible next token (logits). Push the scores for the tools it should not pick down extremely low, so the probability is near 0, and the model cannot pick them. An analogy: the menu still prints every dish, but when you order you cover the ones that cannot be ordered. Note: the logit_bias in the note in this library is illustrative code. The blog post never mentions logit_bias. It only says “mask the token logits directly”. How that is done is below. Whether a hosted API can do this depends on the interface. The Anthropic docs state that changing tool_choice invalidates the cache only for the messages part. tools and system still hit. So “restrict the choice with tool_choice” is much cheaper than “changing the tool list” (I have not checked the other vendors).
How Manus does it, specifically (from the blog section “Mask, Don't Remove”): it first explains why not to delete. Tool definitions sit at the very front of the context. Change them once and the cache for everything after them is invalid. Actions in the history still refer to the deleted tools, so the model gets confused and tends to produce format errors or invent actions. The approach has three parts:
<|im_start|>assistant, and the model decides whether to call a tool; Required prefills up through <tool_call>, so it must call a tool, and any tool is allowed; Specified prefills up through <tool_call>{"name": "browser_, so it must call a tool, and it can only be one of those whose name starts with browser_.browser_, and command-line tools all start with shell_. Prefill one prefix, and the choice is limited to one group of tools.Put together: the tool list always holds the same four, browser_open, browser_click, shell_ls, and shell_run, and never changes. When the current state is “browsing a web page”, prefill {"name": "browser_, and the model can only complete it as browser_open or browser_click. The two shell_ tools are still in the list, but they cannot be chosen at this step. Neither the tool list nor the system prompt changed, so the cache still hits. The blog does not give concrete code for the state machine or the masking. Whether prefill is available in each vendor's API, I have not checked.
The cache-hit part no longer goes through Prefill, so it saves two things at once: time to first token (how long the user waits for the first token) and the input price.
Pick a prompt length, and drag the hit rate. Time is estimated as “Prefill 5,000 tokens per second”. Cost is estimated with cache-hit price = 1/10 of the cache-miss price. Both are illustrative values.
A worked example: a prompt of 32,000 tokens, with a 90% cache hit. The tokens to compute drop from 32,000 to 3,200, and time to first token drops from 6.4 seconds to 0.64 seconds. The input cost is $0.1 + 0.9 \times 0.1 = 0.19$ times the original, about 20% of the full price. At a 100% hit rate, neither latency nor cost drops to 0, because cache-hit blocks still pay a read fee, and the last few tokens always have to be computed.
One thing to note: Prefill compute is not strictly proportional to the token count (the attention part scales with the square of the length), so in a real long context the fraction of time saved is usually larger than in the figure. The figure uses only the simplest linear assumption. (derived from the mechanism, not from a vendor document)
What determines time to first token (TTFT, Time To First Token)? Roughly: TTFT ≈ queue wait + Prefill time of the cache-miss part + the first Decode step + network and tokenization
This structure is derived from the mechanism, not from a vendor document. It is not a formula published by any vendor. The slider figure above uses only the simplest term (number of cache-miss tokens ÷ speed). (derived from the mechanism, not from a vendor document)
prompt_cache_key. The cache is not reused across organizations or across regions, and prompt_cache_key “affects routing, does not pin a request to one machine, and does not guarantee a hit”. The cache is not necessarily stored only in GPU memory: DeepSeek's docs state that it spills to disk. Where the other vendors store it, the official docs do not say.Change the model, and the cache is invalid too. What the cache stores is K and V, computed with the model's own weights. Change the model (even a different version of the same model) and the weights differ. The same tokens produce completely different K and V, and the old cache means nothing to the new model. (derived from the mechanism, not from a vendor document) In the official docs: OpenAI lists model as a setting that affects the cached prefix. The original wording is “A different model can use different weights and caching behavior.” It also says that routing within the same organization and region is for a given model, but it does not write the sentence “changing the model is always a cache miss”. The part of the Anthropic docs I read does not discuss changing the model. It only writes that the minimum cache length varies by model, and that changing the thinking configuration, effort, and similar settings invalidates the cache. (For both vendors' docs, I read only the earlier part, word for word.) So switching models in the middle of one session (for example sending an easy question to a small model) makes the new model Prefill the whole prefix again, and can be slower and more expensive.
The prefix rule is the same for all three. The only difference is who decides the cache breakpoint: with Anthropic you mark it, OpenAI is automatic by default and newer models can be marked by hand, and DeepSeek is fully automatic. The following was checked against the three vendors' official docs (read on 2026-11-24): Anthropic, OpenAI, DeepSeek.
| Anthropic (Claude) | OpenAI | DeepSeek | |
|---|---|---|---|
| How to turn it on | Add one cache_control at the top level of the request, or add it on a content block | Automatic by default. No change to the request. GPT-5.6 and later can be controlled with prompt_cache_options | On by default. No code change |
| How long the cache lasts | 5 minutes by default. "ttl": "1h" is 1 hour | GPT-5.6 and later: 30m (the default) or 12h. Earlier models use prompt_cache_retention (in_memory or 24h) | No fixed duration. Cleaned up “usually within a few hours to a few days” after use |
| Minimum length | It varies by model: 512 (Opus 5.5, Sonnet 5.5, Haiku 5.5, and others), 1,024 (Sonnet 5 and others), 4,096 (Haiku 4.5, Opus 4.5 / 4.6) | 1,024 (GPT-5.6 and later). Earlier models vary with the request settings | The docs give no number |
| Where to see the hit count | usage.cache_read_input_tokens (read), cache_creation_input_tokens (write) | cached_tokens (I did not verify the exact path; go by the API reference) | usage.prompt_cache_hit_tokens / prompt_cache_miss_tokens |
| Write / read price | Write is 1.25× (5 minutes) or 2× (1 hour). Read is 0.1× (Opus 5.5 and Sonnet 5.5 are 0.05×) | GPT-5.6 and later: write is 1.25× (30m) or 2.5× (12h). Read is 0.1×. Earlier models have no extra write fee | See the pricing page |
| Isolation | Not shared across organizations. On the Claude API, workspaces are isolated too | Not shared across organizations | The docs do not say |
Anthropic: two ways to write it. The first is the least work. Add one field at the top level of the request, and the system automatically places the breakpoint on the last cacheable block:
{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"cache_control": {"type": "ephemeral"},
"system": "You are an AI assistant tasked with analyzing literary works...",
"messages": [{"role": "user", "content": "Analyze the major themes."}]
}
The second is to mark the breakpoint yourself on a content block, choosing which block the cache runs through (the official example: the system prompt is split into two blocks, and the long-document block is the one marked):
"system": [
{"type": "text", "text": "You are an AI assistant tasked with analyzing legal documents."},
{"type": "text", "text": "Here is the full text of a complex legal agreement: [...]",
"cache_control": {"type": "ephemeral"}}
]
What does “breakpoint” mean? It is a mark you insert in the prompt that says “cache up to here”: from the start, up to and including the block marked with cache_control, everything goes into the cache. What comes after that block does not. For example, if the request is, in order, tools, the system prompt, a long document, and the user question, marking the breakpoint on the “long document” block caches the first three blocks together. The user question, which differs every time, sits after the breakpoint. It is not cached, and it does not invalidate the cache in front of it. One cache_control at the top level is “marked automatically”: the system places the breakpoint on the last cacheable block. Writing it directly on one block is “marked by you”: you decide which block the cache runs through. The official limit is at most 4 breakpoints per request, and each breakpoint looks back at most 20 blocks. My guess at what several breakpoints are for is to place them at the boundaries between different “rates of change” (the tool list almost never changes, the system prompt changes now and then, the conversation history grows every turn), so that when one layer changes, the more stable cache in front of it can still hit. The official docs do not put it this way.
For a 1-hour cache, write it as "cache_control": {"type": "ephemeral", "ttl": "1h"}. The two ways of writing it can be used together.
cache_control means “this can be cached”. {"type": "ephemeral"} is the type of the cache. ephemeral means “short-lived, temporary”. The official docs write that it is currently the only supported type, with a default lifetime of 5 minutes, which is why the same phrase is written every time. Placed at the top level, it tells the system to put the breakpoint on the last cacheable block automatically. Placed on one block, it means “cache up to this block (including this block)”.
Anthropic's cached-prefix order is fixed as tools → system → messages. “A change at one layer invalidates that layer and every layer after it.” A few rules the official docs state explicitly:
tool_choice, or add or remove images at any position: messages become invalid.usage.These line up with the “prefix pollution” above: Anthropic wrote “tools go first, and changing a tool breaks everything after it” into the docs.
OpenAI: automatic by default, with a manual option added on newer models. Older models cache automatically once the prefix is long enough. The official suggestion is to send a stable prompt_cache_key on requests that share the same prefix, to help route them to the same machine (it affects routing; it does not guarantee a hit). On GPT-5.6 and later, inside prompt_cache_options you can choose implicit (automatic; the breakpoint goes at the end of the last cacheable message) or explicit (you mark prompt_cache_breakpoint on a content block yourself), and use ttl to choose 30m or 12h. The writing on the official page is roughly as follows:
{
"model": "gpt-6.2-sol",
"prompt_cache_key": "support:customer_123",
"prompt_cache_options": { "mode": "explicit", "ttl": "12h" },
"input": [
{ "role": "developer", "content": [
{ "type": "input_text", "text": "Shared instructions...",
"prompt_cache_breakpoint": { "mode": "explicit" } } ] },
{ "role": "user", "content": "The user's question..." }
]
}
This example is several separate snippets from the official page that I joined together. The field names all come from the official page, but the official page does not give a complete merged example. The "role": "developer" in the example is an OpenAI role, not a typo: the official text guide states that a developer message is instructions given by the application developer, with priority above user. The role values of the Responses API are user, assistant, system, and developer. Both developer and system rank above user. I did not find a document saying that developer replaced system. The official caching page also writes: to make reusable instructions eligible for the cache, put them at the start of input, in a developer message. Also, GPT-6.2 and later place the top-level instructions after input. That part is billed at the uncached price, so do not put static content you want cached there.
Try the breakpoints yourself. The figure below is the breakpoint rules for GPT-5.6 and later: first pick breakpoints in request 1 (it writes the cache), then pick breakpoints in request 2 (it is the one that hits). Try a few things: in the default state, look at implicit; turn on Explicit and pick the breakpoints yourself; drag a block of request 1 or of request 2, and see which one makes the hit fail; switch to Earlier models and look at rounding down to a multiple of 128.
Breakpoint simulator. Click a triangle to pick a breakpoint, drag the ⋮ handle to resize each block, and the dashed line is the minimum cacheable length. The token counts in the figure, and the hidden tokens, are illustrative. The idea follows the similar simulator in OpenAI's official Prompt Caching guide. The code and the figure are rewritten by me.
DeepSeek: add nothing. The official wording is that it is on by default for all users, and no code change is needed. Each request leaves one cache-prefix unit at “the end of the user input” and one at “the end of the model output”. It also leaves units at a detected common prefix and at fixed token intervals. A later request hits only if it matches in full some prefix unit, and the prefix has to have already been written into the disk cache. So the long-document example in the docs is that the first two requests both miss, and only the third one hits. The official docs also say explicitly that it is “best effort”, and do not guarantee a 100% hit.
Criterion: put the breakpoint at the boundary between “static” and “dynamic”.
prompt_cache_key stable for the same kind of request. When using explicit, mark the breakpoint at the end of the static content.prompt_cache_hit_tokens). Only when the number rises steadily are you actually getting the cache.cache_control added on the request (you can add a single top-level field, and the system manages the breakpoints). A 5-minute cache write is 1.25× the input price, a 1-hour write is 2×, and a cache-hit read is 0.05–0.1×. OpenAI's pricing page lists a cache-write price on its own line (Sol as the example: 1.25× for 30 minutes, 2.5× for 12 hours). DeepSeek recognizes it automatically. No code change.Further reading: Lessons from Manus on context engineering (KV-Cache optimization and a 10× cost difference).