Claude Prompt Caching Strategy: Pick the TTL by the Quiet Gap, Read Cache Diagnostics, and Warm Before You Fan Out
Some SupportDesk calls read zero from the cache, and there are three suspects. Ask the API: diagnostics names system_changed (567 tokens lost) for a timestamp, tools_changed for a reorder, and nothing at all for an expired entry. A 1h lifetime halves the cost of quiet bursts (2,040 vs 4,092 units), and warming first turns 3 cold fan-out calls into 1.
What you will learn
- Pick the cache lifetime (5m, 1h or none) from the longest quiet gap in your traffic
- Opt in to cache diagnostics and read cache_miss_reason next to the usage
- Match each miss type to its fix: stable system text, fixed tool order, append-only history, one model
- Warm the cache with one call before fanning out parallel requests
Before you start
- Claude prompt cache breakpoints
- Claude usage fields
Picture a support agent that answers thousands of tickets a day, all on the same long prompt. Caching should make that cheap, but only if you plan it, and only if you can see why it misses.
Some SupportDesk calls show a cache read of zero, and there are three suspects. Maybe a time line crept into the system text. Maybe a deploy changed the tool order. Or maybe traffic went quiet for eight minutes. Each one leaves the read at zero and writes the whole prefix again at full price. The bill climbs, and nobody knows which it was.
In this article we answer three questions: what to cache, how long to keep it, and what changed. The basics of where breakpoints go are in prompt cache breakpoints. Here we add the lifetime plan, the API's own diagnostics, and warming before a fan-out.
A kitchen that preps ahead
Some prep sits on the counter: it stays ready for five minutes, and every order keeps it fresh. Some goes in the fridge: it lasts an hour, but costs more to prepare. And if someone changes step one, every later step is redone. Prepare what never changes, and keep it as long as the quiet gaps need.
The plan: stable first, lifetime by the gap
The request goes tools, then system text, then the ticket. The first two are the same on every call, so the breakpoint goes right after the system text. Keep a time line, a request id and a reshuffled tool list out of that stable part. The lecture also notes a minimum prompt length (512 tokens in this example); under it, nothing is cached.
The project runs on a stand-in model (the Anthropic SDK on an httpx mock transport, with a simulated prompt cache), so no API key is needed and the replies are test replies. Its token counts are its own (four characters per token), not real ones.
MULT = {"read": 0.05, "write_5m": 1.25, "write_1h": 2.0} # Sonnet 5.5, as multiples of the base input price
def pick_ttl(gap_seconds):
"""pick a lifetime from the longest quiet gap"""
if gap_seconds <= 300:
return "5m"
if gap_seconds <= 3600:
return "1h"
return None
def mark(ttl):
return {"type": "ephemeral", "ttl": "1h"} if ttl == "1h" else {"type": "ephemeral"}
def build_request(text, ttl="5m", history=(), stamp=None,
model=MODEL, tools=TOOLS, tool_choice=None):
"""tools, then system, then messages"""
system = POLICY if stamp is None else f"Time now: {stamp}. " + POLICY
head = {"type": "text", "text": system}
head["cache_control"] = mark(ttl)
block = {"type": "text", "text": text}
if history:
block["cache_control"] = mark(ttl)
messages = list(history) + [{"role": "user", "content": [block]}]
req = dict(model=model, max_tokens=256, tools=tools,
system=[head], messages=messages)
if tool_choice:
req["tool_choice"] = tool_choice
return req
(Excerpt from cache_plan.py.)
- Gaps within five minutes: the default 5-minute lifetime is enough, because every use refreshes it.
- Up to an hour: use the 1-hour lifetime, so the entry survives the gap.
- Longer than that: return
Noneand don't pay to write an entry that will expire before the next call. - The price ratios: a write costs 1.25x the base input price at 5 minutes and 2x at 1 hour; a read costs 0.05x on Sonnet 5.5.
5m or 1h for quiet bursts
First, pick_ttl on three example gaps. Then four bursts of three tickets, with several quiet minutes between bursts, run once with each lifetime:
B. how long should the cache live?
gap 120s -> 5m | gap 440s -> 1h | gap 5400s -> None
ttl 5m: 4 bursts of 3 tickets cold 4 hits 8 cost 4092 units
ttl 1h: 4 bursts of 3 tickets cold 1 hits 11 cost 2040 units
1h costs 50% less than 5m
With 5 minutes, every burst starts cold: four cold calls. With 1 hour, only the very first call is cold. The 1-hour write costs more, but it is paid once instead of four times, so the input cost halves.
The doctor: ask the API why it missed
Usage tells you that a call missed. Cache diagnostics tells you why. You opt in per request by passing the previous response's id:
"""The cache doctor: send diagnostics with every call, then read the answer next to the usage."""
FIXES = {
"model_changed": "hold the model constant",
"tools_changed": "same tools, same order",
"system_changed": "keep the system text byte-stable",
"messages_changed": "history is append-only",
"previous_message_not_found": "send diagnostics every turn",
"unavailable": "keep tool_choice constant",
}
def ask(client, request, previous_id=None):
"""opt in with the previous response id"""
return client.beta.messages.create(
**request, diagnostics={"previous_message_id": previous_id})
def diagnose(r):
"""read the answer next to the usage"""
u = r.usage
miss = r.diagnostics and r.diagnostics.cache_miss_reason
if miss:
lost = getattr(miss, "cache_missed_input_tokens", None)
note = f" ({lost} tokens)" if lost else ""
return f"{miss.type}{note}: {FIXES[miss.type]}"
if u.cache_read_input_tokens:
return "hit"
if u.cache_creation_input_tokens:
return "entry expired: use the 1h ttl"
return "under the minimum length: not cached"
diagnostics is a request field on the Messages API. In the Python SDK it goes through client.beta.messages, and the answer comes back on the response as cache_miss_reason, which names the first change it found and how many tokens were lost.
Nine calls, read two ways
A. why did the cache miss?
steady read 720 written 0 hit
timestamp read 0 written 725 system_changed (567 tokens): keep the system text byte-stable
tools reordered read 0 written 720 tools_changed (740 tokens): same tools, same order
history edited read 720 written 53 messages_changed (53 tokens): history is append-only
fallback model read 0 written 720 model_changed (740 tokens): hold the model constant
quiet for 8 min read 0 written 720 entry expired: use the 1h ttl
tool_choice set read 720 written 0 unavailable: keep tool_choice constant
too short read 0 written 0 under the minimum length: not cached
lost the id read 0 written 720 previous_message_not_found: send diagnostics every turn
- Timestamp: a time line in the system text. Diagnostics says
system_changed, 567 tokens lost. The fix is byte-stable system text. - Tools reordered:
tools_changed. Same read of zero, same kind of fix: keep the order. - History edited: only the 53 tokens after the edit were lost; the rest was still read. History is append-only.
- Fallback model: the model changed, so
model_changedand the whole prefix is written again. Hold the model constant. - Quiet for 8 minutes: diagnostics reports nothing, and the read is zero. Nothing changed; the entry expired. That is the case for the 1-hour lifetime, and only that one.
- Too short: nothing read, nothing written. Under the minimum, never cached.
- Lost the id: the previous response wasn't sent with diagnostics, so there is nothing to compare. Send it every turn.
Look at the usage column alone: timestamp, tools reordered and quiet-for-8-minutes all read 0 and write about 720. Only diagnostics tells them apart, and they need different fixes.
Warm it first, then fan out
Three tickets arrive at the same moment. Sent together, each one finds nothing to read, and each writes the whole prefix. An entry can be read only after the first response that writes it has started. So send one call ahead, then fan out the rest:
C. fan out
cold fan-out calls 3 cold 3 hits 0 cost 2751 units
warm first calls 3 cold 1 hits 2 cost 1022 units
Common mistakes
- Adding more breakpoints after a deploy breaks the cache. The count isn't the problem; something before the breakpoint changed.
- Switching every call to the 1-hour lifetime and hoping. It fixes an expired entry, not a changed prompt, and every write costs 2x instead of 1.25x.
- Turning caching off. Then you pay the full price every time.
- Reading usage alone. Three different causes looked identical in the usage column. Read diagnostics next to it.
- Fanning out cold. Parallel calls can't read an entry that doesn't exist yet. Warm first.
For edits that keep the cache intact mid-conversation, see cache-safe instruction changes.
Quick recap
| Question | Answer | In this run |
|---|---|---|
| What to cache? | Tools, then system text; breakpoint after the stable part | 720-token prefix read on a hit |
| How long? | By the longest quiet gap: 5m, 1h or none | quiet bursts: 1h, 2,040 vs 4,092 units |
| Why did it miss? | diagnostics, read with usage | system_changed, tools_changed, ... or expired |
| Parallel calls? | Warm first, then fan out | 1,022 vs 2,751 units |
Try it yourself
Your traffic has bursts every 50 minutes overnight and every 2 minutes during the day. Use pick_ttl to decide the lifetime for each period, then work out whether one lifetime for the whole day would be cheaper than switching at the shift change.
Related course on Udemy
Claude Certified Developer - Professional (CCDV-P) Exam Prep
Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
