Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin 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

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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.

Every token count below comes from the course's stand-in for Claude, not a real run. The rates come from the Claude docs Pricing page as written in the lab's 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
Three cache breakpoints in prefix order tools system: policy text messages ... newest turn BP 1BP 2BP 3 Each breakpoint caches everything before it. BP 3 moves along with the conversation. Three breakpoints used; a request allows at most four.
Tools come first in the prefix, so one breakpoint on the last tool covers all of them.
  • 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

FixWhy it misses
Lower max_tokens on every callOutput is 13 percent of the bill, so it barely moves
Send the live chat through batchA customer is waiting for that answer
Trim the customer's questionThe 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

MoveFileResult here
Read usageusage.pyInput is 87 percent: the dominant driver
Layered breakpointsapp.pyDay falls 68 percent
Batch the night jobdigest.pyNight falls 50 percent
Comparecompare.py62 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.

Keep going in Claude · 59 of 66

Previous
Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
Next post
Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
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)

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

  • Step 1: read the usage
  • Step 2: three layered breakpoints
  • Step 3: the nightly job goes to batch
  • Step 4: before and after
  • Fixes aimed at the wrong cost
  • Recap
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.