Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
On the refund app: usage shows input is 87 percent of the bill, three cache breakpoints cut the day by 68 percent, the nightly job moves to batch for 50 percent off, and the whole bill falls 62 percent.
What you will learn
- Find the dominant cost driver from the usage fields of every call
- Place three layered cache_control breakpoints: tools, system policy, newest turn
- Move work nobody waits for to the Message Batches API and match results by custom_id
- Quantify the saving with a before and after table
Before you start
- Ship a Claude app (part 3)
- Prompt caching: cost and latency
The refund assistant works and customers like it. Then finance asks: the bill keeps growing, where does the money go? They want a number they can trust, with the same answers as before. So we don't guess. We read the usage first, fix the biggest line, and measure the saving.
Picture a courier who packs the whole toolbox for every parcel. A smarter courier leaves the toolbox in the van and carries only the new parcel, and sends anything nobody needs today by freight. Our app resends the tools and the policy on every call: that's the toolbox. A cache read is leaving it in the van. The nightly job is the freight.
meter.py. Treat the percentages as the result of this setup, not a promise for your app.Step 1: read the usage
"""Usage to dollars. Rates are dollars per million tokens."""
# Source: Claude docs, Pricing (Claude Sonnet 5.5).
LIVE = {"in": 2.00, "write": 2.50, "read": 0.10, "out": 10.00}
BATCH = {"in": 1.00, "out": 5.00}
# Our own limit, in dollars per question.
BUDGET = 0.004
class Meter:
"""Wraps the client and adds up the usage of every call."""
def __init__(self, claude):
self.claude = claude
self.calls = self.fresh = self.written = 0
self.read = self.out = 0
self.messages = self
def create(self, **kwargs):
r = self.claude.messages.create(**kwargs)
self.take(r.usage)
return r
def take(self, u):
"""Add up every usage field of one call."""
self.calls += 1
self.fresh += u.input_tokens
self.written += u.cache_creation_input_tokens
self.read += u.cache_read_input_tokens
self.out += u.output_tokens
The meter from part 3 grows two fields: cache_creation_input_tokens (written to the cache) and cache_read_input_tokens (read back). Each kind of token has its own rate, so a parts() function prices them separately and shows the biggest line. Here is the day's three questions with no breakpoints:
R-1 calls 2 fresh 1993 write 0 read 0 out 60 $0.00459 over budget
R-2 calls 3 fresh 3077 write 0 read 0 out 90 $0.00705 over budget
R-3 calls 4 fresh 4228 write 0 read 0 out 120 $0.00966 over budget
day $0.02130
within budget: 0 of 3
input 87% of the bill, output 13%
dominant cost driver: input tokens
Nothing is cached, so every token is billed at the full input price. Fresh input is large on every call because each one resends the tools and the policy. Input is 87 percent of the bill. That tells us what to fix first, and what not to bother with: output is only 13 percent.
Step 2: three layered breakpoints
For how a breakpoint works on its own, and why cache reads can stay at zero, see Claude cache breakpoints. Here we apply it to our app.
POLICY = (pathlib.Path(__file__).with_name("policy.md")).read_text()
BREAKPOINT = {"type": "ephemeral"}
MAX_TOKENS = 300
def mark(block):
return {**block, "cache_control": BREAKPOINT}
def with_breakpoints(tools, messages):
"""Layers: 1 tools, 2 policy, 3 newest turn."""
tools = tools[:-1] + [mark(tools[-1])]
system = [mark({"type": "text", "text": POLICY})]
messages = copy.deepcopy(messages)
last = messages[-1]
if isinstance(last["content"], str):
text = last["content"]
last["content"] = [{"type": "text", "text": text}]
last["content"][-1] = mark(last["content"][-1])
return tools, system, messages
- Layer 1, the last tool. Tools come first in the prefix, so a breakpoint there covers every tool before it.
- Layer 2, the policy. The biggest block, and it never changes.
- Layer 3, the newest turn. Marked on a deep copy so the stored history stays clean, which lets the breakpoint move along each turn.
MAX_TOKENS = 300 is the token budget on the output side. The caching mechanics themselves are explained in prompt caching: cost and latency.
R-1 calls 2 fresh 0 write 1024 read 969 out 60 $0.00326 within budget
R-2 calls 3 fresh 0 write 126 read 2951 out 90 $0.00151 within budget
R-3 calls 4 fresh 0 write 191 read 4037 out 120 $0.00208 within budget
day $0.00685
within budget: 3 of 3
In R-1 the first call writes the prefix and the second reads it back. In R-2 almost everything is a read; only a small new part is written. Fresh input is now zero everywhere: every input token is either a write or a read. A read costs one twentieth of normal input at these rates, while a write costs a quarter more, so the reads have to repeat for caching to pay off. Here they do.
Step 3: the nightly job goes to batch
def request(oid):
"""One request per order. custom_id names the order."""
ask = f"Write a one-line status note for {oid}."
params = {"model": MODEL, "max_tokens": 100,
"system": POLICY,
"messages": [{"role": "user", "content": ask}]}
return {"custom_id": f"note-{oid}", "params": params}
def wait_for(claude, batch_id):
get = claude.messages.batches.retrieve
while get(batch_id).processing_status != "ended":
time.sleep(60)
def run_digest():
reset()
claude = make_client()
batch = claude.messages.batches.create(
requests=build(ORDERS))
wait_for(claude, batch.id)
meter = Meter(None)
ids = []
for item in claude.messages.batches.results(batch.id):
if item.result.type == "succeeded":
ids.append(item.custom_id)
meter.take(item.result.message.usage)
return batch.id, ids, meter
Nobody waits for the nightly status notes, so they don't need live prices. One batches.create call sends the night's work, one request per order, each with a custom_id. We poll until processing_status is "ended", then read the results and match each by custom_id, never by position, because results can arrive in any order.
msgbatch_001: 6 of 6 succeeded
first custom_id note-A-101, last note-A-106
tokens: in 4446 out 180
nightly job, one call at a time: $0.01069
nightly job, as a batch: $0.00535
saved 50%
The stand-in finishes at once. In real life a batch ends within 24 hours or expires, and most finish within an hour. The saving is exactly the batch discount: half the live price. The live chat stays live; a customer is waiting for that one. The same choice on a bigger pipeline is in the overnight document pipeline.
Step 4: before and after
before after saved
day, 3 questions $0.02130 $0.00685 68%
night, 6 notes $0.01069 $0.00535 50%
both together $0.03199 $0.01219 62%
questions within $0.004: 0 of 3 before, 3 of 3 after
That's the number finance asked for: 62 percent less, with no change to the answers, and every question now inside the per-question budget.
Fixes aimed at the wrong cost
| Fix | Why it misses |
|---|---|
Lower max_tokens on every call | Output is 13 percent of the bill, so it barely moves |
| Send the live chat through batch | A customer is waiting for that answer |
| Trim the customer's question | The question is a tiny share of the input |
The right move reads the usage first, caches the repeated text in layers, and batches only the work nobody waits for. The same read-the-bill habit applies to latency too, see cutting p95 and cost.
Recap
| Move | File | Result here |
|---|---|---|
| Read usage | usage.py | Input is 87 percent: the dominant driver |
| Layered breakpoints | app.py | Day falls 68 percent |
| Batch the night job | digest.py | Night falls 50 percent |
| Compare | compare.py | 62 percent overall, 3 of 3 within budget |
Previous: lab: golden set and judge. Next: lab: three planted bugs in the prompt, the schema and the stream handler.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.