Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
A naive tracker guesses 2,560 tokens where usage says 1,432. Build a ledger that counts before the call, caps the output and reads usage after it, then read a three-workload bill, find the dominant line and pick caching, batch or a token budget.
What you will learn
- Count input with count_tokens, cap output with max_tokens and read usage after every call
- Keep a per-feature ledger that prices each call from usage
- Price the four usage fields and name the dominant line of a bill
- Match the dominant line to caching, batch or a token budget, and state the saving with its assumption
Before you start
- The Claude Messages API: your first call
- LLM tokens, context windows and cost
A study-notes app has three features: summarize long notes, a quiz that keeps a chat going, and short tags. At the end of the month finance asks a fair question: why doesn't the bill match our estimate, and which feature spent it?
Nobody can answer, because the app guesses tokens from the text. In this article we stop guessing. First we build a ledger that counts before the call, caps the output and reads usage after it. Then we read a real-shaped bill, find the dominant line, and pick the one lever that fits it.
A restaurant tab
- Read the menu. The sizes are listed, so you know an order before you place it. That's counting tokens before the call.
- Set a limit. No dish above it. That's
max_tokenson the call. - Keep the receipt. It shows the real charge, line by line. That's
usageafter the call.
You wouldn't guess the bill. You'd keep the receipt.
Where each number comes from
- Before the call: the token counting endpoint,
client.messages.count_tokens. It takes the same input as a message and returnsinput_tokens. It's an estimate. - On the call:
max_tokens, a hard ceiling on the output. When it's reached,stop_reasonismax_tokens. - After the call:
usageon the response, withinput_tokensandoutput_tokensas billed.
naive_tracker.py: the guess we are replacing
"""The before version: guess the tokens from the text, and assume the cap was spent."""
from stand_in import MODEL
CAP = 300
def handle(req, client):
msgs = req["messages"]
r = client.messages.create(model=MODEL, max_tokens=CAP, messages=msgs)
guess_in = len(msgs[-1]["content"]) // 4
guess_out = CAP
return {"in": guess_in, "out": guess_out, "text": r.content[0].text}
The response carries usage, but the tracker throws it away. Input is the last message's length divided by four, so the chat history that travels with every quiz turn is missed. Output is assumed to be the full cap, every time.
ledger.py: count, cap, read, price
"""The tracked version: count before the call, read usage after it, price it."""
from collections import defaultdict
from stand_in import MODEL
INPUT_BUDGET = 400
OUTPUT_CAP = {"summarize": 300, "quiz": 120, "tags": 40}
RATE = {"in": 3, "out": 15} # demo units per 1,000 tokens, not real prices
TOTALS = defaultdict(lambda: {"in": 0, "out": 0})
def cost(tokens_in, tokens_out):
return (tokens_in * RATE["in"] + tokens_out * RATE["out"]) / 1000
def handle(req, client):
feat, msgs = req["feature"], req["messages"]
counted = client.messages.count_tokens(model=MODEL, messages=msgs).input_tokens
if counted > INPUT_BUDGET:
return {"counted": counted, "sent": False}
r = client.messages.create(model=MODEL, max_tokens=OUTPUT_CAP[feat],
messages=msgs)
u = r.usage
TOTALS[feat]["in"] += u.input_tokens
TOTALS[feat]["out"] += u.output_tokens
return {"counted": counted, "sent": True, "in": u.input_tokens,
"out": u.output_tokens, "stop": r.stop_reason,
"cost": cost(u.input_tokens, u.output_tokens)}
- Each feature has its own output cap.
- The input is counted first. Over our budget of 400, the request isn't sent.
- After the call,
usagegoes into that feature's running total, so every feature keeps its own count.
Guessed versus tracked
The project runs without an API key against a scripted stand-in model (the Anthropic SDK on an httpx mock transport), so these token counts come from the stand-in, not a live Claude run. RATE is a demo rate card, not Anthropic pricing.
naive tracker (guesses)
R-1 summarize guess in 261 out 300
R-2 quiz guess in 6 out 300
R-3 quiz guess in 10 out 300
R-4 summarize guess in 779 out 300
R-5 tags guess in 4 out 300
guessed 2560 tokens | usage says 1432
ledger (counts, then reads usage)
R-1 summarize counted 221 | in 221 out 180 | cost 3.36
R-2 quiz counted 11 | in 11 out 60 | cost 0.93
R-3 quiz counted 34 | in 34 out 60 | cost 1.00
R-4 summarize counted 652 > budget 400 | not sent | cost 0.00
R-5 tags counted 9 | in 9 out 25 | cost 0.40
per feature
summarize in 221 out 180 | cost 3.36
quiz in 45 out 120 | cost 1.94
tags in 9 out 25 | cost 0.40
total cost 5.70 demo units
Follow request three, the second quiz turn. The naive tracker guesses 10 input tokens; the count is 34, because the history came along. It guesses 300 output tokens; usage says 60. Request four is a huge paste, counted at 652 and never sent, so it costs nothing. Now every feature has a line on the bill.
A cap and a pace. max_tokens is a hard cap the API enforces, for one request and only its output. A task budget (beta, set in output_config, minimum total 20,000 tokens) is a soft hint that spans a whole agentic loop so Claude can pace itself. It doesn't stop a request, so sum usage yourself. Pair them: a pace for Claude, a ceiling for you.
Reading the bill: four fields, four prices
Once usage is logged, you can read a bill the way you read an itemised phone bill: every charge on its own line, then find the biggest one. Every response's usage block has four token fields, each with its own price. The rates below are the Claude Sonnet 5.5 row of the Claude docs Pricing page.
| Field | Counts | USD per million |
|---|---|---|
input_tokens | New, uncached input | 2.00 |
output_tokens | What the reply wrote | 10.00 |
cache_creation_input_tokens | Input written to the cache (5-minute write) | 2.50 |
cache_read_input_tokens | Input read back from the cache | 0.10 |
Total input is the sum of the three input fields.
bill.py: price each field, find the biggest line
"""Read usage rows, price each field, find the biggest line."""
import json, pathlib
# USD per million tokens, Claude Sonnet 5.5 row of Pricing
RATES = {"input_tokens": 2.00, "output_tokens": 10.00,
"cache_creation_input_tokens": 2.50,
"cache_read_input_tokens": 0.10}
FIELDS = tuple(RATES)
def load(path):
text = pathlib.Path(path).read_text(encoding="utf-8")
return [r["usage"] for r in json.loads(text)]
def lines(usages, scale=1.0):
"""dollars per usage field, summed over every row"""
return {f: sum(u[f] for u in usages) * RATES[f] / 1e6 * scale
for f in FIELDS}
def dominant(cost):
"""the biggest line and its share of the bill"""
field = max(cost, key=cost.get)
return field, cost[field] / sum(cost.values())
levers.py: fit the lever to the line
"""Pick the lever for the dominant line, then price it again."""
from bill import lines
def choose(cost, prefix_share, can_wait):
total = sum(cost.values())
inp = cost["input_tokens"] / total
out = cost["output_tokens"] / total
if inp >= 0.6 and prefix_share >= 0.5:
return "caching"
if out >= 0.7:
return "token budget"
if can_wait:
return "batch"
return "none"
def with_caching(usages, prefix):
rows = [dict(u, input_tokens=u["input_tokens"] - prefix)
for u in usages]
rows[0]["cache_creation_input_tokens"] = prefix
for v in rows[1:]:
v["cache_read_input_tokens"] = prefix
return lines(rows)
def with_batch(usages):
return lines(usages, scale=0.5)
def with_budget(usages, target):
capped = [min(u["output_tokens"], target) for u in usages]
return lines([dict(u, output_tokens=n)
for u, n in zip(usages, capped)])
- Input dominates and mostly repeats: caching. The first request writes the prefix, later ones read it.
- Output dominates: a token budget. The replies are too long; ask for shorter ones and keep
max_tokensas the ceiling. - Nothing dominates and nobody waits: batch, which is half price on input and output.
Bill, driver, lever
The three logs hold twelve responses each. Their token numbers are made up for the demo; the rates are the Sonnet 5.5 row. Here is what the reader printed, per 1,000 requests:
cost per 1,000 requests, USD (stand-in logs, Sonnet 5.5 rates)
policy_qa in 10.11 | out 1.54 | write 0.00 | read 0.00 | total 11.65
review_tagging in 2.91 | out 3.04 | write 0.00 | read 0.00 | total 5.95
draft_writer in 0.81 | out 14.04 | write 0.00 | read 0.00 | total 14.85
dominant line
policy_qa input_tokens 87% dominates
review_tagging output_tokens 51% no clear driver
draft_writer output_tokens 95% dominates
lever and saving
policy_qa caching 11.65 -> 3.15 (-73%)
review_tagging batch 5.95 -> 2.98 (-50%)
draft_writer token budget 14.85 -> 8.81 (-41%)
multi-agent job
brief_reader caching 13.90 -> 3.70
overnight_tagger batch 6.00 -> 3.00
long_drafter token budget 30.80 -> 15.80
status_reply none 1.40 -> 1.40
Every saving has an assumption, and it only counts when you state it:
- Caching saves 73% on the policy bot if requests land inside the five-minute cache lifetime.
- Batch halves the tagger because nobody waits for the answer.
- The token budget saves 41% on drafts if replies stay near the target length.
- In the multi-agent drill, the small status reply that a person waits for gets no lever: nothing repeats and nothing dominates.
For the cache mechanics behind the first lever, see prompt caching. For the same "read the bill, match the lever" habit applied to latency too, see cutting p95 and cost.
Common mistakes
- Estimating from the character count. It misses the history and the real output.
- Multiplying
max_tokensby the rate. That assumes every reply fills the cap. - Treating a task budget as a hard stop. It's advisory, and in beta.
- Fixing the loudest complaint, not the biggest line. Read the four fields first.
- Quoting a saving without its assumption. Cache lifetime, waiting time and reply length all decide whether it holds.
Quick recap
| Step | Tool |
|---|---|
| Count the input before the call | messages.count_tokens |
| Cap the output | max_tokens |
| Read what was billed | response.usage, all four token fields |
| Price it per feature | A rate per field, summed per feature |
| Find the driver, fit the lever | Caching, batch or a token budget |
Try it yourself
Log the usage of one day of your own app's calls, grouped by feature. Price the four fields, name each feature's dominant line, and write down one lever per feature together with the assumption that makes its saving real.
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.