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 Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero

A library chat resends 1,220 identical tokens every turn. Put cache_control breakpoints on the stable parts and one that moves with the chat, then diagnose four setups whose cache reads stay at zero and price each fix.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Place cache_control breakpoints on the tools, the system prompt and the newest message
  • Read cache_creation_input_tokens and cache_read_input_tokens to prove the cache works
  • Diagnose zero reads: volatile text, a moving tool list, the 20-block lookback and the wrong lifetime
  • Price a fix with the write and read ratios

Before you start

  • Prompt caching: keep the start of every request identical
  • The Claude Messages API: your first call

A library chat assistant sends the same long instructions on every turn: three tool definitions, the library rules, the branch list, and then the whole conversation so far. Most of each request is text the model saw one turn ago.

Prompt caching lets the API reuse that fixed part. In Claude you tell it where the fixed part ends with cache breakpoints, also called checkpoints: a cache_control marker on a block. This article has two halves. First we place the breakpoints and prove they work. Then we take a second app whose cache was "turned on" and still made the bill go up, and find out why the reads stay at zero.

Bookmarks in a long book

  • Start from page one every time and you read the whole book again. That's no breakpoints.
  • Put a bookmark after the fixed chapters and you only read the new pages. That's a breakpoint on the tools and the system prompt.
  • Use a bookmark that follows the last page you read. That's a moving breakpoint on the newest message.

How a breakpoint works

  • The API reads the prompt in a fixed order: tools, then system, then messages. So stable text goes first.
  • A breakpoint is "cache_control": {"type": "ephemeral"} on one block. Everything up to it can be reused.
  • You can use up to four breakpoints per request. The default lifetime is five minutes; "ttl": "1h" gives one hour. A prefix shorter than the model's minimum is silently not cached.
  • Three usage fields tell you what happened: cache_creation_input_tokens (written), cache_read_input_tokens (read), and input_tokens (the uncached rest).
Where the three breakpoints sit tools (3) system rules.md + branches.md messages history ... newest turn 1 last tool 2 last system block 3 newest message render order: tools, system, messages (moves each turn)
Everything up to a marker can be reused. Everything after it is paid for in full.

build_request.py: markers on the stable parts

"""Build one request, with checkpoints on the stable parts."""
import copy, pathlib
import tools

PROMPTS = pathlib.Path(__file__).with_name("prompts")
CHECKPOINT = {"type": "ephemeral"}


def module(name):
    return (PROMPTS / name).read_text(encoding="utf-8")


def build(history, checkpoints=("tools", "system", "last")):
    tool_list = copy.deepcopy(tools.TOOLS)
    system = [{"type": "text", "text": module("rules.md")},
              {"type": "text", "text": module("branches.md")}]
    messages = copy.deepcopy(history)
    if "tools" in checkpoints:
        tool_list[-1]["cache_control"] = CHECKPOINT
    if "system" in checkpoints:
        system[-1]["cache_control"] = CHECKPOINT
    if "last" in checkpoints:
        messages[-1]["content"][-1]["cache_control"] = CHECKPOINT
    return tool_list, system, messages

The third marker goes on the last block of the newest message, so it moves every turn. Notice copy.deepcopy(history): the marker is placed on a copy, so old markers never pile up in the stored history and push you past the limit of four.

The chat itself stays plain. chat.py calls client.messages.create(model=..., tools=..., system=..., messages=...) as usual and prints the three usage fields. There is no special caching call.

Breakpoints turn input into reads

The project runs against a stand-in: the Anthropic SDK on an httpx mock transport with a small simulated cache. Token counts are an estimate at four characters per token, so the numbers below come from the project's stand-in, not from a live Claude run. They show the shape.

no checkpoints
turn 1 | write 0 | read 0 | input 1258
turn 2 | write 0 | read 0 | input 1304
turn 3 | write 0 | read 0 | input 1351
tools and system checkpoints
turn 1 | write 1220 | read 0 | input 38
turn 2 | write 0 | read 1220 | input 84
turn 3 | write 0 | read 1220 | input 131
plus a moving checkpoint on the last message
turn 1 | write 1258 | read 0 | input 0
turn 2 | write 46 | read 1258 | input 0
turn 3 | write 47 | read 1304 | input 0
turn 4 | write 45 | read 1351 | input 0
  • With no markers, every turn is full price input.
  • With markers on tools and system, turn one writes the 1,220 fixed tokens once, and later turns read them. Only the conversation is uncached.
  • With the moving marker, each turn reads the whole chat so far and writes only the part it adds: 46, 47, 45 tokens. The API also has an automatic mode, a top-level cache_control, that moves this marker for you.

An edit breaks everything after it

branches.md edited
turn 5 | write 1026 | read 394 | input 0
tool description edited
turn 1 | write 1258 | read 0 | input 0
turn 2 | write 46 | read 1258 | input 0
turn 3 | write 47 | read 1304 | input 0
find_book description edited
turn 4 | write 1405 | read 0 | input 0

Add one line to branches.md and the tools breakpoint still hits (394 tokens read), but the system prompt and the chat are written again. Change one tool description and nothing can be read at all, because tools render first. A change anywhere in the prefix invalidates what follows it.

Why the reads stay at zero

Now a second app, a plant nursery assistant. Caching is on, breakpoints are on the system prompt and the newest message, and the bill went up. The usage rows show it: turn one writes 1,197 tokens, as expected, but turns two and three read zero and write again.

That costs more than no caching, because every write pays a premium. In units of one normal input token, the broken setup costs 4,580 against 3,664 with no caching at all.

Three checks

  1. The usage rows. A write on every turn with zero reads from turn two means a breakpoint missed.
  2. Compare two requests. Strip the markers and find the first position that changed. That's the cause.
  3. If nothing changed, count new positions. More than twenty in one turn means the lookback missed the old entry.

The API also offers cache diagnostics, in beta, which names the first divergence on the server side.

"""Read usage rows, then compare two request bodies to find the cause."""
import stand_in


def stripped(body):
    return [(p["label"], p["text"]) for p in stand_in.positions(body)]


def missed(rows):
    """Turns after the first that wrote again and read nothing."""
    return [i for i, r in enumerate(rows, 1)
            if i > 1 and r["read"] == 0 and r["write"] > 0]


def cause(prev, cur):
    """First position where the new request stops matching the old one."""
    a, b = stripped(prev), stripped(cur)
    for x, y in zip(a, b):
        if x != y:
            return "first change at " + y[0]
    added = len(b) - len(a)
    if added > stand_in.LOOKBACK:
        return f"no change, but {added} new positions past the lookback"
    return "no change found"

Four defects, four fixes

Four reasons the reads stay at zero A volatile text in the prefix request time in the system prompt fix: move it after the breakpoints B a moving tool list tool order rotates per request fix: one fixed tool list C past the lookback one turn adds 24 positions (limit 20) fix: a second breakpoint mid-turn D the wrong lifetime 12-minute gaps, 5-minute entry fix: ttl "1h"
Each defect, and the change that brings the reads back.

The request builder takes the defects as parameters, so each one can be switched on and off:

def build(history, stamp, stamp_in="turn", tool_names=tools.BASE,
          breakpoints=("system", "last"), ttl="5m"):
    mark = {"type": "ephemeral", "ttl": ttl}
    tool_list = [copy.deepcopy(tools.ALL[n]) for n in tool_names]
    system = [{"type": "text", "text": module("rules.md")},
              {"type": "text", "text": module("stock.md")}]
    if stamp_in == "system":
        system.insert(0, {"type": "text", "text": f"Request time: {stamp}"})
    messages = copy.deepcopy(history)
    if "tools" in breakpoints:
        tool_list[-1]["cache_control"] = mark
    if "system" in breakpoints:
        system[-1]["cache_control"] = mark
    if "mid" in breakpoints:
        blocks = messages[-1]["content"]
        blocks[len(blocks) // 2]["cache_control"] = mark
    if "last" in breakpoints:
        messages[-1]["content"][-1]["cache_control"] = mark
    return tool_list, system, messages

Here is the run, broken then fixed (stand-in numbers again; cost is in units of one base input token):

A  request time inside the system prompt
turn 1 | write 1197 | read 0 | input 0
turn 2 | write 1223 | read 0 | input 0
turn 3 | write 1244 | read 0 | input 0
reads stay at zero from turn 2 | first change at system block 0
cost 4580 against 3664 with no caching
A  request time after the breakpoints
turn 1 | write 1195 | read 0 | input 0
turn 2 | write 28 | read 1195 | input 0
turn 3 | write 23 | read 1223 | input 0
cost 1799 against 3664 with no caching
B  tool order changes on every request
turn 1 | write 1195 | read 0 | input 0
turn 2 | write 1223 | read 0 | input 0
turn 3 | write 1246 | read 0 | input 0
reads stay at zero from turn 2 | first change at tools
cost 4580 against 3664 with no caching
B  one fixed tool list
turn 1 | write 1195 | read 0 | input 0
turn 2 | write 28 | read 1195 | input 0
turn 3 | write 23 | read 1223 | input 0
cost 1799 against 3664 with no caching
C  22 blocks in one turn, one breakpoint
turn 1 | write 1195 | read 0 | input 0
turn 2 | write 1388 | read 0 | input 0
turn 3 | write 28 | read 1388 | input 0
reads stay at zero from turn 2 | no change, but 24 new positions past the lookback
cost 3403 against 3999 with no caching
C  a second breakpoint in the middle
turn 1 | write 1195 | read 0 | input 0
turn 2 | write 193 | read 1195 | input 0
turn 3 | write 28 | read 1388 | input 0
cost 2028 against 3999 with no caching
D  a request every minute, 5-minute breakpoint
minute 0 | write 1173 | read 0 | input 22
minute 1 | write 0 | read 1173 | input 22
minute 2 | write 0 | read 1173 | input 22
minute 3 | write 0 | read 1173 | input 22
cost 1906 against 4780 with no caching
D  a request every 12 minutes, 5-minute breakpoint
minute 0 | write 1173 | read 0 | input 22
minute 12 | write 1173 | read 0 | input 22
minute 24 | write 1173 | read 0 | input 22
minute 36 | write 1173 | read 0 | input 22
cost 5953 against 4780 with no caching
D  a request every 12 minutes, 1-hour breakpoint
minute 0 | write 1173 | read 0 | input 22
minute 12 | write 0 | read 1173 | input 22
minute 24 | write 0 | read 1173 | input 22
minute 36 | write 0 | read 1173 | input 22
cost 2786 against 4780 with no caching
  • A. The comparison says the first change is at system block 0: the timestamp changes every request, so the prefix never matches. Moving the time into the question fixes it.
  • B. The first change is at tools. Tools render first, so everything after them is written again. One fixed order brings the reads back.
  • C. Nothing changed. A scanner sent 22 stock counts as separate blocks, which added 24 positions in one turn, and a breakpoint looks back at most 20 positions for an earlier entry. A second breakpoint in the middle of the long turn puts the old entry back in reach.
  • D. Same prefix, but how far apart? At one request a minute, each read refreshes the five-minute timer. At twelve-minute gaps the entry has expired every time, which is worse than no caching. The one-hour lifetime fixes it.

Choose the lifetime by the gap

Count the gap from the start of one request to the start of the next. Under five minutes, take the default five-minute lifetime. From five to sixty minutes, take "ttl": "1h".

Price the fix with the ratios

Relative to the base input price, a five-minute write costs 1.25, a one-hour write costs 2, and a read costs 0.1 on most models (lower on some newer ones). cost.py applies those ratios to the usage rows:

WRITE_5M, WRITE_1H, READ = 1.25, 2.0, 0.1


def units(row):
    return (row["input"] + WRITE_5M * row["w5"] + WRITE_1H * row["w1"]
            + READ * row["read"])

Writes are split by lifetime in usage.cache_creation (ephemeral_5m_input_tokens and ephemeral_1h_input_tokens), which is where w5 and w1 come from.

DefectBrokenFixedNo cachingFix saves
A and B4,5801,7993,66461% against broken
C3,4032,0283,99940%
D (12-min gaps)5,9532,7864,78053%

These are ratios, not prices. Multiply by the model's input price to get money, as in Claude cost tracking from usage.

Common mistakes

  • Today's date at the top of the system prompt. The prefix changes every request, so nothing is read.
  • Leaving every old marker in the history. Markers pile up past the limit of four. Place them on a copy.
  • A breakpoint on a very short prompt. Below the model's minimum, nothing is cached and no error says so.
  • Building the tool list from an unordered set. A different order is a different prefix.
  • Trusting "caching is on". Check cache_read_input_tokens on the second request. If it's zero, read the log.

Quick recap

RuleWhat to do
OrderStable text first: tools, system, then messages
BreakpointsAfter each stable part, plus one on the newest message (max 4)
ProofWrites then reads in the usage fields
Zero readsCompare requests for the first change; count positions against the 20-block lookback
LifetimeMatch it to the start-to-start gap: 5 minutes or 1 hour

Try it yourself

Take a chat you already run and log the three usage fields for five turns. If the reads are zero from turn two, dump two consecutive request bodies with the cache_control keys removed and diff them. The first line that differs is your defect.

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 · 21 of 66

Previous
Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
Next post
Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures

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

  • Bookmarks in a long book
  • How a breakpoint works
  • build_request.py: markers on the stable parts
  • Breakpoints turn input into reads
  • An edit breaks everything after it
  • Why the reads stay at zero
  • Three checks
  • Four defects, four fixes
  • Choose the lifetime by the gap
  • Price the fix with the ratios
  • 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.