Sub topic 11
Finding and fixing the changes that break your cache
This chapter assumes you can read short Python snippets and that you know how exact prefix matching works. You should also know how to read the cache fields in a usage report (tokens written, read, and uncached). Here you will use those fields to find out why a cache that should hit is missing.
Start with the symptom, not the guess
A cache miss has one root cause: the prompt prefix the provider sees is not byte-for-byte the same as the prefix it stored. Your job is to find the first position where the two prompts differ. Everything after that position is lost, even if it is identical.
Begin with the hit ratio from the previous chapter. The pattern of the ratio over time points to the cause:
- Always near 0 from the first repeat. The prefix changes on every request, or the prompt is below the minimum cacheable length, or no breakpoint is set (on providers that need one).
- Good, then sudden drop after a deploy. Someone edited the system prompt, the tool definitions, or the template.
- Good during busy hours, poor at night. Entries expire between requests. This is a lifetime problem, not a content problem.
- Good for the first turns of a conversation, then poor. Something in the history is being rewritten or trimmed.
- Inconsistent: some requests hit and some do not. Parallel requests, several prompt variants, or requests routed to different servers.
The rest of this chapter covers the last branch, which is the most common one.
Compare two requests segment by segment
Reading raw prompts by eye does not scale. A small script that splits each request into ordered segments and reports the first one that differs works better. Order matters because providers build the prefix in a fixed sequence. Tools usually come first, then the system prompt, then messages.
import copy
import json
def segments(request):
"""Flatten a request into ordered (name, text) pairs, in prefix order."""
parts = []
for tool in request.get("tools", []):
parts.append(("tool:" + tool["name"], json.dumps(tool, sort_keys=True)))
parts.append(("system", request.get("system", "")))
for i, message in enumerate(request.get("messages", [])):
name = f"message[{i}]:{message['role']}"
parts.append((name, json.dumps(message["content"], sort_keys=True)))
return parts
def first_break(previous, current):
"""Return a description of the first change that breaks the shared prefix."""
a, b = segments(previous), segments(current)
for (name_a, text_a), (name_b, text_b) in zip(a, b):
if name_a != name_b:
return f"order or name changed: {name_a} -> {name_b}"
if text_a != text_b:
return f"content changed in {name_a}"
if len(b) < len(a):
return f"current prompt is shorter; {a[len(b)][0]} and later were dropped"
return None # previous is a prefix of current: the cache can be reused
base = {
"tools": [
{"name": "search", "description": "Search docs"},
{"name": "calc", "description": "Do math"},
],
"system": "You are a support assistant.",
"messages": [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello"},
{"role": "user", "content": "Refund?"},
],
}
# 1. A normal next turn: history grows at the end.
next_turn = copy.deepcopy(base)
next_turn["messages"] += [
{"role": "assistant", "content": "Within 30 days."},
{"role": "user", "content": "Thanks"},
]
# 2. Tools reordered.
reordered = copy.deepcopy(base)
reordered["tools"].reverse()
# 3. A timestamp added to the system prompt.
stamped = copy.deepcopy(base)
stamped["system"] = "Time: 2026-11-28T06:23:34Z\n" + stamped["system"]
# 4. An earlier message edited.
edited = copy.deepcopy(base)
edited["messages"][0]["content"] = "Hi there"
for label, request in [("next turn", next_turn), ("reordered tools", reordered),
("timestamp", stamped), ("edited history", edited)]:
print(f"{label}: {first_break(base, request)}")Running it prints:
next turn: None
reordered tools: order or name changed: tool:search -> tool:calc
timestamp: content changed in system
edited history: content changed in message[0]:userNone is the good result: the old request is a prefix of the new one. Log the output of first_break for a sample of consecutive requests from the same session. The names it returns show you which part of your template is unstable.
The usual causes
| Cause | What happens | Fix |
|---|---|---|
| Timestamp, date, or request ID near the top | The prefix differs on every call | Move per-request values after the stable text, or into the final user message |
| Reordered tools | The tool list sits at the start of the prefix, so the whole cache is lost | Sort tools by name, or build the list in one fixed order |
| Non-deterministic serialization | The same data produces different text | Use `json.dumps(..., sort_keys=True)` and a fixed format |
| Edited or summarized history | Every segment after the edit is new | Append only; compact history in rare, planned steps |
| Per-user text in the system prompt | Each user gets a separate prefix | Put user-specific text after the shared part |
| Changed model or settings | Entries are tied to the model, and some providers also tie them to certain settings | Keep the model fixed within a session; check your provider's list of what invalidates the cache |
| Whitespace or template edits | A trailing space or a reworded line changes the text | Treat the prompt template like code and review changes to it |
| Breakpoint on changing content | The marker sits on a block that varies | Place it on the last stable block |
Volatile values hidden in "static" text
Timestamps are the obvious case. Less obvious are these:
- A randomly chosen few-shot example, or examples shuffled each call.
- A "current user" name or locale inserted in the greeting line.
- A retrieved document list that changes order because of ties in a ranking.
- A Python
setor unsorteddictprinted into the prompt. - A feature flag or A/B test variant that changes one sentence for some users.
The second code example in this tutorial already showed the date fix. The same rule applies to all of these: if a value changes per request, per user, or per run, it belongs after the shared prefix.
Tools and tool results
Tool definitions come before the system prompt in many providers' prefix order, so an edit to one tool description can invalidate everything. Generate the tool list from a single source, sort it, and avoid dynamic descriptions such as "Available regions: ..." built at runtime. If you must offer different tools to different users, group users into a few fixed tool sets instead of making a unique list for each one.
Tool results sit in the message history. If you later replace a large old result with a short stub to save space, you have edited history, and the cache from that point on is gone. Decide how to trim when you design the loop, and do it at a fixed threshold so that the cache is rebuilt once, not at every turn.
History that is rewritten
Common ways history gets rewritten without anyone noticing:
- A sliding window that drops the oldest message on every turn. The first message changes every call, so nothing matches. A better approach is to keep the window fixed until it reaches a limit, then cut a large chunk at once.
- A client library that strips or normalizes whitespace in assistant messages before sending them back.
- A framework that reformats the assistant's earlier output, for example by re-rendering tool calls.
Compare what you stored against what you send. If the assistant said "Hello " and you send "Hello", the prefix is broken at that message.
Check breakpoints and minimums
Two causes look like content problems but are configuration problems:
- The prompt is too short. Each provider has a minimum cacheable length that can differ by model. A prompt below it is processed normally, and the usage report shows no cache activity. An editing mistake that trims your policy file can push you under the limit with no error.
- The breakpoint is misplaced. With explicit breakpoints, a marker on the final user message caches that message, which changes every time. Put the marker on the last block that stays the same across requests. Providers that look back only a limited number of blocks from a marker may also miss when many blocks are appended between requests, so check the lookback rule in your provider's documentation.
With automatic caching there is no marker to misplace, but all the prefix rules still apply.
Make regressions visible
Fixing the cause once is not enough, because the next template edit can undo it. Two cheap habits keep the fix in place.
First, log the cache hit ratio per request, tagged with the prompt template version. A drop after a release then points at the change.
Second, add a test that builds two consecutive requests and asserts that the stable part is identical:
def test_prefix_is_stable():
first = build_request(user="alice", question="Q1")
second = build_request(user="bob", question="Q2")
# Everything up to the final user message must match.
assert segments(first)[:-1] == segments(second)[:-1]Here build_request is your own function that assembles a request in the shape used above. The test fails as soon as someone adds a timestamp, a user name, or an unsorted list into the shared part.
Exercise
Your hit ratio was 0.9 last week and is 0.0 today. The only deploy added the line "Today is {date}" as the first line of the system prompt. Explain why the ratio dropped to 0, and give the fix.
Show answer
The date changes from day to day, and the line sits at the start of the prefix, so the first difference between a stored prompt and a new one is at the very beginning. No leading part matches, so nothing can be read from the cache. (If the date changes only daily, requests on the same day could still match each other, but a per-request timestamp would break every request.) Move the date line after the static instructions, or into the final user message, so the long shared prefix stays identical.
Exercise
A chat app drops the oldest message from the history on every turn once the conversation reaches 20 messages. Hit ratios are high for the first 20 turns and near zero afterward. Why, and what would you change?
Show answer
After the limit is reached, each turn removes the first message, so the beginning of the prompt is different from the previous call. The prefix no longer matches from the first position, so everything misses. Instead, let the history grow to a higher limit, then remove a large block at once (or summarize it once). The cache is then rebuilt only at those planned points, and most turns append to an unchanged prefix.