Cut Cost and Latency with Prompt Caching
- A cache stores the processed prefix of your prompt. The prefix is built in the order
tools, thensystem, thenmessages, up to and including the block marked withcache_control. A hit needs the prefix to be 100 percent identical. - Two ways to turn it on: automatic caching (one top-level
cache_controlfield; the breakpoint follows the last cacheable block as a conversation grows) or explicit breakpoints on content blocks (up to 4 per request). Cache writes happen only at a breakpoint. - Default lifetime is 5 minutes, refreshed free on every hit and measured from the start of the request. A 1-hour lifetime costs more to write (
"ttl": "1h"). - Prices (as of 2026-11-16): a 5-minute write is 1.25x base input, a 1-hour write is 2x, and a read is 0.1x (0.05x on Claude Opus 5.5 and Claude Sonnet 5.5, 0.025x on Claude Fable 5.2 and Claude Fable 5.1). The docs say a 5-minute cache pays off after one read, a 1-hour cache after two.
- Minimum cacheable prompt: 512 tokens on Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5 (other models differ). Shorter prompts are processed without caching and no error is returned.
- Check
usage:cache_creation_input_tokens(written),cache_read_input_tokens(read),input_tokens(only the part after the last breakpoint). Total input is the sum of all three. - On 2026-11-02 I read three official pages and ran only the local price calculator and a stub test of the demo script. I did not call the real API (no API key, no
anthropicpackage), so cache hits are untested here.
What you’ll be able to do after this tutorial
Section titled “What you’ll be able to do after this tutorial”- Decide where a breakpoint belongs so a changing question does not break the cache.
- Pick between automatic caching and explicit breakpoints, and between the 5-minute and 1-hour lifetimes.
- Read the three
usageinput fields and tell whether a request hit, wrote, or skipped the cache. - Name the usual causes of a cache miss and know where the docs’ diagnostics tool fits.
Concepts to know first
Section titled “Concepts to know first”Dev 2 already gives the money overview: cache first, then batches, effort, and model choice. This lesson stays on caching only.
| Term | Meaning |
|---|---|
| Prefix | Everything from the start of the request up to and including the marked block, in the order tools, system, messages. |
| Breakpoint | A block carrying cache_control. A cache entry is written exactly there, as a hash of the whole prefix up to that block. |
| Cache write | Storing a prefix for the first time. It costs more than normal input. |
| Cache read (hit) | Reusing a stored prefix. It costs a fraction of normal input and refreshes the lifetime. |
| Lookback window | When a breakpoint has no entry, the system checks earlier block positions, at most 20 including the breakpoint, for an entry that an earlier request wrote. |
Prices per million tokens, from the pricing and caching pages (as of 2026-11-16). Always confirm on the official pricing page:
| Model | Base input | 5m write | 1h write | Read | Min. length |
|---|---|---|---|---|---|
Claude Fable 5.2 (claude-fable-5-2) |
$8 | $10 | $16 | $0.20 | 512 |
Claude Fable 5.1 (claude-fable-5-1, previous version) |
$10 | $12.50 | $20 | $0.25 | 512 |
Claude Opus 5.5 (claude-opus-5-5) |
$4 | $5 | $8 | $0.20 | 512 |
Claude Sonnet 5.5 (claude-sonnet-5-5) |
$2 | $2.50 | $4 | $0.10 | 512 |
Claude Haiku 5.5 (claude-haiku-5-5), prompt up to 100,000 tokens |
$0.10 | $0.125 | $0.20 | $0.01 | 512 |
These multipliers stack with other modifiers such as the Batch API discount. On Claude Haiku 5.5, cache reads and writes count toward the prompt length that decides which price tier a request falls in.
Step-by-step guide
Section titled “Step-by-step guide”-
Order the prompt: stable first, changing last
The cache works on a prefix, so a single changed byte before the breakpoint means a different hash and no hit. Put tool definitions, system instructions, long documents, and examples first. Put the question, timestamps, and per-request context last.
The docs describe a common mistake. A large static system context (blocks 1 to 5) is followed by a block with a timestamp and the user message (block 6), and
cache_controlsits on block 6. Every request writes a new entry and never reads one, because the lookback only finds entries that earlier requests wrote at their own breakpoints. The fix is to move the breakpoint to block 5, the last block that stays identical. -
Choose automatic caching or explicit breakpoints
Automatic caching Explicit breakpoints How One "cache_control": {"type": "ephemeral"}at the top level of the requestcache_controlon individual content blocksBreakpoint Placed on the last cacheable block and moved forward each turn Where you put it, up to 4 per request Best for Multi-turn conversations where the history keeps growing A static prefix followed by a varying part, or sections that change at different speeds They can be combined; the automatic breakpoint then uses one of the 4 slots. Edge cases from the docs: if the last block already has
cache_controlwith a different TTL, the API returns a 400 error, and if 4 explicit breakpoints already exist, automatic caching also returns a 400 error. Automatic caching is not available on the legacy Amazon Bedrock integration for Opus 4.6 and earlier, where a top-levelcache_controlreturns a 400 error.A growing conversation with automatic caching is safe while each turn adds fewer than 20 blocks. If a turn adds more, the lookback can miss the earlier entry; the docs suggest adding a second breakpoint closer to it.
-
Write the demo script
Save a long, unchanging text as
company_manual.txt(at least 512 tokens for this model), then save this ascache_demo.py. It puts the manual insystemwith the breakpoint on that block and sends the question as the user message, which is the part after the breakpoint.import sysfrom pathlib import Pathimport anthropicMODEL = "claude-opus-5-5"# Long, unchanging text (a manual, a policy). It must be at least 512 tokens# for this model, or nothing is cached and no error is raised.MANUAL = Path("company_manual.txt").read_text(encoding="utf-8")client = anthropic.Anthropic()def ask(question):response = client.messages.create(model=MODEL,max_tokens=300,system=[{"type": "text", "text": "You answer questions using only the manual below."},{"type": "text","text": MANUAL,# Breakpoint on the LAST block that stays identical across requests."cache_control": {"type": "ephemeral"},},],# The part that changes goes after the breakpoint.messages=[{"role": "user", "content": question}],)u = response.usagewritten = u.cache_creation_input_tokens or 0read = u.cache_read_input_tokens or 0total = read + written + u.input_tokensprint(f"uncached input {u.input_tokens} | cache write {written} | cache read {read} | total input {total}")if written == 0 and read == 0:print(" Not cached. Is the prefix under the model minimum (512 tokens here)?")return responseif __name__ == "__main__":for q in sys.argv[1:] or ["How many vacation days do I get?", "What is the remote work policy?"]:ask(q) # first call should show a cache write, the second a cache readThe block shapes (a
systemlist withcache_controlon the last text block) follow the docs’ large-context example. SetANTHROPIC_API_KEYas in C16 and runpython cache_demo.py. Not run against the real API. I only ran it with a local stub, which proved the printing logic and that the breakpoint sits on the last system block.Expected shape: the first call shows a cache write and the second a cache read, if the second starts within the lifetime. The docs also warn that a cache entry becomes available only after the first response starts, so for parallel requests wait for the first response before sending the rest.
-
Read the
usagefieldsField Meaning (docs) cache_creation_input_tokensTokens written to the cache by this request cache_read_input_tokensTokens read from the cache input_tokensOnly tokens after the last breakpoint, not your whole input Total input is
cache_read_input_tokens + cache_creation_input_tokens + input_tokens. The docs’ example: 100,000 cached tokens read plus a 50-token question givesinput_tokens: 50and 100,050 tokens processed. If both cache fields are 0, the prompt was not cached, most likely because it was under the minimum length. With a 1-hour entry the response also contains acache_creationobject withephemeral_5m_input_tokensandephemeral_1h_input_tokens, and the older field equals their sum. -
Choose the lifetime and check the break-even
The default is 5 minutes. Each hit refreshes it at no extra charge, and it is measured from the start of the request, so a response that streams for 4 minutes leaves only about 1 minute for the follow-up. Use the 1-hour option when the same prefix is reused less often than every 5 minutes but more often than every hour, for example a side agent that runs longer than 5 minutes. The docs say cache hits are not deducted against your rate limit, which is another reason some teams choose it.
In one request you may mix both lifetimes, but a 1-hour entry must appear before any 5-minute entry.
Save this as
cache_breakeven.py. It only computes prices, so it needs no API key. It ignores new input and output and assumes the cache never expires between requests.# Prices in USD per million tokens, from the official pricing page (as of 2026-11-02).# (base input, 5m cache write, 1h cache write, cache read)PRICES = {"claude-opus-5-5": (4.00, 5.00, 8.00, 0.20),"claude-sonnet-5-5": (2.00, 2.50, 4.00, 0.10),}def prefix_cost(model, prefix_tokens, requests, mode):"""Cost of the shared prefix only (new input and output are ignored).mode: "none", "5m", or "1h". Assumes the cache never expires between requests."""base, w5, w1h, read = PRICES[model]m = prefix_tokens / 1_000_000if mode == "none":return requests * m * basewrite = w5 if mode == "5m" else w1hreturn m * write + (requests - 1) * m * readif __name__ == "__main__":model, tokens = "claude-opus-5-5", 20_000print(f"{model}, {tokens} cached tokens, prefix cost only")for n in (1, 2, 3, 5, 10):row = {mode: prefix_cost(model, tokens, n, mode) for mode in ("none", "5m", "1h")}print(f"requests={n:2d} none=${row['none']:.4f} 5m=${row['5m']:.4f} 1h=${row['1h']:.4f}")I ran it. Result for a 20,000-token prefix on Claude Opus 5.5:
Requests No cache 5-minute 1-hour 1 $0.0800 $0.1000 $0.1600 2 $0.1600 $0.1040 $0.1640 3 $0.2400 $0.1080 $0.1680 10 $0.8000 $0.1360 $0.1960 This matches the pricing page’s statement: the 5-minute cache pays off after one read, the 1-hour cache after two. One request alone costs more with caching than without, so caching a prefix you will never reuse loses money.
-
Find out why a cache missed
The docs list what invalidates which level (
toolstosystemtomessages; a change invalidates that level and everything after it):Change Effect Tool definitions (names, descriptions, parameters) Whole cache Web search or citations toggle, speed setting ( fastvs standard)System and messages tool_choice, adding or removing images anywhereMessages Thinking parameters, output_config.effortMessages always; tools and system depend on the model Other checks from the troubleshooting list: cached sections identical across calls, requests inside the lifetime, prefix above the minimum, and stable key ordering inside
tool_useblocks (some languages, for example Swift and Go, randomize JSON key order). Caches are isolated by workspace on the Claude API, Claude Platform on AWS and Microsoft Foundry, so the same prefix in two workspaces does not share a cache. There is no way to clear a cache manually.For harder cases the docs offer cache diagnostics. Include a
diagnosticsobject withprevious_message_idset to the previous responseid(nullon the first turn), and the response reports the first point where the request diverged, with acache_miss_reasonofmodel_changed,system_changed,tools_changed,messages_changed,previous_message_not_found, orunavailable. It is available on the Claude API only (not Bedrock or Google-managed Google Cloud), and the docs’ Python example calls it throughclient.beta.messages. I read the page but did not run it. -
Optional: warm the cache before users arrive
Sending
max_tokens: 0makes the API read the prompt and write the cache at your breakpoints, then return an emptycontentarray withstop_reason: "max_tokens"and no output tokens billed. A write is still charged if the prefix was not cached. Put the breakpoint on the last block shared with the real requests (not on the placeholder user message such as"warmup"), and use the same thinking andeffortsettings. The request is rejected withstream: true, extended thinking, structured outputs, forcedtool_choice, and inside a Message Batches request.Copy and paste this promptReview my Claude API request for prompt caching. Tell me which blocks never change and which change on every request, where one cache_control breakpoint should go, whether the cached part is likely above the 512-token minimum for claude-opus-5-5, and which of my parameters (tools, tool_choice, images, thinking, effort) could silently break the cache. Do not invent token counts; tell me how to check them. Here is my request with secrets removed: (paste your request body)
Quick reference
Section titled “Quick reference”| Item | Value (official docs, as of 2026-11-16) |
|---|---|
| Enable | Top-level "cache_control": {"type": "ephemeral"} or the same on content blocks |
| Prefix order | tools, system, messages |
| Breakpoints | Up to 4 explicit per request; lookback 20 positions per breakpoint |
| Lifetime | 5 minutes default, refreshed on each hit; 1 hour with "ttl": "1h" |
| Write / read price | 5m 1.25x, 1h 2x, read 0.1x (0.05x on Opus 5.5 and Sonnet 5.5, 0.025x on Fable 5.2 and Fable 5.1) |
| Minimum length | 512 tokens on Fable 5.2, Fable 5.1, Opus 5.5, Opus 5, Sonnet 5.5, Haiku 5.5; 1,024 on Sonnet 5 and Opus 4.8; larger for some older models |
| Cannot be cached directly | Thinking blocks (they can ride along in earlier assistant turns), sub-content such as citations (cache the top-level document), empty text blocks |
| Data | Eligible for zero data retention (excludes Covered Models); KV cache and hashes held in memory for the lifetime |
Common sticking points
Section titled “Common sticking points”cache_read_input_tokens is always 0
Section titled “cache_read_input_tokens is always 0”- Cause: The prefix is under the minimum, a value before the breakpoint changes every request, the breakpoint is on the changing block, or the gap between requests is longer than the lifetime.
- Fix: Print all three usage fields, move the breakpoint to the end of the static prefix, and send the second request soon after the first. Try cache diagnostics on the Claude API.
Parallel requests all write the cache
Section titled “Parallel requests all write the cache”- Cause: An entry becomes available only after the first response starts.
- Fix: Send one request, wait for its response to begin, then send the rest.
A 400 error after adding a breakpoint
Section titled “A 400 error after adding a breakpoint”- Cause: The docs list conflicts such as a different TTL on the last block, or already having 4 explicit breakpoints when automatic caching adds one.
- Fix: Use the same TTL, or drop an explicit breakpoint.
The cache missed after I changed effort or thinking
Section titled “The cache missed after I changed effort or thinking”- Cause: These settings are rendered into the prompt, so changing them invalidates cached messages.
- Fix: Keep them constant within a cached conversation. Models that support per-message effort can carry a change in a
role: "system"message without breaking the cached prefix.
Caching with batches saves less than expected
Section titled “Caching with batches saves less than expected”- Cause: Batch requests run concurrently and in any order, so the docs say cache hits are best-effort.
- Fix: See Dev 16. The docs suggest sending one request with the shared prefix and a 1-hour cache block first, then the rest once it completes.
Practical tips
Section titled “Practical tips”- Log the three cache fields next to the usage data from Dev 11 so the hit rate stays visible over time.
- Start with one breakpoint at the end of the static prefix. Add more only when sections change at different speeds or a conversation grows past 20 blocks per turn.
- Do not put timestamps, request IDs, or user names in the cached part.
- Caching does not change the model’s output. The docs say the response is identical to one without caching.
- Cached content is stored only in memory for its lifetime, but still do not put secrets in a prompt you do not need to send.
Next tutorials
Section titled “Next tutorials”- 2. Cut API costs with prompt caching, batches, and effort — the full cost picture
- 14. Token counting API — check prefix length before you send
- 16. Large jobs with the Batches API — caching inside batches
- 17. Adaptive thinking and effort — how thinking settings interact with the cache
- 11. Team usage dashboard with the usage and cost API — track spending over time
- C16. Getting started with the Claude API
Sources
Last verified: Nov 16, 2026
- Prompt caching platform.claude.com
- Cache diagnostics platform.claude.com
- Pricing platform.claude.com
Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.
Finished this tutorial?
Progress is saved only in this browser and never sent anywhere.