Claude API Cost Optimization: Usage Data, Batching and Budgets

๐Ÿ“š Exam guide v1.1 (exams from 7 Dec 2026)๐Ÿ”„ Checked against official sources: 24 Nov 2026โฑ๏ธ 8 min read๐ŸŽฏ D5 Cost Diagnosis and Optimization

๐Ÿ‘‹ 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.

Advertisement

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.

๐Ÿ“– What You’ll Learn: You will be able to log Claude usage, compute cost per route and per completed task, identify the dominant cost driver, choose caching, batching, effort, budgets or model changes accordingly, and quantify the impact.

๐Ÿ”‘ 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.

Advertisement

๐Ÿชœ 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
๐ŸŽฏ Exam focus: Match the lever to the driver: uncached repeated input โ†’ caching; latency-insensitive volume โ†’ batching (50% off); output and thinking โ†’ effort, output limits, task budgets; failed or repeated tasks โ†’ fix the cause before optimising. “Switch everything to the cheapest model” without measuring quality is a distractor.
Advertisement

๐Ÿชœ 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:

  1. max_tokens: a hard ceiling per response, which the model does not see.
  2. Task budgets (beta): output_config={"task_budget": {"type": "tokens", "total": N}} with the task-budgets-2026-03-13 beta 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).
  3. Harness limits: step limits and spend limits in your loop, or max_turns / max_budget_usd in 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()
Advertisement

๐Ÿชœ Step 6: Keep a cost checklist

  1. Log usage per route and per completed task; review weekly.
  2. Cache stable prefixes (Lesson 43); verify hit rates.
  3. Batch anything that can wait (Lesson 13).
  4. Tune effort per route; cap output; use task budgets for agents.
  5. Consider a cheaper model only with evaluation evidence (Lesson 8), comparing cost per completed task.
  6. 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

  1. Task 1: Add log_usage to one of your Claude routes and collect a day of data.
    โœ… Done when: the CSV has at least 50 rows.
  2. Task 2: Run cost_report.py on your data with your own prices.
    โœ… Done when: you can name each route’s dominant driver.
  3. 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.
Advertisement

โ“ 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.
๐Ÿ“ Test yourself: D5 Model Selection and Optimization practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Eval Design: Golden Sets, Metrics and Regression Suites.

๐ŸŽฌ Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

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.