Sub topic 3
Why Only an Identical Prefix Can Hit
This chapter assumes you have called an LLM API before, know what tokens and a context window are, and can read short Python snippets. It builds on the previous two chapters: processing a prompt (prefill) costs time and money, and the provider can store the attention state it computed for a prompt (the key/value cache). Here you will see why that stored state can only be reused when the start of the new prompt is identical to the start of an earlier one.
The rule in one sentence
A cache hit happens only for the longest run of tokens at the beginning of a prompt that exactly matches a prompt the provider has already processed. The first token that differs ends the reusable part. Everything after that token is processed from scratch, even if it is identical to text in the earlier prompt.
Why order matters: each position depends on everything before it
Decoder-only language models use causal attention. When the model processes the token at position N, it computes a key and a value vector for that token. Those vectors are a function of the token itself and of the hidden states of all earlier tokens (positions 0 to N-1), because each layer attends to what came before.
This has a direct consequence for caching:
- The stored state for position N is only correct if tokens 0 to N-1 are the same as when it was computed.
- If token 5 changes, the state at positions 6, 7, 8 and beyond is different too. Those later tokens were computed "in the context of" the old token 5.
- Reusing old state after a change would give the model a context that does not match the text you sent. The provider cannot do that and still return the same result as an uncached call.
So the cache is not a lookup of "have I seen this paragraph before?". It is a lookup of "have I seen this exact sequence of tokens from the very start?". The same paragraph at a different position, or after a different opening, has different state.
A toy model
The following code models prompts as lists of pieces. A real provider compares tokens, not words, but the logic is the same.
def shared_prefix_len(a, b):
n = 0
for x, y in zip(a, b):
if x != y:
break
n += 1
return n
first = ["SYSTEM", "RULES", "DOC", "Q1"]
second = ["SYSTEM", "RULES", "DOC", "Q2"]
changed = ["SYSTEM", "RULES v2", "DOC", "Q2"]
print(shared_prefix_len(first, second)) # 3 -> three leading pieces are reusable
print(shared_prefix_len(first, changed)) # 1 -> one early edit invalidates everything after itIn the second comparison, "DOC" and "Q2" still appear in both prompts. They do not help, because the comparison stops at the first mismatch. The long document that follows the edited rules is processed again at full price.
What counts as "identical"
The match is on the token sequence the model receives, so anything that changes the tokens breaks it. Common surprises:
- Whitespace and punctuation. A trailing space, a changed newline, or a swapped quote character produces different tokens.
- Case and wording. "You are a helpful assistant." and "You are a helpful assistant!" are different prefixes from the exclamation mark onward.
- Serialization differences. A JSON object with the same data but different key order serializes to different text. So does a dictionary built in a different order, or a float printed with different precision.
- Different model or model version. State computed by one model is meaningless to another. A cache entry belongs to one specific model.
- Different content before the shared part. An extra line at the very top shifts everything. The text below it is the same, but its prefix is not.
- Non-text parts. Images, tool definitions and other request fields that the provider places in the prompt count as part of the prefix, in the order the provider assembles them.
Because tokenization can merge characters across a boundary, a small edit can also change tokens slightly before or after the visible change. You should not rely on the cache being forgiving about "almost the same" text.
Granularity: matching in blocks
The rule above is stated per token, but providers rarely cache at single-token precision. Depending on the provider, matching may happen in fixed-size chunks of tokens, or only at positions you mark. In both designs the prefix logic is unchanged. What changes is how much of a partial match you get to keep.
The next snippet models chunked matching. The block size here is illustrative, not any provider's real value.
def shared_prefix_len(a, b):
n = 0
for x, y in zip(a, b):
if x != y:
break
n += 1
return n
def reusable_tokens(a, b, block=4):
# Only whole blocks of the shared prefix can be reused.
return (shared_prefix_len(a, b) // block) * block
old = list(range(100))
new = list(range(10)) + [999] + list(range(11, 100))
print(shared_prefix_len(old, new)) # 10
print(reusable_tokens(old, new)) # 8: two whole blocks of 4 tokensThe identical prefix is 10 tokens, but with 4-token blocks only 8 are reusable. The practical lesson is that a change close to the end of a long stable section still costs you a little. You cannot assume every matching token is billed as cached.
Where the match is checked
Providers differ in how they find the matching prefix, which affects what you control. The next chapter covers this in detail, but the key idea is relevant here:
- With automatic caching, the provider looks for the longest previously seen prefix of your prompt on its own. You do not mark anything.
- With explicit breakpoints, you mark the end of a stable section. The provider checks whether the prompt up to that mark matches a stored entry. Some providers also check a limited number of earlier positions if the exact mark does not match, so a small append after a marked section can still hit the older entry.
In both models the check is on a prefix. A breakpoint does not let you cache "this block, wherever it appears". It only says "the prefix ending here is worth storing".
Consequences for how you write prompts
The prefix rule produces a handful of practical principles. Chapter 5 turns them into a full layout method, so here are only the direct implications.
- Anything that varies must come after anything that does not. A timestamp, user name, or request ID near the top invalidates the whole prompt.
- Appending is cheap, editing is expensive. Adding new content at the end preserves the old prefix. Changing earlier content invalidates everything after the change.
- Order of stable parts must be stable. Two prompts with the same instructions, tools and documents in different orders do not share a prefix beyond the first difference.
- Reuse requires a request that comes after another. The first call writes an entry. Only later calls with an identical prefix can read it.
from datetime import datetime, timezone
STATIC_INSTRUCTIONS = "You are a support assistant. Follow the policy below.\n" + open("policy.md").read()
def bad_prompt(question):
# The timestamp changes on every call, so no two prompts share a prefix.
now = datetime.now(timezone.utc).isoformat()
return f"Current time: {now}\n{STATIC_INSTRUCTIONS}\nQuestion: {question}"
def good_prompt(question):
# Stable text first, per-request values last.
now = datetime.now(timezone.utc).isoformat()
return f"{STATIC_INSTRUCTIONS}\nCurrent time: {now}\nQuestion: {question}"In bad_prompt, the first line differs on every call, so the shared prefix has length zero and nothing is ever read from the cache. In good_prompt, the entire policy text is a stable prefix, and only the final two lines vary. (The code above expects a policy.md file next to the script.)
What a partial match looks like in practice
Suppose your prompt has three stable parts and a question:
| Part | Tokens | Changes between calls? |
|---|---|---|
| System instructions | 1,200 | No |
| Tool definitions | 2,500 | No |
| Reference document | 6,000 | No |
| User question | 40 | Yes |
If nothing before the question changes, the first 9,700 tokens form the shared prefix. Each later call can read those from the cache and process only the 40 new tokens.
Now suppose someone edits one sentence in the tool definitions. The system instructions (1,200 tokens) still match. The edited tool definitions, the document and the question all fall after the first mismatch, so around 8,540 tokens are processed again. One small edit moved the hit from about 9,700 tokens to about 1,200.
The edit is costly because of its position, not its size. The same one-sentence edit made in the question would cost almost nothing.
Common mistakes
- Assuming a repeated document is cached regardless of where it appears in the prompt.
- Putting a dynamic value, such as the date, a session ID, or retrieved search results, ahead of long static text.
- Building tool lists or JSON from unordered collections, so the order changes between runs.
- Editing a system prompt during a rollout without expecting the first request after the change to pay full price.
- Treating a hit as a content-based lookup. A hit is a position-based match from the first token.
Exercise
A prompt has this order: system instructions (2,000 tokens), a retrieved search result that differs per request (800 tokens), a style guide (5,000 tokens, never changes), and the user question. Why does the style guide never get read from the cache, and what change fixes it?
Show answer
The style guide comes after the search result, and the search result differs on every request. The shared prefix ends where the search result starts, so only the 2,000 system tokens can ever hit, and the style guide is recomputed each time. Move the style guide ahead of the search result, so the order is system instructions, style guide, search result, question. Then the first 7,000 tokens are an identical prefix and only the search result and question vary.
Exercise
Two prompts are 10,000 tokens long and identical except that token 9,990 differs. Roughly how much can be reused, and what would change if the difference were at token 10 instead?
Show answer
With the difference at token 9,990, about 9,989 tokens match from the start, so almost all of the prompt is reusable (subject to the provider's block size, which can round the reusable amount down). With the difference at token 10, only about the first 10 tokens match, so almost nothing is reusable, even though 9,990 later tokens are identical. The position of the change decides the result, not the amount of changed text.