Claude Prompt Caching: Why Agent Loops Miss the 20-Block Lookback An engineer discovered that Claude prompt caching misses its 20-block lookback window in agent loops, causing silent cache misses and 12x cost swings. They detail how parallel tool calls append 18 blocks per turn, exceeding the limit, and propose rotating cache breakpoints at a stride shorter than 20 blocks to maintain cache hits. 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 blocks tool 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: thinking blocks can't carry cache control — skip back to an eligible one 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: