Cost and latency problems rarely show up in a demo. They show up when traffic grows a hundredfold and the invoice, or the p95 response time, stops being a rounding error. The discipline is the same as elsewhere in this course: measure first, change one thing at a time, and protect quality with an evaluation so that "cheaper" does not quietly mean "worse".
Every price in this module is illustrative. The worked examples say "assume $X per million tokens" so you can follow the arithmetic. Real prices, cache multipliers and model names change; check Anthropic's pricing page before you plan a budget. The documented mechanisms (what is cached, what the Batch API trades away) are taken from the official pages listed at the end.
5.1 Prompt caching: stable prefix first
Prompt caching lets the API reuse the processed form of the beginning of a prompt across requests. It matches on an exact prefix, and the docs state the prefix order: tools, then system, then messages, up to the block you mark with cache_control.
That order gives the one rule that governs everything: put stable content first and dynamic content last. Anything that changes on every request (a timestamp, a user id, the current question) must come after the breakpoint. A single changing token before the breakpoint makes every request a miss.
Figure 1. Prompt layout: stable first, dynamic last
How to read this: the prompt is read left to right in the order tools, system, messages; everything inside the box is the exact prefix the cache matches, and the orange node on the right is the only part allowed to change.
Picture it: Pre-printed company stationery. The letterhead is printed in bulk because it never changes; only the blanks are filled in per letter. Print today's date into the letterhead and every sheet becomes unique, so the stack of pre-printed paper is worthless. (The cache is stricter than stationery: one changed character early in the prefix voids everything after it.)
import anthropic
client = anthropic.Anthropic()
MODEL = "your-pinned-model-id" # from your config, not hard-coded across files
response = client.messages.create(
model=MODEL,
max_tokens=500,
system=[
{"type": "text", "text": "You answer questions about the Larkspur Outfitters returns policy."},
{
"type": "text",
"text": POLICY_TEXT, # large, identical on every request
"cache_control": {"type": "ephemeral"}, # breakpoint after the stable part
},
],
messages=[{"role": "user", "content": user_question}], # dynamic, after the breakpoint
)
print(response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens)
Facts from the docs that exam scenarios lean on:
- The default cache lifetime is 5 minutes and is refreshed each time the cached content is used. A 1-hour lifetime is available at additional cost.
- A minimum cacheable size applies, and it differs by model. A prompt shorter than the minimum is processed without caching and no error is returned, which is why a "cache that never hits" is sometimes simply a prompt that is too short. Look up your model in the docs table; do not assume.
- You can set up to four explicit breakpoints. Place one at the end of each segment that changes at a different rate (for example, tool definitions, then a policy document, then conversation history).
- The response
usagereportscache_creation_input_tokens(written),cache_read_input_tokens(read) andinput_tokens(only the tokens after the last breakpoint). Total input is the sum of the three. Watch these fields to know whether caching works. - Caching affects input processing only. Output tokens are never cached; they are billed and generated every time.
- A cache entry becomes available only after the first response begins. If a hundred parallel workers start together with a cold cache, all hundred pay the write. Send one request first, wait for it to start, then fan out.
Figure 2. "The cache did not help": check in this order
How to read this: take the questions from top to bottom; each problem branch ends in its own fix, and the last box is the good news, that caching works and the cost lives elsewhere.
Exam angle. "We added cache_control and the bill did not change." Check three things in order: is the marked block above the minimum size for the model, is anything dynamic ahead of the breakpoint, and does usage show reads at all. Common trap: concluding that caching "does not work for large prompts" or adding more breakpoints without fixing the volatile prefix.
On call, 3 a.m.: Ravi Menon at Cobalt Parcel turns on caching for a long courier-rules prompt and goes to bed pleased. In the morning the invoice looks the same and the usage fields show writes on every call and no reads. The first line of every prompt is Request id: 48213, a new number each time, so no two prefixes are ever equal. He moves the request id below the breakpoint and the next batch of calls reads the rules from the cache. Invented example.
5.2 What invalidates a cache, and what it costs
Because the match is a prefix, a change invalidates everything after the changed point. The docs list what breaks which part. In summary: changing tool definitions invalidates the tools, system and messages caches; changing the system prompt invalidates system and messages; toggles such as web search or citations affect system and messages; changing tool choice or adding or removing images affects the messages cache.
Practical consequence: version your static prefix deliberately. Editing one sentence of a 20,000-token system prompt on a busy service means the next request writes the entire prefix again. Batch prompt edits into releases, and do not generate the prefix from something that varies per request (a rendered date, a randomised example order, a dictionary serialised in unstable key order).
The cost model. Assume a write costs a premium over the normal input price and a read costs a fraction of it. The docs give the multipliers per model and lifetime (they differ by model); for the arithmetic below assume a write at 1.25x and a read at 0.1x the base input price, both illustrative.
Worked example (illustrative prices). Assume input at $3 per million tokens and output at $15 per million. A service sends 1,000 requests inside one cache lifetime, each with a 20,000-token stable prefix, 400 dynamic input tokens and 300 output tokens.
| Item | Per request | Working |
|---|---|---|
| No caching: input | $0.0612 | 20,400 tokens x $3 / 1,000,000 |
| No caching: output | $0.0045 | 300 x $15 / 1,000,000 |
| No caching, 1,000 requests | $65.70 | 1,000 x ($0.0612 + $0.0045) |
| Cached, first request | $0.0807 | write 20,000 x $3.75 / 1,000,000 = $0.075; dynamic $0.0012; output $0.0045 |
| Cached, each later request | $0.0117 | read 20,000 x $0.30 / 1,000,000 = $0.006; dynamic $0.0012; output $0.0045 |
| Cached, 1,000 requests | about $11.77 | $0.0807 + 999 x $0.0117 = $0.0807 + $11.6883 |
The saving is about $53.93, roughly 82%. Notice the break-even: the write premium on the prefix is 20,000 x $0.75 / 1,000,000 = $0.015, and each read saves 20,000 x $2.70 / 1,000,000 = $0.054, so a single reuse within the lifetime already pays back the premium. A prefix that is rarely reused within the lifetime, by contrast, only pays the premium.
Caching also relieves rate limits: tokens read from the cache do not count toward the input-tokens-per-minute limit (see module 2).
5.3 Batch API: cheaper, slower, asynchronous
The Message Batches API processes many requests asynchronously. According to the docs, usage is billed at 50 percent of standard prices, most batches finish within an hour, and a batch expires if it is not done within 24 hours. What you trade away is immediacy: there is no streaming and no response while a user waits.
Use it for work nobody is waiting on: nightly classification, bulk summarisation, evaluation runs, backfills. Do not use it for an interactive chat turn or anything with a latency SLO in seconds.
Figure 3. Two paths: real-time for people, batch for backlogs
How to read this: the top path is a person waiting and gets an immediate stream; the bottom path trades immediacy for half price, and your code collects results later and re-queues anything that did not succeed.
Picture it: Express post versus freight. A parcel that must arrive tomorrow goes express at full price. A pallet of stock for next month goes by freight at half the cost, and nobody stands at the door waiting for it. The mistake is to put the birthday present on the freight lorry because it is cheaper.
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"doc-{doc_id}",
"params": {
"model": MODEL,
"max_tokens": 400,
"messages": [{"role": "user", "content": prompt_for(doc)}],
},
}
for doc_id, doc in documents
]
)
# later: poll until processing_status == "ended", then stream the results
for item in client.messages.batches.results(batch.id):
if item.result.type == "succeeded":
store(item.custom_id, item.result.message)
else:
retry_queue.append(item.custom_id) # errored, canceled or expired
Things to design for, all from the docs:
- A batch is limited to 100,000 requests or 256 MB, whichever comes first. Match results to inputs by
custom_id. - Individual results can be
succeeded,errored,canceledorexpired; the last three are not billed. Your job must re-queue them. - Request parameters are validated asynchronously, so test a request shape with the normal Messages API first.
- Results are retained for a limited time (the docs say 29 days); download them.
- Prompt caching works in batches, but hits are best effort because requests run concurrently and in any order. The docs suggest the 1-hour lifetime for batches with shared context.
Worked example (illustrative prices). A nightly job processes 50,000 documents, each 2,000 input tokens and 500 output tokens. Assume $3 per million input and $15 per million output. Synchronously: input 50,000 x 2,000 = 100,000,000 tokens = $300; output 50,000 x 500 = 25,000,000 tokens = $375; total $675. At the 50% batch discount: $337.50, a saving of $337.50 with a longer, uncertain completion time.
Exam angle. An overnight report job is run synchronously against a rate limit and keeps failing. The batch route removes the contention and halves the cost. Common trap: choosing the Batch API for a feature a user is actively waiting on, because "it is cheaper".
5.4 Right-size the model and route by task
Not every request needs the most capable model. A common design is a small, fast model for routine, well-bounded tasks (classification, extraction, short rewrites) and a larger model for hard reasoning, chosen by a router.
The rule that makes this safe: an evaluation guards the swap. Measure quality on a golden set that includes the hard cases per segment, then lower the model only where the pass rate holds. Routing without an eval trades unmeasured quality for measured savings.
Worked example (illustrative prices). Assume a larger model at $3 / $15 per million input / output tokens and a smaller one at $1 / $5. A typical request has 1,000 input and 400 output tokens.
- Larger model: 1,000 x $3/1M = $0.003, plus 400 x $15/1M = $0.006, total $0.009.
- Smaller model: $0.001 + $0.002 = $0.003.
- If an eval shows 70% of traffic is easy enough for the smaller model: 0.7 x $0.003 + 0.3 x $0.009 = $0.0021 + $0.0027 = $0.0048, about 47% lower than $0.009.
Every model change is a release: re-run the eval, and keep the previous setting to roll back to.
Common trap: picking the smallest model everywhere because "the average score barely moved". Averages hide the hard segment; compare per segment.