Claude Prompt Caching: Where to Mark, Verify Hits, Check Bills

Blog / Developer tools

Claude Prompt Caching: Where to Mark, Verify Hits, Check Bills

Claude prompt caching saves money on one condition: your requests share a large prefix that is identical every time, such as a long system prompt, tool definitions, or an entire codebase as context. Mark that prefix with cache_control. The first request writes it to the cache, and requests within the cache lifetime are billed at the cache read price, which is far below the normal input price. If the prefix is too short, changes often, or requests are spaced too far apart, the cache either does not apply or the write surcharge never pays off.

This article covers how it works, when to use it, how to mark requests, how to verify hits, and how to do the cost math. Field names and behavior follow the official Anthropic documentation; parameters Anthropic may change are flagged in the text.

What does Claude prompt caching actually cache?

It caches the prompt prefix, not the answer. When the model processes input it produces intermediate state. The cache stores the state for the prefix, and if the next request is byte-for-byte identical from the start up to the cache breakpoint, that state is reused instead of recomputed.

Several things follow from this:

  • Matching is prefix matching. If any character in the prefix changes, everything after the change must be recomputed.
  • The prefix order is fixed: tools first, then system, then messages. Changing a tool definition invalidates every cache after it; changing the last user message affects only that message.
  • Output tokens are unaffected. Caching only lowers the cost and processing time of the input side.
  • The cache has a lifetime. The official docs give a default of 5 minutes, refreshed on each hit, plus an optional 1-hour lifetime ("ttl": "1h") with a higher write price. Check the official docs and pricing page for exact durations and prices.

Which scenarios are worth it, and which are not?

The test is how many times the same prefix will be reused within the cache lifetime.

ScenarioIs the prefix stable?Reuse frequencyAdvice
Long system prompt + multi-turn chatStableHigh when the user keeps askingWorth it; put the breakpoint at the end of the system prompt
Coding agent reading codebase contextStable until files changeMany calls within one taskVery worth it; put the breakpoint at the end of the context
Many tool definitions (dozens of tools)StableSent with every callWorth it; tools come first, so they suit caching naturally
Repeated Q&A over one long documentStableDepends on question densityWorth it; put the document before the question
Batch processing unrelated short textsDifferent every timeNo reuseNot worth it; only a shared instruction block might be long enough
System prompt with current time or request ID mixed inChanges every timeNoneMove the changing content to the end first, then think about caching
Only a few calls per dayStableGaps far longer than the lifetimeNot worth it; you pay the write surcharge every time

The last two rows are the most common reason caching ends up costing more. Writing to the cache is more expensive than normal input, so if nobody reads what you wrote, it is pure loss.

There is also a minimum length threshold. If the prefix is too short, the request does not fail, but it is not cached either, and both cache fields in usage are 0. The threshold varies by model; check the prompt caching page in the official docs for the numbers.

How do you mark a request for caching?

Add cache_control to the content block where you want the cache to end. Here is a minimal example that caches a long system prompt:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "<the model ID you use>",
    "max_tokens": 1024,
    "system": [
      {
        "type": "text",
        "text": "<a long, fixed system prompt goes here, e.g. coding standards, project notes, API docs>",
        "cache_control": {"type": "ephemeral"}
      }
    ],
    "messages": [
      {"role": "user", "content": "这个函数为什么会在并发时出错?"}
    ]
  }'

(The user message above, "这个函数为什么会在并发时出错?", means "Why does this function fail under concurrency?")

Key points:

  1. Put the breakpoint at the end of the stable content. Everything before the breakpoint, including tools, becomes part of this cache.
  2. Put changing content after the breakpoint. The current time, user ID, and this turn's question must not appear before it.
  3. A request can have multiple breakpoints, up to a limit set in the official docs (currently 4). A common pattern for multi-turn chat is one at the end of the system prompt and another on the last message of the conversation history, so history is also reused turn by turn.
  4. For a longer lifetime, write {"type": "ephemeral", "ttl": "1h"}. This only pays off when requests are often spaced beyond the default lifetime but still return within an hour.

The Python SDK works the same way: pass a list for system and add the cache_control field to the relevant block. A multi-turn example:

messages = history + [{
    "role": "user",
    "content": [{
        "type": "text",
        "text": question,
        "cache_control": {"type": "ephemeral"},
    }],
}]

On the next request, that message is already part of the history, so the prefix can hit, and the new breakpoint moves further back.

How do you confirm the cache actually hit?

Look at usage in the response. Three fields matter:

FieldMeaning
cache_creation_input_tokensTokens written to the cache this time, billed at the write price
cache_read_input_tokensTokens read from the cache this time, billed at the read price
input_tokensNormal input tokens after the last breakpoint that did not go through the cache

Total input for the request is the sum of the three. Note that input_tokens does not include the cached portion, so looking at it alone makes it seem as if the input shrank.

The simplest verification flow:

  1. Send two requests with the same prefix, a few seconds apart.
  2. The first should show cache_creation_input_tokens greater than 0 and cache_read_input_tokens equal to 0.
  3. The second should be the reverse: reads greater than 0, writes at 0 or very small.
  4. If both cache fields are 0 on both requests, check in order: whether the prefix reaches the minimum length; whether anything before the breakpoint changes on every request; whether cache_control is on the right block.
  5. If the second request shows large writes again, the prefix changed between the two requests. Common causes are an unstable tool list order, field order changing during JSON serialization, or a timestamp in the system prompt.

You can pull the three fields into your logs with a one-line jq:

... | jq '.usage | {in: .input_tokens, write: .cache_creation_input_tokens, read: .cache_read_input_tokens, out: .output_tokens}'

In production, log these fields per request and compute a cache read ratio = read / (in + write + read). If that ratio stays low for a long time, either the cache design has a problem or the traffic pattern does not suit caching.

How do you estimate the savings?

You can work out the cache economics like this. Let the base input price be P, the write multiplier w (greater than 1), the read multiplier r (much less than 1), the prefix length L, and the number of reuses within the lifetime n:

  • Without cache: prefix cost = (n + 1) × L × P
  • With cache: prefix cost = L × P × w + n × L × P × r

As long as n is at least 1 and r is small enough, caching is usually cheaper. When n is 0, the extra you pay is (w − 1) × L × P. Check Anthropic's official pricing page for current values of w and r; the write multiplier differs by lifetime.

The script below takes your own numbers (the price and multipliers in the example are placeholders and must be replaced with values from the pricing page):

def prefix_cost(L, n, P, w, r):
    no_cache = (n + 1) * L * P
    with_cache = L * P * w + n * L * P * r
    return no_cache, with_cache

# Assumption: 20,000-token prefix, reused 10 times; replace P, w, r with values from the official pricing page
L, n = 20_000, 10
P = 1.0 / 1_000_000   # placeholder: base input price per token
w, r = 1.0, 1.0       # placeholder: write multiplier, read multiplier
print(prefix_cost(L, n, P, w, r))

A more reliable method is to verify against a real bill: sum the usage for the same kind of task before and after enabling caching, multiply by the corresponding prices, and compare the totals. If your bill and usage do not match, see AI API bills don't add up: token counting and how to reconcile. Prices change too; subscribe to cdnping's site changes feed, which logs additions and removals on the Claude pricing page line by line. For more tracking methods, see How to find out immediately when LLM API prices change.

Does caching make responses faster?

Yes, but only for the server-side input processing step. When a long prefix hits the cache, the model does not reprocess that input, so time to first token (TTFT) usually drops. It does not affect connection setup or network round trips.

For reference, on October 17, 2026, cdnping probed api.anthropic.com from a Cloudflare edge node (DEN), and the samples collected that day showed a median round trip of 73 ms and a P95 of 84 ms. cdnping only began collecting on that day, so the sample covers less than a full day. This is a network-layer figure from a US data center; it does not represent your local conditions and excludes model processing time. To measure how far your own network is from the Claude API, use the speed test on the cdnping homepage; to see whether the API is currently up, check the Claude API status page.

Breaking one request's latency into connect, round trip, and TTFT makes it clearer how much caching actually helped. See AI API latency breakdown: connection setup, gateway round trip, and time to first token.

Does caching still work through a gateway or relay?

Not necessarily; you have to test it. Whether caching works depends on whether the intermediate layer passes cache_control upstream unchanged, whether it inserts its own content into the prefix, and whether it faithfully returns the cache-related usage fields in the response. Also, caches are not shared across organizations, so if the intermediate layer routes consecutive requests to different upstream accounts, the second request may not be able to read what the first one wrote.

The check is the same as above: send the same prefix twice and look at cache_read_input_tokens on the second. If the intermediate layer does not return that field, you cannot tell from usage whether caching worked, and you cannot verify whether a cache discount was applied to billing, so ask about this before choosing one. For a fuller list of evaluation points, see How to choose an AI API relay: uptime, billing, and data policy checks.

Take AGI Plan as an example (AGI Plan is a commercial partner of cdnping). It is a multi-provider aggregation gateway; the operator states that it is not an officially authorized channel, that it is compatible with the Anthropic API format, and that it meters usage in CU. With it or any third-party endpoint, test the cache-related fields yourself using the steps above and go by the measured results. For how to change the endpoint address in tools like Claude Code, see Configuring a custom API endpoint in Claude Code, Codex, and OpenCode.

Pre-launch checklist

  • Prefix length exceeds the minimum cacheable length for the model you use (check the official docs)
  • Nothing that changes every request (timestamps, request IDs, random numbers, usernames) appears before the breakpoint
  • Tool list order is fixed and JSON serialization is stable
  • The system prompt and document context come before the question
  • In multi-turn chat, a breakpoint is set on the latest message, and the total number of breakpoints stays within the official limit
  • The typical gap between requests falls within the cache lifetime; where gaps are longer, you have evaluated whether ttl: "1h" pays off
  • Logs record input_tokens, cache_creation_input_tokens, cache_read_input_tokens, and output_tokens
  • You monitor the cache read ratio and have an alert for when it drops below a threshold
  • You have multiplied a week of real usage by current prices and confirmed that total cost actually went down

Caching addresses the cost of repeated input. If most of your spend is on output, or many requests could go to a cheaper model, caching will not help much; see How to do multi-model routing: split traffic by task to cut LLM costs. The two approaches can be used together.

Related articles

Keep reading