Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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

  1. Read the menu. The sizes are listed, so you know an order before you place it. That's counting tokens before the call.
  2. Set a limit. No dish above it. That's max_tokens on the call.
  3. Keep the receipt. It shows the real charge, line by line. That's usage after the call.

You wouldn't guess the bill. You'd keep the receipt.

Count, cap, read usage Before count_tokens input estimate During max_tokens hard output ceiling After response.usage exact tokens in and out Only usage is exact.
Count first, cap during, read after.

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 returns input_tokens. It's an estimate.
  • On the call: max_tokens, a hard ceiling on the output. When it's reached, stop_reason is max_tokens.
  • After the call: usage on the response, with input_tokens and output_tokens as 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, usage goes 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.

FieldCountsUSD per million
input_tokensNew, uncached input2.00
output_tokensWhat the reply wrote10.00
cache_creation_input_tokensInput written to the cache (5-minute write)2.50
cache_read_input_tokensInput read back from the cache0.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_tokens as the ceiling.
  • Nothing dominates and nobody waits: batch, which is half price on input and output.
Bill shape decides the lever policy_qa input 87% caching review_tagging input 49% output 51% batch draft_writer output 95% token budget
Blue is input, red is output. The shape of the bill picks the lever.

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_tokens by 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

StepTool
Count the input before the callmessages.count_tokens
Cap the outputmax_tokens
Read what was billedresponse.usage, all four token fields
Price it per featureA rate per field, summed per feature
Find the driver, fit the leverCaching, 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 20 of 66

Previous
Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
Next post
Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero

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.

On this page

  • A restaurant tab
  • Where each number comes from
  • naive_tracker.py: the guess we are replacing
  • ledger.py: count, cap, read, price
  • Guessed versus tracked
  • Reading the bill: four fields, four prices
  • bill.py: price each field, find the biggest line
  • levers.py: fit the lever to the line
  • Bill, driver, lever
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.