Claude API Cost Optimization: Usage Data, Batching and Budgets
๐ In plain words: When the Claude bill grows, guessing at fixes wastes time. The usage numbers on every response tell you exactly where the money goes. This lesson turns those numbers into a cost report per feature, finds the biggest driver, and matches it to the right fix, one step at a time.
The CCDV-F skill “Cost Diagnosis and Optimization” asks you to analyse usage or cost data, identify the dominant cost driver, select the optimisation that addresses it (prompt caching, batch processing or token budgets) and quantify the expected impact. In this lesson you will log usage per request, build a cost report per route in Python, classify each route’s dominant driver, choose the matching lever, and estimate the saving before you change anything.
๐ Key terms
- Route: one feature or call site in your app, such as “triage” or “test generation”.
- Cost driver: the part of usage that dominates cost: uncached input, output (including thinking), or cache writes.
- Cost per completed task: total cost of all calls (including retries and extra turns) needed to finish one task.
- Task budget: a token budget an agentic loop is told about, so Claude can pace itself (beta).
๐ช Step 1: Log usage on every request
Record what you need for analysis with every call: route, model, the four usage fields, and whether the task finished:
๐ usage_logger.py
import csv
import os
FIELDS = ["route", "model", "input_tokens", "output_tokens", "cache_creation_input_tokens",
"cache_read_input_tokens", "batch", "task_done"]
def log_usage(path: str, route: str, response, batch: bool = False, task_done: bool = True) -> None:
new = not os.path.exists(path)
with open(path, "a", newline="") as f:
w = csv.DictWriter(f, fieldnames=FIELDS)
if new:
w.writeheader()
u = response.usage
w.writerow({"route": route, "model": response.model, "input_tokens": u.input_tokens,
"output_tokens": u.output_tokens,
"cache_creation_input_tokens": u.cache_creation_input_tokens or 0,
"cache_read_input_tokens": u.cache_read_input_tokens or 0,
"batch": batch, "task_done": task_done})
For organisation-wide numbers, Anthropic also offers usage and cost reporting in the Claude Console and an Admin API for usage and cost data.
๐ช Step 2: Build a cost report per route
A week of logs, summarised per route (numbers are a realistic example, in millions of tokens):
๐ usage_week.csv
route,model,requests,input_mtok,output_mtok,cache_write_mtok,cache_read_mtok,batch_share,tasks_done
pr_review,claude-opus-5-5,4200,210.0,6.3,0.0,0.0,0.0,4100
nightly_triage,claude-opus-5-5,1500,12.0,9.0,0.4,30.0,0.0,1480
ticket_labels,claude-haiku-5-5,90000,27.0,1.8,0.0,0.0,0.0,90000
testcase_gen,claude-opus-5-5,800,4.0,14.0,0.0,0.0,0.0,520
๐ cost_report.py
import csv
PRICES = { # $ per million tokens: input, output, cache write (5-min), cache read
"claude-opus-5-5": (4.00, 20.00, 5.00, 0.20),
"claude-haiku-5-5": (0.10, 0.50, 0.125, 0.01),
}
rows = list(csv.DictReader(open("usage_week.csv")))
print(f"{'route':<15}{'total $':>9}{'input':>8}{'output':>8}{'writes':>8}{'reads':>7} {'$/task':>7} driver")
for r in rows:
p_in, p_out, p_w, p_r = PRICES[r["model"]]
parts = {"input": float(r["input_mtok"]) * p_in, "output": float(r["output_mtok"]) * p_out,
"writes": float(r["cache_write_mtok"]) * p_w, "reads": float(r["cache_read_mtok"]) * p_r}
total = sum(parts.values())
driver = max(parts, key=parts.get)
per_task = total / int(r["tasks_done"])
s = {k: v / total for k, v in parts.items()} # share of the route's cost
print(f"{r['route']:<15}{total:>9,.0f}{s['input']:>8.0%}{s['output']:>8.0%}{s['writes']:>8.0%}{s['reads']:>7.0%}"
f" {per_task:>7.3f} {driver}")โจ๏ธ Terminal
python cost_report.py๐ฅ๏ธ Output
route total $ input output writes reads $/task driver
pr_review 966 87% 13% 0% 0% 0.236 input
nightly_triage 236 20% 76% 1% 3% 0.159 output
ticket_labels 4 75% 25% 0% 0% 0.000 input
testcase_gen 296 5% 95% 0% 0% 0.569 output
The cache-write and cache-read prices for Haiku in this table follow the usual 1.25ร and 0.1ร multipliers and are illustrative; check Anthropic’s pricing page for exact values.
๐ช Step 3: Read the diagnosis
| Route | Dominant driver | What the data says |
|---|---|---|
pr_review |
Input, with zero cache reads | The same long review guide is sent 4,200 times uncached โ prompt caching |
nightly_triage |
Output (and it already caches) | Thinking and long answers dominate โ effort per step, shorter output, batching (not urgent) |
ticket_labels |
Input, tiny per call, huge volume | Already on Haiku; check prompt size and caching of the instructions |
testcase_gen |
Output, and only 520 of 800 tasks finished | Cost per completed task is high: failures and retries โ fix quality first, then effort/budgets |
๐ช Step 4: Quantify the expected saving
Estimate before you change anything, so you can check the real result afterwards:
๐ estimate.py
# pr_review: 210 MTok input/week, almost all of it the same review guide
input_mtok, guide_share, price_in, price_read, price_write = 210.0, 0.90, 4.00, 0.20, 5.00
writes_mtok = 2.0 # rough: a few cache writes per 5-minute window during working hours
before = input_mtok * price_in
after = input_mtok * (1 - guide_share) * price_in + (input_mtok * guide_share - writes_mtok) * price_read \
+ writes_mtok * price_write
print(f"pr_review input: ${before:,.0f}/week -> ${after:,.0f}/week ({1 - after / before:.0%} saving)")
# nightly_triage: move to batch (50% off) and lower effort on the 'same as yesterday?' step
output_cost, input_cost = 9.0 * 20.00, 12.0 * 4.00
effort_cut = 0.40 # measured: 40% fewer output tokens at low effort on that step
batch_after = (input_cost + output_cost * (1 - effort_cut)) * 0.5
print(f"nightly_triage: ${input_cost + output_cost:,.0f}/week -> ${batch_after:,.0f}/week")โจ๏ธ Terminal
python estimate.py๐ฅ๏ธ Output
pr_review input: $840/week -> $131/week (84% saving)
nightly_triage: $228/week -> $78/week
These are estimates with stated assumptions (guide share, write volume, measured effort saving). After the change, compare them with the next week’s logs.
๐ช Step 5: Use budgets for agentic loops
For agents, the risk is runaway loops. Three controls exist at different levels:
max_tokens: a hard ceiling per response, which the model does not see.- Task budgets (beta):
output_config={"task_budget": {"type": "tokens", "total": N}}with thetask-budgets-2026-03-13beta tells Claude its budget for the loop so it can pace itself and finish gracefully. Supported on current models such as Opus 5.5 (check the docs for the list). - Harness limits: step limits and spend limits in your loop, or
max_turns/max_budget_usdin the Agent SDK.
๐ task_budget.py
import anthropic
client = anthropic.Anthropic()
with client.beta.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
betas=["task-budgets-2026-03-13"],
output_config={"effort": "high", "task_budget": {"type": "tokens", "total": 40000}},
messages=[{"role": "user", "content": "Investigate the failing checkout tests and propose a fix."}],
# tools=[...] for a real agent
) as stream:
final = stream.get_final_message()
๐ช Step 6: Keep a cost checklist
- Log usage per route and per completed task; review weekly.
- Cache stable prefixes (Lesson 43); verify hit rates.
- Batch anything that can wait (Lesson 13).
- Tune effort per route; cap output; use task budgets for agents.
- Consider a cheaper model only with evaluation evidence (Lesson 8), comparing cost per completed task.
- Remove waste: oversized tool results, unpruned history, duplicate retries (Lessons 11, 19, 24).
๐ Real-world example: Ravi’s cost review
Ravi’s monthly Claude bill doubled. The per-route report showed one cause: the PR-review bot, with zero cache reads. A misplaced breakpoint (Lesson 43) was fixed in one line, and the following week’s logs matched the estimate within a few percent. The nightly triage moved to batches the same week.
๐งช Practice Questions
Question 1. Usage data shows a route where 90% of cost is input tokens, the same 8K-token instructions are sent with every request, and cache_read_input_tokens is 0. Which optimisation addresses the dominant driver?
- A. Prompt caching with a breakpoint after the stable instructions
- B. Lowering effort
- C. Raising max_tokens
- D. Adding more examples
Show answer
Answer: A. The driver is repeated uncached input. Caching the stable prefix turns it into cheap cache reads.
Question 2. A nightly report job’s cost is dominated by output and thinking tokens, and results are only needed the next morning. Which two changes fit? (Choose 2.)
- A. Move the job to the Message Batches API
- B. Add a cache breakpoint after the question
- C. Lower effort on simple steps and cap output length
- D. Switch to streaming
Show answer
Answer: A and C. Batching halves the price of non-urgent work, and effort and output limits reduce the dominant output cost.
Question 3. Route A costs $0.02 per request and Route B $0.03, but A finishes only 60% of tasks and needs retries, while B finishes 99%. Which metric should drive the decision?
- A. Cost per request
- B. Cost per completed task
- C. Input tokens per request
- D. Number of requests
Show answer
Answer: B. Retries and failed tasks add cost. Compare the cost of actually finishing the work.
Question 4. An agent occasionally runs for hundreds of turns. Which control lets Claude pace itself within a token budget for the whole loop?
- A. max_tokens on each request
- B. A task budget (beta) in output_config
- C. stop_sequences
- D. temperature
Show answer
Answer: B. Task budgets inform the model of its overall budget. max_tokens is a per-response ceiling the model is not told about.
๐ Assignment
- Task 1: Add
log_usageto one of your Claude routes and collect a day of data.
โ Done when: the CSV has at least 50 rows. - Task 2: Run
cost_report.pyon your data with your own prices.
โ Done when: you can name each route’s dominant driver. - Stretch: Apply one optimisation, write your estimate down first, then compare it with the next day’s numbers.
โ Done when: you have estimate versus actual and an explanation of the gap.
โ Frequently Asked Questions
๐ค How do I reduce Claude API costs?
Measure usage per route, find the dominant driver, then apply the matching lever: caching for repeated input, batching for non-urgent volume, effort and output limits for output-heavy routes, and a cheaper model only with evaluation evidence.
๐ค Do thinking tokens cost money?
Yes. Thinking is billed as output tokens even when not displayed. Lower effort reduces it.
๐ค What is a task budget in the Claude API?
A beta feature that tells Claude a token budget for an agentic loop, so it can plan its work and finish before running out.
๐ค Where can I see my Claude usage and costs?
In the Claude Console usage and cost pages, through the Admin API’s usage and cost reporting, and in the usage field of every response.
๐ Summary
- Log usage per request with route, model, tokens and task outcome.
- Compute cost per route and per completed task; find the dominant driver.
- Uncached repeated input โ caching; non-urgent volume โ batching; output/thinking โ effort, limits, budgets.
- Estimate savings with stated assumptions, then verify with the next period’s data.
- Fix failure and retry causes before optimising price per request.
Next, continue with Claude Eval Design: Golden Sets, Metrics and Regression Suites.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.