Skip to content
한국어

Cut Cost and Latency with Prompt Caching

In short
  • A cache stores the processed prefix of your prompt. The prefix is built in the order tools, then system, then messages, up to and including the block marked with cache_control. A hit needs the prefix to be 100 percent identical.
  • Two ways to turn it on: automatic caching (one top-level cache_control field; 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 anthropic package), 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 usage input 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.

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.

0/6 done
  1. 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_control sits 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.

  2. Choose automatic caching or explicit breakpoints

    Automatic caching Explicit breakpoints
    How One "cache_control": {"type": "ephemeral"} at the top level of the request cache_control on individual content blocks
    Breakpoint 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_control with 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-level cache_control returns 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.

  3. Write the demo script

    Save a long, unchanging text as company_manual.txt (at least 512 tokens for this model), then save this as cache_demo.py. It puts the manual in system with the breakpoint on that block and sends the question as the user message, which is the part after the breakpoint.

    import sys
    from pathlib import Path
    import anthropic
    MODEL = "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.usage
    written = u.cache_creation_input_tokens or 0
    read = u.cache_read_input_tokens or 0
    total = read + written + u.input_tokens
    print(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 response
    if __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 read

    The block shapes (a system list with cache_control on the last text block) follow the docs’ large-context example. Set ANTHROPIC_API_KEY as in C16 and run python 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.

  4. Read the usage fields

    Field Meaning (docs)
    cache_creation_input_tokens Tokens written to the cache by this request
    cache_read_input_tokens Tokens read from the cache
    input_tokens Only 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 gives input_tokens: 50 and 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 a cache_creation object with ephemeral_5m_input_tokens and ephemeral_1h_input_tokens, and the older field equals their sum.

  5. 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_000
    if mode == "none":
    return requests * m * base
    write = w5 if mode == "5m" else w1h
    return m * write + (requests - 1) * m * read
    if __name__ == "__main__":
    model, tokens = "claude-opus-5-5", 20_000
    print(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.

  6. Find out why a cache missed

    The docs list what invalidates which level (tools to system to messages; 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 (fast vs standard) System and messages
    tool_choice, adding or removing images anywhere Messages
    Thinking parameters, output_config.effort Messages 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_use blocks (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 diagnostics object with previous_message_id set to the previous response id (null on the first turn), and the response reports the first point where the request diverged, with a cache_miss_reason of model_changed, system_changed, tools_changed, messages_changed, previous_message_not_found, or unavailable. It is available on the Claude API only (not Bedrock or Google-managed Google Cloud), and the docs’ Python example calls it through client.beta.messages. I read the page but did not run it.

  7. Optional: warm the cache before users arrive

    Sending max_tokens: 0 makes the API read the prompt and write the cache at your breakpoints, then return an empty content array with stop_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 and effort settings. The request is rejected with stream: true, extended thinking, structured outputs, forced tool_choice, and inside a Message Batches request.

    Copy and paste this prompt

    Review 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)

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
  • 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.
  • 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.
  • 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.
  • 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.

Sources

Last verified: Nov 16, 2026

Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.