Prompt Caching in Practice: What a Cache-Friendly Prompt Looks Like in an Agent Loop
Three Claude worker runs read 98% of their input from cache. The layout that allows it is small, and one common feature, history compaction, works against it.

Here is one turn from a coding-agent run, trimmed to the three fields that matter for prompt caching:
{ "input_tokens": 2, "cache_creation_input_tokens": 113, "cache_read_input_tokens": 57962 }
One turn of a 65-turn run: 57,962 tokens came from cache, 113 were newly written, 2 were fresh. That split is what a cache-friendly prompt produces.
If your agent sends its full conversation on every request, track how much of that input was read from cache, written to cache, or billed at the base rate. Across this run, 98.1% was read from cache. Those counters show how much input was reused. Below is a layout that makes that reuse possible, the numbers from three of my own runs, and the one feature that works against it.
What a cache-friendly prompt layout looks like
Caching is prefix matching. The provider hashes everything from the start of the request up to a breakpoint, and a hit needs that whole prefix to be identical. So the layout rule is about order: what never changes goes first, what changes most goes last.
tools fixed set, fixed order, never filtered per turn
system role and rules; no timestamps, no per-user text
[summary] rewritten only when history is folded
history append-only: user, assistant, tool_use, tool_result
<- explicit breakpoint: last reusable block
current turn the new message
Illustrative layout: if an unexpired cache entry matches through the marked history block, the API reads that prefix from cache and bills the new message at the base input rate.
With an explicit breakpoint you mark the last block you expect to reuse, which sits before the new message. With automatic caching the API puts the breakpoint on the last cacheable block of the request, and in an append-only conversation the next request can reuse that entry if the prefix still matches, the entry has not expired, and its breakpoint is within the lookback window. The lookback only finds entries that earlier requests actually wrote, within 20 blocks of the breakpoint. If a turn adds 20 or more blocks (a burst of tool calls, say), the previous entry can fall out of reach.
The Anthropic docs I fetched for this article say cache prefixes are built in the order tools, then system, then messages, and that a change at one level invalidates that level and every level after it. Changing a tool definition invalidates all three. Changing tool_choice only invalidates messages. That is why "filter the tool list per turn" is an expensive habit.
Claude prompt caching: what the API gives you
Claude prompt caching has two ways to mark a breakpoint. You can put one top-level cache_control field on the request and let the API place it on the last cacheable block ("cache_control": {"type": "ephemeral"} at the request root, plus "ttl": "1h" for the one-hour lifetime), or you can put cache_control on individual content blocks. You can define up to four breakpoints, and a hit is looked for within a 20-block window before a breakpoint. The default lifetime is five minutes, refreshed each time the entry is read, with a one-hour option at extra cost. For Sonnet 5.5 the minimum cacheable prompt is 512 tokens; shorter prompts are processed normally with no error.
The usage fields are what let you check your own layout. cache_read_input_tokens is what came from cache, cache_creation_input_tokens is what was written, and input_tokens is only what came after the last breakpoint. The docs say plainly that input_tokens is not the total. Add all three to get the real input size. If you only watch input_tokens you will think caching is working or broken for the wrong reasons.
What the first request reused across three runs
You start a worker on a fresh task. Nothing in the conversation exists yet, so you expect a cold start. I looked at the first turn of three separate Claude Sonnet 5.5 worker runs, started on different tasks, and the first assistant turn of each read exactly 15,766 tokens from cache.
Each run hit a cached prefix of the same length. That is consistent with a shared prefix, but the usage counters cannot establish that the three runs matched the same entry. I did not open the prompts. The likely candidate is the system prompt, the tool definitions and the standing instruction files that every worker loads. What I can say is what happened around it: each first turn also wrote a new block of 34,000 to 36,000 tokens (the additional tokens written on that request). The next request in each run wrote another 3,667 to 4,853 tokens, and later writes were smaller still.
So the part I control is the front. I keep the standing instructions identical for every worker and put the task text last. Putting a timestamp or request ID inside the shared prefix would prevent reuse of entries that include that block. Put the variable part at the end.
Cache reads grew as the session progressed
The 65-turn run shows how cache reads grew as the session progressed. In the stretch I read turn by turn, cache_read_input_tokens climbs from about 52,000 to about 83,000, and the per-turn write is usually hundreds of tokens after the initial writes. input_tokens was 2 on every turn I read.
The table uses the CLI's final per-model usage totals for all three runs. The turn counts come from the run results.
| Run | Turns | Cache read | Cache written | Fresh input | Read share of input |
|---|---|---|---|---|---|
| A | 65 | 4,093,053 | 81,261 | 112 | 98.1% |
| B | 119 | 7,637,336 | 86,844 | 200 | 98.9% |
| C | 11 | 529,880 | 48,055 | 20 | 91.7% |
From the per-run totals the Claude CLI logs: in the two long runs about 98 of every 100 input tokens were a cache read.
Across the three runs together the read share is 98.3%. These are three runs of one kind of work, not a benchmark. They do show the mechanism. In a client that re-sends the conversation on each request, the same history accounts for a growing share of input. With append-only history, a request can reuse a previously written prefix that still matches and is within the lookback window. Editing an earlier message invalidates entries that include the edit, though the request may still hit an earlier eligible entry. In the turns I read, the read count never fell back.
The short run paid more per token
Run C is the odd one: 11 turns, and a read share of 91.7%. The shorter the run, the more of its input is the first big write that nothing has paid back yet.
The docs I fetched list the multipliers. For Sonnet 5.5 a cache read costs 0.05 times the base input price, a five-minute write 1.25 times, and a one-hour write 2 times. In all three logs every write sits in the one-hour bucket and the five-minute bucket is zero, so I priced writes at 2 times. Converting each run to base-input-price equivalents (read at 0.05, write at 2, fresh at 1) gives:
- Run A: 8.8% of what the same tokens would cost with no caching.
- Run B: 7.2%.
- Run C: 21.2%.
The short run costs two to three times as much per input token because cache writes made up a larger share of its input. The CLI's own logged cost for the three runs adds up to about $2.50, across all three runs, including output.
Without a hit, a one-hour cache write doubles the input cost of that prefix. One hit brings the total to 2.05 times the base input price, versus 2 times for two uncached requests. At the Sonnet 5.5 rates used here, a one-hour write followed by two cache hits costs 2.10 times the base input price for that prefix, versus 3 times for three uncached requests.
Compaction rewrites the prefix on purpose
A long chat eventually will not fit in the context window, so something has to shrink it. The usual answer is compaction: summarize old turns and drop them. That rewrites history, so it invalidates every cached prefix that includes the rewritten part. An earlier prefix that holds only tools and system prompt can still be reused.
I hit this while designing context compaction for an AI SDK that several of my apps share, ChatPing among them. The design plan notes that prompt caching favors an append-only prefix and that the prefix, meaning system prompt plus summary, "changes only at fold time." The compaction is built around that sentence:
- The design first prunes old tool payloads at 70% of the input budget, then folds if input is still above the 70% threshold or history is nearing the message cap.
- A fold summarizes only turns that newly aged out, plus the old summary.
- The summary is stored as the first history message and replaced in place, so the summary stays stable between folds. Pruning old tool payloads can still change later history in the sent request.
- The fold runs after the current turn commits. The next send waits for any pending fold. A failed fold falls back to plain trimming instead of failing the turn.
The agent version of this is merged for Android and iOS. The plain-chat path turns compaction on when the app sets ChatCapabilityConfig.historyCompactor; leaving it unset keeps full-history replay. The plan also has a cheaper first step that replaces old tool results with one-line references before any summarizing. That step rewrites old turns too, so by my reading it also invalidates the cache from that point; it is just cheaper than a model call.
Here is the part I have not measured. The plan states the cache reasoning, and I did not find a cache-hit measurement of the SDK's compaction in the repo. The usage numbers in this article come from coding-agent runs, not from SDK chat sessions. I can still do the arithmetic from the docs multipliers: at one-hour write pricing, a token written to the one-hour cache costs 2 times the base input price and a token read from cache costs 0.05 times, so every token that compaction forces back into a cache write costs 40 times what it cost as a cache read. Whether folding saves money depends on the summarization call, how much input it removes, and how often the new prefix is reused. The SDK's cache savings were not measured.
Fold late and in one batch, and make the folded prefix the new stable one.
The same rule on other providers
The OpenAI docs say prompt caching is on by default and needs the whole rendered prefix to match. They advise stable instructions first, dynamic content at the end, and appending new messages instead of rewriting earlier turns, and they say summarization or compaction can reset reuse. For GPT-5.6 and later, the minimum is 1,024 visible input tokens; for earlier models it varies by request settings. Gemini's docs say implicit caching is on by default for 2.5 and newer models and suggest putting large, common content at the beginning of the prompt. Different mechanics, same layout.
Checklist you can apply today
- Put tools, system prompt and standing rules first. Keep them byte-identical across requests and across runs.
- Remove timestamps, request IDs and per-user text from the front. Put them in the last message.
- Do not filter or reorder tool definitions per turn. Restrict tool use with
tool_choiceinstead. - Treat history as append-only. Never edit an earlier message to tidy it.
- Put an explicit breakpoint on the last reusable block, before the new message. With top-level
cache_control, keep history append-only and keep each turn under 20 new blocks so the lookback can find the last entry. - Log
cache_read_input_tokens,cache_creation_input_tokensandinput_tokensper turn, and add all three before judging anything. - Check the minimum cacheable length for your model and your lifetime option before assuming a hit.
- For one-shot calls, work out whether the write premium will ever be read back.
- Fold history at a threshold, in a batch, after the turn. Do not summarize every turn.
- After any prompt change, compare read, write and total input counts on the turns around it.
If you want help getting an agent loop or chat feature to this shape, that is work I take on. For the surrounding cost picture, see what Claude Code plans cost, and for the manual version of the compaction problem, what survives Claude Code compact. Running many of these workers at once has its own limits, covered in running multiple Claude Code agents.
Keep reading
- I Counted 332 AI Coding Agent Journal Rows. Fewer Than Half Landed First TimeMost pages about an AI coding agent rank tools. This one counts what happened when I logged 332 rows of agent work on live Android and iOS codebases.
- Trunk-Based Development With Coding Agents: What My Merge History ShowsI pulled the merge history of five repos to see how long my branches really live. One large branch failed CI three times before it went green; the small ones merged in minutes.
- Android and iOS, Two Device Layers: agent-device Against My Own StackThe same kind of task on an Android emulator and an iOS Simulator, run through two device layers. One handed the agent screens of a few hundred bytes; the other handed it tens of kilobytes. Both finished, and both platforms had a moment that would have fooled an agent.