Anthropic Prompt Caching: Cut Claude API Costs
Learn how Anthropic prompt caching works, use cache_control with Sonnet 5 and Opus 5, and compare cache read and write pricing per million tokens.

The anthropic prompt caching question usually starts the same way: an app
sends a large system prompt, tool definitions, or conversation history on
every request, and the bill grows faster than expected. Anthropic prompt
caching is the mechanism that stores a processed prefix so later requests can
read it back instead of reprocessing it. It is not an invisible default
optimization. You enable it with cache_control, keep the cached prefix
stable, and work inside a cache lifetime. When those three conditions are
met, reused input tokens are billed at 10% of the base input price and
time-to-first-token for long prompts drops.
This guide explains how Anthropic prompt caching works, how to call the Anthropic prompt caching API with Python and cURL, what cache read and cache write pricing looks like for Claude Sonnet 5 and Claude Opus 5, and how a support agent can use it to reduce monthly token spend. All pricing was checked on 2026-09-16 against Anthropic's official prompt caching documentation and live OurToken model pages.
Verification status: Cache rules and prices below were checked against live sources on 2026-09-16. Product defaults change, so confirm current Anthropic prompt caching documentation and your provider's model page before writing production runbooks.
Anthropic Prompt Caching: How Cache Breaks Down
Anthropic prompt caching stores a tokenized prefix, not a semantic summary. When a request starts with the same block sequence as a recent request, the API can reuse the stored representation from the last cache breakpoint. The cache write happens when the request begins generating a response; the cache read happens on later requests that match the prefix. Every read refreshes the entry, and the default lifetime is 5 minutes measured from the start of the request that writes or reads it.
request 1: [ system prompt ][ tool schemas ][ conversation history ][ user message ]
\____________________ cache write at breakpoint ___________________/
request 2: [ identical prefix ][ new user message ]
\ cache read / \ fresh input /
Three usage fields make the behavior visible. usage.cache_creation_input_tokens
counts tokens written to the cache, usage.cache_read_input_tokens counts
tokens read from the cache, and usage.input_tokens counts uncached input
after the last breakpoint. A simple way to verify caching is to run two
identical requests: the first should show cache_creation_input_tokens, and
the second should show cache_read_input_tokens.
Automatic caching and explicit cache_control
Anthropic prompt caching can be enabled two ways. Top-level automatic caching
adds one "cache_control": {"type": "ephemeral"} field to the request, and
the system places the breakpoint on the last cacheable block. Explicit
caching places cache_control directly on individual content blocks.
Explicit blocks are the right choice when the static prefix changes less
often than the conversation tail or when you want a predictable cache
boundary.
A request can define up to four cache breakpoints. Cache matching is exact: text, images, tool definitions, and block order must be identical up to the marked block. The system looks backward up to 20 blocks from a breakpoint to find a prior write, so a breakpoint that moves more than 20 blocks between requests can miss an earlier cache entry.
The minimum cacheable prompt length is model-specific. On the Claude API, Claude Sonnet 5 requires 1,024 cacheable tokens and Claude Opus 5 requires 512 tokens. Shorter prompts are not cached even when marked; no error is returned, and both cache usage fields remain zero.
What invalidates the cache
The cache is invalidated by any change to the prefix before a breakpoint. The most common production causes are:
- Dynamic system prompts that include timestamps, session IDs, or user-specific values
- Tool definitions that change between requests
tool_choiceor thinking configuration changes rendered into the prompt- A cache breakpoint placed on a block that changes every request
- Context trimming that removes or rewrites earlier conversation blocks
The fix is structural: put stable content first, place the breakpoint after the last block that stays identical, and move dynamic content into the user message or after the breakpoint. This is why the same 2,000-token system prompt can produce a cache hit in one client and a full reprocess in another.
Anthropic Prompt Caching Setup: Python and cURL
The Anthropic prompt caching API uses the Messages request shape. The example below targets an OurToken endpoint, reads the API key from an environment variable, retries transient network errors, and logs cache usage after each call. It marks the system prompt as cacheable with an explicit breakpoint.
Python example with retries and cache logs
import json
import os
import time
import urllib.error
import urllib.request
API_URL = "https://api.ourtoken.ai/v1/messages"
API_KEY = os.environ["OURTOKEN_API_KEY"]
MODEL = "claude-sonnet-5"
MAX_RETRIES = 3
def call_with_cached_system(system_prompt: str, user_message: str) -> dict:
body = {
"model": MODEL,
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"},
}
],
"messages": [{"role": "user", "content": user_message}],
}
payload = json.dumps(body).encode("utf-8")
for attempt in range(1, MAX_RETRIES + 1):
request = urllib.request.Request(
API_URL,
data=payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
result = json.load(response)
break
except (urllib.error.URLError, TimeoutError) as error:
if attempt == MAX_RETRIES:
raise
wait = 2**attempt
print(f"Retry {attempt} in {wait}s: {error}")
time.sleep(wait)
else:
raise RuntimeError("Request failed after retries")
usage = result.get("usage", {})
print("Input tokens:", usage.get("input_tokens"))
print("Cache creation tokens:", usage.get("cache_creation_input_tokens"))
print("Cache read tokens:", usage.get("cache_read_input_tokens"))
print("Output tokens:", usage.get("output_tokens"))
return result
if __name__ == "__main__":
prompt = "You are a support agent. Use only the policy appendix below."
result = call_with_cached_system(prompt, "How do I reset my password?")
print("First response:", result["content"][0]["text"][:120])
The function reads OURTOKEN_API_KEY from the environment, so the key never
appears in source control. The retry loop is capped at three attempts and
uses exponential backoff. After each response, the printed usage fields tell
you whether the prefix was written or read.
cURL example
The same request in cURL:
curl https://api.ourtoken.ai/v1/messages \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OURTOKEN_API_KEY" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are a support agent. Use only the policy appendix below.",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{"role": "user", "content": "How do I reset my password?"}
]
}'
For SDK-based applications, LangChain ships an
anthropicPromptCachingMiddleware for JavaScript that can add cache control
to recent messages. The middleware supports options such as cacheUntil and
minMessagesToCache, which is useful when a long conversation should only
start caching after a few turns. See the
LangChain reference
for current import paths and options.
Anthropic Prompt Caching Pricing: Cache Reads vs Cache Writes
Anthropic pricing uses three multipliers for the standard 5-minute cache: a cache write is 1.25x the base input price, a cache read is 0.1x the base input price, and output is unchanged. A 1-hour cache write is 2x the base input price on Anthropic's official list. The table below compares official list prices with the current OurToken prices for the two Claude 5 models.
| Item (per 1M tokens) | Anthropic official | OurToken current |
|---|---|---|
| Claude Sonnet 5 input | $2.00 | $0.80 |
| Claude Sonnet 5 cache write, 5m | $2.50 | $1.00 |
| Claude Sonnet 5 cache read | $0.20 | $0.08 |
| Claude Sonnet 5 output | $10.00 | $4.00 |
| Claude Opus 5 input | $5.00 | $2.00 |
| Claude Opus 5 cache write, 5m | $6.25 | $2.50 |
| Claude Opus 5 cache read | $0.50 | $0.20 |
| Claude Opus 5 output | $25.00 | $10.00 |
The OurToken figures are 40% of the official prices shown on Claude Sonnet 5 and Claude Opus 5 model pages. All values were verified on 2026-09-16.
Where the savings come from
A cache write is the expensive event, but it is paid once per changed prefix. Every cache read after that is 10x cheaper than processing the same tokens as fresh input. The real metric is the amortized cost: write once, read many times, refresh for free each time the cached prefix is used within its lifetime.
The same principle explains why Anthropic prompt caching matters for agent
loops. Coding agents such as Claude Code resend system prompts, tool
definitions, and repository context across turns. A
Claude Code API pricing vs subscription guide
explains why a claude code api pricing analysis that ignores caching
overstates the cost of long agent sessions. The same input tokens may be
billed as expensive writes on turn one and cheap reads on turns two through
twenty.
LLM API pricing comparison
Anthropic and OpenAI implement caching differently. OpenAI prompt caching is
best-effort and uses provider-managed cache controls; Anthropic prompt
caching requires explicit cache_control but gives the developer a
deterministic breakpoint. An
OpenAI-compatible prompt caching guide
and an
OpenAI prompt caching API guide
cover the other side of that comparison. For a broader view, the
LLM model routing guide
explains when a cheaper model route, a cached prompt, or a different provider
is the right lever.
One caveat: a direct "X model is cheaper" comparison can be misleading. An LLM API pricing comparison should include expected cache hit rate, output token volume, retry behavior, and the frequency with which static prompt content changes. If a prompt is rewritten on every request, no provider can cache it.
Real Scenario: A Customer Support Agent
A support agent demonstrates the economics. Assume Claude Sonnet 5 handles 10,000 requests per day. The request has a 50,000-token cached prefix: instructions, tool schemas, and a policy appendix. Each request adds 100 uncached input tokens for the user message and generates 150 output tokens.
Without caching, every request pays for the full 50,000-token prefix:
- Input: 50,000 x $0.80 / 1,000,000 = $0.04000
- User message: 100 x $0.80 / 1,000,000 = $0.00008
- Output: 150 x $4.00 / 1,000,000 = $0.00060
- Cost per request: $0.04068
- Daily cost: $406.80
With caching, the first request writes the prefix at the cache write price, and the next 9,999 requests read it at the cache read price:
- First request cache write: 50,000 x $1.00 / 1,000,000 = $0.05000
- First request user message + output: $0.00068
- Cached requests: 50,000 x $0.08 / 1,000,000 = $0.00400 each
- Cached request user message + output: $0.00068 each
- Daily cost: $0.05068 + 9,999 x $0.00468 = $46.85
The cached setup costs about 88.5% less on input-heavy days. Over 30 days, the difference is about $10,800 per month. Latency improves too, because the cached prefix does not need to be reprocessed before the first output token is generated.
Troubleshooting Anthropic Prompt Caching
| Symptom | Likely cause | Fix |
|---|---|---|
cache_read_input_tokens is always 0 | Prompt is below the minimum or the prefix changes | Verify the model minimum (1,024 for Sonnet 5, 512 for Opus 5) and keep the prefix identical |
| First request is unexpectedly expensive | A cache write costs 1.25x base input | Treat the write as a one-time setup cost and measure after 100+ cache reads |
| Cache misses after a few minutes | Default TTL is 5 minutes and is measured from request start | Keep traffic inside the window or use Anthropic's 1-hour cache at 2x write price |
400 error when combining automatic and explicit caching | Too many breakpoints or TTL mismatch | Stay at four total breakpoints and use the same TTL for all entries |
| Cache hit rate drops after conversation grows | The breakpoint moved more than 20 blocks past the last write | Add a second breakpoint near the previous write position |
| Same prompt does not hit cache in another app | Caches are isolated per key/workspace | Reuse the same key or rewrite the cache under the new key |
| Latency is high on every request | Caching may be disabled or content is dynamic | Log cache_creation_input_tokens and cache_read_input_tokens; run two identical requests to confirm |
| Cache misses at the start of a busy period | Entry expired before traffic arrived | Pre-warm the prefix before user traffic starts |
Pre-warming is a useful production pattern: send a request with max_tokens: 0
and an explicit cache_control breakpoint before users arrive. The response
writes the prefix without generating output, so the first real user request
starts with a warm cache. Keep the same thinking configuration and model
settings used by real traffic.
Conclusion
Anthropic prompt caching works when the cached prefix is stable, the
breakpoint is placed after the last unchanged block, and requests arrive
inside the cache lifetime. Start with explicit cache_control on the system
prompt, monitor cache_creation_input_tokens and cache_read_input_tokens,
then move to automatic caching or multiple breakpoints once the pattern is
proven. The result is usually a large reduction in input spend and a
measurable improvement in time-to-first-token for long-context apps.
For the Anthropic prompt caching API with Claude Sonnet 5 and Claude Opus 5
at 40% of official list price, create an
OurToken API key, use the Messages endpoint at
https://api.ourtoken.ai/v1/messages, and start with the Python example above.
FAQ
Is Anthropic prompt caching automatic?
No. You must send cache_control at the request level for automatic caching
or on individual content blocks for explicit breakpoints. A prompt below the
model minimum is processed without caching and returns no error.
What is the minimum cacheable prompt length?
Claude Sonnet 5 requires 1,024 cacheable tokens. Claude Opus 5 requires 512
tokens. If both cache_creation_input_tokens and cache_read_input_tokens
are zero, the request was not cached.
How much cheaper are cache reads?
For Claude Sonnet 5 and Claude Opus 5, cache reads cost 10% of the base input price. Cache writes cost 25% more than base input for the default 5-minute TTL. On OurToken, that means Sonnet 5 cache reads are $0.08 per million tokens and Opus 5 cache reads are $0.20 per million tokens.
Does prompt caching change the model's output?
No. Prompt caching reuses processed input, not generated responses. Output tokens are billed normally and the response content is not affected by the cache.
Can I use prompt caching with OpenAI models?
OpenAI has its own caching behavior with different parameters and usage fields. See the OpenAI-compatible prompt caching guide and the OpenAI prompt caching API guide for the OpenAI-side setup.
Interpret the fields together, not independently. cache_creation_input_tokens
and cache_read_input_tokens describe the prefix up to the breakpoint, while
input_tokens describes only the uncached suffix after the breakpoint. The
sum of the three equals the total input tokens for a cached request. If
cache_read_input_tokens is high, your static prefix is being reused; if it
is zero on every call, the breakpoint or prefix is wrong.
The multiplier spread is what makes caching useful. A write is 25% more expensive than normal input, but a read is 90% cheaper. A request that reads 50,000 cached tokens and processes 1,000 new ones is still cheaper than one that reprocesses all 51,000 from scratch. The 1-hour TTL changes the write multiplier to 2x, so choose it only when requests can arrive more than five minutes apart or when a single cache entry must survive a longer gap.
The same pattern scales to Claude Opus 5. Input is $2.00 per million tokens, cache writes are $2.50, cache reads are $0.20, and output is $10.00. Without caching, the same 50,000-token prefix costs $0.10170 per request, or $1,017 per day for 10,000 calls. With caching, the first request costs $0.12670, each following request costs $0.01170, and the daily total is about $117.10. Sonnet 5 remains the better default for high-volume support, but the same cache pattern keeps Opus 5 economical for deeper reasoning workloads.