Your agent starts a run with cache_read_input_tokens
at 40K and climbing. Twelve tool calls later, reads drop to zero and cache_creation_input_tokens
jumps to the full conversation length β on every single turn. Nothing in your prompt changed. No timestamp, no reordered tool, no model switch. The prefix is byte-identical.
You just hit the 20-block lookback window, and it is the single most expensive thing about Claude prompt caching that nobody puts in their retro.
cache_control
breakpoint searches backward through tool_choice
, images, and toggling thinking preserve the tools+system cache. Only tool-definition changes and model switches force a full rebuild.{"role": "system", ...}
message to messages[]
instead (Claude Opus 5, Opus 4.8, Fable 5; not Sonnet 5).input_tokens
in the usage block is the input_tokens + cache_creation + cache_read
. Dashboards that graph input_tokens
alone will show you a flat line while you burn cache writes.Because cache lookup is bounded. Prompt caching is a prefix match on exact bytes, but a breakpoint doesn't scan the entire history for a matching entry β it walks backward a limited number of content blocks. That limit is 20. If the previous request's cached block is more than 20 blocks behind your new breakpoint, the lookup fails, and the API treats your request as cold even though a perfectly valid entry exists.
Chat apps never see this. One user turn is one text block; one assistant turn is one text block. You'd need ten round trips to move 20 blocks, and you place a breakpoint on each turn anyway.
Agent loops are different. Count what a single "turn" actually appends:
tool_use
blockstool_result
blocksAn agent that fires 8 parallel tool calls appends 8 tool_use
-
8
tool_result -
2 = 18 blocks in one round trip. Two of those turns and your single trailing breakpoint is 36 blocks past the last cached point. Silent miss. No error, no warning field β just
cache_read_input_tokens: 0
and a cache-creation charge for the full history.
The economics are brutal at scale. On Claude Opus 5 at $5/MTok input, a cache read is ~$0.50/MTok and a 5-minute cache write is ~$6.25/MTok. A 12x price swing per turn, triggered by a config detail you never set.
Stop putting one marker on the last block. Rotate a small set of markers through the message list at a stride shorter than the lookback window. Every breakpoint is both a write point and a read point, so a trailing chain of them means each new request always finds a prior entry within 20 blocks.
The budget matters: 4 breakpoints per request, total, across tools + system + messages. Spend one on the last system block (it caches tools and system together, since render order is tools
β system
β messages
) and rotate the remaining three.
CACHEABLE = {"text", "image", "tool_use", "tool_result", "document"}
STRIDE = 15 # < 20-block lookback, with headroom
MSG_BREAKPOINTS = 3 # 4 total minus the one on the system block
def place_breakpoints(messages):
"""Re-place cache_control so no two markers are >STRIDE blocks apart.
Mutates plain-dict messages in place (round-trip SDK objects with
.model_dump() first β you cannot set cache_control on a response object)."""
flat = []
for m in messages:
if isinstance(m["content"], str):
m["content"] = [{"type": "text", "text": m["content"]}]
for b in m["content"]:
b.pop("cache_control", None) # clear last request's markers
flat.append(b)
marks, pos = [], len(flat) - 1
while pos >= 0 and len(marks) < MSG_BREAKPOINTS:
while pos >= 0 and flat[pos].get("type") not in CACHEABLE:
pos -= 1
if pos < 0:
break
marks.append(pos)
pos -= STRIDE
for i in marks:
flat[i]["cache_control"] = {"type": "ephemeral"}
return messages
resp = client.messages.create(
model="claude-opus-5",
max_tokens=8192,
system=[{"type": "text", "text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"}}], # caches tools + system
tools=TOOLS, # sorted, frozen for the run
messages=place_breakpoints(history),
thinking={"type": "adaptive"},
)
Two details that bite:
Clear the old markers. Breakpoints you set on turn 5 are still sitting in the history you resend on turn 6. If you don't strip them you'll exceed 4 and get a validation error, or worse, waste your budget on positions that no longer help.
Thinking blocks are not cacheable anchors. cache_control
goes on text
, image
, tool_use
, tool_result
, and document
blocks. Landing a stride on a thinking block and silently dropping the marker is exactly how you end up 20+ blocks apart again.
Not all of them, and this is where most teams over-engineer. There are three tiers β tools, system, messages β and a change only invalidates its own tier and everything after it.
| Change | Tools | System | Messages |
|---|---|---|---|
| Tool definitions (add/remove/reorder) | β | β | β |
| Model switch | β | β | β |
speed , web-search/citations toggle |
|||
| β | β | β | |
| System prompt content | β | β | β |
tool_choice , images, thinking on/off |
|||
| β | β | β | |
| Message content | β | β | β |
Read the practical consequence: you can force tool_choice
on one turn, flip thinking off on the next, and keep the tools+system cache intact. Stop threading a "cache-safe mode" flag through your call sites for those.
What you cannot do casually is touch the tool array. Tools render at position 0, so adding one tool for one turn rebuilds everything. Serialize tool definitions deterministically β sort by name, sort_keys=True
on any JSON schema you generate β because a dict-ordering flip in your schema builder is a full-prefix invalidation that looks like nothing in a diff.
Model switching has no escape hatch; caches are model-scoped. If you want a cheap Haiku 4.5 pass over a long context, that's a separate cache lineage, not a discount on the existing one.
Append it to messages[]
as a system-role message instead of editing the top-level system
field:
history.append({"role": "user", "content": "..."})
history.append({
"role": "system",
"content": "Terse mode enabled β keep responses under 40 words.",
})
Editing top-level system
changes bytes ahead of the entire conversation, so every cached turn gets reprocessed at full price. A role: "system"
message sits after the history and leaves the cached prefix intact.
It's supported on Claude Opus 5, Opus 4.8, Fable 5, and Mythos 5 with no beta header β not Sonnet 5, which returns a 400. Wrap it and fall back to putting the instruction in a user-turn block.
There's a security bonus that's easy to miss: this is a non-spoofable operator channel. Instructions embedded as text inside user or tool content can be forged by anything that writes into that content β a scraped page, a tool response, a file. A role: "system"
message cannot.
Because a cache entry only becomes readable once the first response begins streaming. Fire ten identical-prefix requests simultaneously and none of them can read what the other nine are still writing. You pay ten cache writes at 1.25x β worse than not caching at all.
The fix is a two-phase fan-out: send one request, await the first streamed token (not the full response), then release the remaining Nβ1. They read the entry the first one just wrote. On a 100K-token shared prefix across ten workers, that's the difference between ten writes and one write plus nine reads.
Same reasoning applies to sub-agents and compaction passes. If a fork rebuilds system
or tools
with any difference from the parent, it misses the parent's cache entirely. Copy model
, system
, and tools
verbatim, then append fork-specific content at the end.
Probably the minimum cacheable prefix β and it is not monotonic across model generations:
| Model | Minimum |
|---|---|
| Claude Opus 5, Fable 5, Mythos 5 | 512 tokens |
| Opus 4.8, Sonnet 5, Sonnet 4.6, Sonnet 4.5 | 1024 tokens |
| Opus 4.7, Haiku 3.5 | 2048 tokens |
| Opus 4.6, Opus 4.5, Haiku 4.5 | 4096 tokens |
Below the threshold, the marker is accepted and ignored: no error, cache_creation_input_tokens: 0
. A 3K-token prefix caches on Opus 5 and Sonnet 4.5, and silently doesn't on Opus 4.6 or Haiku 4.5. Teams that route cheap sub-tasks to Haiku and expensive ones to Opus routinely find their Haiku path has never cached once.
The other silent killer is TTL. The default entry lives 5 minutes. If a tool call in your loop takes 6 minutes β a long build, a slow scrape, a human approval gate β the entry expires mid-turn and the next request rebuilds from scratch. Use {"type": "ephemeral", "ttl": "1h"}
on those paths. The write costs 2x instead of 1.25x, so break-even moves from two requests to three, which is trivially cleared by any agent loop.
Log all three usage fields per request, not one:
u = resp.usage
total_prompt = u.input_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens
print(f"read={u.cache_read_input_tokens} write={u.cache_creation_input_tokens} "
f"raw={u.input_tokens} total={total_prompt}")
The diagnostic pattern for the lookback bug is unmistakable: cache_read
grows normally for the first few turns, then collapses to 0 while cache_creation
equals the full history β and it flips exactly on the turn where a burst of parallel tool calls landed. Correlate the miss with the number of blocks that turn appended and you'll see the 20-block cliff in your own logs.
If you want the API to tell you directly, there's a cache diagnostics beta: client.beta.messages.*
with the cache-diagnosis-2026-04-07
beta flag, passing diagnostics: {previous_message_id: <prior response id>}
. It reports why a request missed instead of leaving you to diff prompt bytes by hand.
Claude prompt caching misses inside agent loops because each cache_control
breakpoint only searches backward 20 content blocks for a matching entry, and a single agentic turn with parallel tool calls easily appends more than 20 blocks β so a lone trailing breakpoint lands out of range and the API rewrites the entire prefix at 1.25x instead of reading it at 0.1x. Fix it by rotating breakpoints through the message list at a ~15-block stride within the 4-marker budget, keeping one marker on the last system block, stripping stale markers before each request, skipping thinking blocks as anchors, and switching to a 1-hour TTL wherever tool latency can exceed five minutes. Then confirm it with cache_read_input_tokens
rather than the input_tokens
field, which reports only the uncached remainder and will happily look healthy while your cache does nothing.