Tutorial
Cut LLM costs with prompt caching and token budgets
Lay out prompts so the provider can cache them, measure tokens before you send, and use batch processing and model routing to cut what each request costs.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Most LLM applications send the same thing over and over: a long system prompt, tool definitions, a policy document, the first twenty turns of a conversation. Without caching, the provider processes all of it from scratch on every request and charges full price. With prompt caching, it stores the processed prefix and charges a small fraction to reuse it. On a chat with a long fixed preamble, that is often the single biggest saving available, and it also cuts time to first token.
This tutorial shows how caching works, how to lay out prompts so it actually hits, how to measure tokens and cache use, and the two other levers that go with it: batch processing and model routing. Prices and limits were checked against Anthropic’s and OpenAI’s documentation on 20 November 2026; they change, so re-check before you budget.
How prompt caching works
Caching works on prefixes. The provider caches the processed form of your prompt up to a point, and a later request gets a cache hit only if everything up to that point is byte-for-byte identical. Change one character near the start and everything after it is a miss.
For Claude, the prefix is built in a fixed order: tools, then system, then messages. For OpenAI, it is the rendered prompt from the start. In both cases the rule for you is the same:
Put what never changes first, what changes rarely next, and what changes every request last.
| Position | Content | Changes |
|---|---|---|
| First | Tool definitions | When you deploy |
| System prompt, policies, reference documents | When you deploy or edit content | |
| Earlier conversation turns | Grows, but the old part is stable | |
| Last | The new user message, retrieved snippets, timestamps | Every request |
The most common way to break caching is to put something dynamic early: today’s date in the first line of the system prompt, a user’s name in the instructions, tool definitions in a random order. Move it to the end.
Prices that make it worth doing
Anthropic charges for cache writes and reads as multiples of the model’s base input price:
| Multiplier | |
|---|---|
| Cache write, 5-minute lifetime (default) | 1.25 × input price |
| Cache write, 1-hour lifetime | 2 × input price |
| Cache read | 0.1 × input price (0.05 × on Claude Opus 5.5 and Sonnet 5.5) |
The cache lifetime refreshes for free each time it is read, so a busy endpoint keeps its cache warm. Prompts below a minimum length are not cached at all (512 tokens for the current Opus, Sonnet and Haiku 5.5 models, higher for some older ones), and no error tells you so.
A worked example at list prices for Claude Sonnet 5.5 ($2 per million input tokens): a 50,000-token handbook sent with 1,000 questions in a busy hour.
- Without caching: 50 million input tokens, about $100.
- With caching: one write (50,000 × $2.50/M ≈ $0.13) and 999 reads (about 50 million × $0.10/M ≈ $5), so roughly $5.
The questions and answers cost the same either way. The saving is on the repeated part.
OpenAI caches automatically on supported models without any code change, with a minimum prefix length (1,024 tokens on current models) and a discount on cached input that the documentation says can reach 95%. Its newer models also charge more than standard input for cache writes, so measure rather than assume.
1. Measure before you optimise
Count tokens before you send. Anthropic’s token counting endpoint takes the same arguments as a message and returns the input size:
# count.py
import anthropic
client = anthropic.Anthropic()
handbook = open("handbook.md", encoding="utf-8").read()
count = client.messages.count_tokens(
model="claude-sonnet-5-5",
system=[{"type": "text", "text": "Answer questions about the staff handbook."},
{"type": "text", "text": handbook}],
messages=[{"role": "user", "content": "How many days of annual leave do I get?"}],
)
print(count.input_tokens)
Run this on your real prompts. Teams are often surprised that tool definitions or a “short” system prompt are thousands of tokens.
2. Mark the cache breakpoint
Put a cache_control marker on the last block of the stable prefix. Everything up to and including that block is cached:
# ask.py
import anthropic
client = anthropic.Anthropic()
handbook = open("handbook.md", encoding="utf-8").read()
SYSTEM = [
{"type": "text", "text": "Answer questions about the staff handbook below. "
"Quote the section you rely on. If it is not covered, say so."},
{"type": "text", "text": handbook, "cache_control": {"type": "ephemeral"}},
]
def ask(question: str) -> str:
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system=SYSTEM,
messages=[{"role": "user", "content": question}],
)
u = resp.usage
print(f"uncached in={u.input_tokens} cache write={u.cache_creation_input_tokens} "
f"cache read={u.cache_read_input_tokens} out={u.output_tokens}")
return "".join(b.text for b in resp.content if b.type == "text")
ask("How many days of annual leave do I get?")
ask("What is the policy on working from abroad?")
The first call prints a large cache write and the second a large cache read. Total input is the sum of the three input figures. If both calls show zero for write and read, the prefix is under the minimum length or something before the breakpoint differs between calls.
You can mark up to four breakpoints, which helps when parts of the prefix change at different rates: one after the tools, one after the system prompt, one at the end of the conversation history. Anthropic’s API also supports automatic caching with a single top-level cache_control field, which places the breakpoint on the last cacheable block and moves it forward as a conversation grows. That is the simplest option for multi-turn chat.
3. Check hits in production
Log the three input fields from every response, alongside the model and a request type. Then compute the share of input served from cache:
def cache_hit_rate(usage) -> float:
total = usage.input_tokens + usage.cache_creation_input_tokens + usage.cache_read_input_tokens
return usage.cache_read_input_tokens / total if total else 0.0
For OpenAI’s Responses API the equivalent field is usage.input_tokens_details.cached_tokens. A tracing tool such as Langfuse records these per span; see Trace an agent with OpenTelemetry.
A healthy chat or agent endpoint with a long fixed preamble should serve most of its input from cache. A low rate usually means a dynamic value near the top of the prompt, traffic too sparse to keep a 5-minute cache warm (consider the 1-hour lifetime), or requests spread across prompt variants.
4. Batch what does not need an answer now
Classification of yesterday’s tickets, summaries of last week’s calls, embeddings for a document import: none of these need a response in two seconds. Anthropic’s Message Batches API and OpenAI’s Batch API both charge 50% of the normal price in exchange for asynchronous processing (results within 24 hours, usually much sooner). Batch requests can use prompt caching too.
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"ticket-{t['id']}",
"params": {
"model": "claude-haiku-5-5",
"max_tokens": 256,
"system": SYSTEM,
"messages": [{"role": "user", "content": t["text"]}],
},
}
for t in tickets
]
)
print(batch.id, batch.processing_status)
Poll with client.messages.batches.retrieve(batch.id) and read results with client.messages.batches.results(batch.id) when processing has ended.
5. Route by difficulty
Not every request needs your most capable model. A simple router sends easy, high-volume work to a small model and escalates the rest:
def pick_model(task: str, text: str) -> str:
if task in {"classify", "extract", "route"}:
return "claude-haiku-5-5"
if len(text) > 20_000 or task == "plan":
return "claude-opus-5-5"
return "claude-sonnet-5-5"
Rules like these are crude, but they are transparent and easy to evaluate. Before you route a task to a cheaper model, run your eval suite on both and compare; Run LLM evals in CI with promptfoo shows how. Also look at effort settings: on current Claude models, lowering output_config.effort cuts thinking and output tokens for simpler requests.
6. Set budgets
Budgets turn surprises into alerts:
- Per request: set
max_tokensdeliberately. It caps output, which is the expensive side. - Per task: for agents, cap turns and stop when a run’s summed tokens pass a threshold. An agent stuck in a loop is the classic runaway bill.
- Per day or month: set workspace or project spend limits in your provider’s console, and alert at 50% and 80%.
Pitfalls
Caching a prompt that changes every time. A timestamp, a request ID or a shuffled list near the top makes every request a write, which costs more than no caching at all.
Assuming a hit. Check the usage fields. Below the minimum length nothing is cached and nothing tells you.
Optimising the cheap side. Output tokens cost several times more than input. Shorter answers, structured output and lower effort can save more than caching on prompts that are mostly output.
Routing without evals. A cheaper model that is wrong 10% more often can cost more in support time than it saves.
Next steps
- See where spend goes across a whole product, and other ways to reduce LLM costs, in how to reduce LLM costs without hurting quality.
- Keep long agent sessions small with Agent memory and compaction.
- Review what goes into the prompt in the first place with Context engineering basics.
Covers
- Tools
Check your understanding
Prompt caching and token costs quiz
How prefix caching works, prompt layout, cache breakpoints, checking hits, batch processing, routing and budgets.
7 questions · pass mark 70%
Review
Related
- Controlling LLM costs without hurting quality
Where LLM spend actually goes (context, retries, agent loops, output) and the levers that cut it without hurting quality: caching, routing, batching, budgets.
- Context engineering techniques: what the model should see
What to put in a model's context at each step, what to leave out, and how instruction files, retrieval and tools fit.
- Agent memory and compaction in practice
Keep long Claude Code sessions accurate with compaction, CLAUDE.md, auto memory, subagents and a summarise-and-restart routine, and know what survives each.
- Prompt caching
Reusing the processed form of a repeated prompt prefix, such as a long system prompt, across requests to reduce latency and cost.
- Token
The unit of text a model reads and writes, often a word or part of a word; in English a token averages about four characters of text.