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

In this topic

Claude
  • Claude.ai Interface Tour: Every Control You Need on One Screen
  • The AI Fluency Model: Delegation, Description, Discernment and Diligence
  • Working With Claude: Pick the Surface, Match the Model, Keep the Context Clear
  • Claude's Four Entry Points: Choose Chat, Projects, Artifacts or Research Before You Type
  • What Claude Can Do: Extended Thinking, Web Search, Artifacts and File Analysis
  • Getting More From a Claude Chat: Steer the Conversation Instead of Starting Over
  • Claude Research Mode End to End: From One Prompt to a Cited Briefing
  • Claude's Capability Layer: When to Use Skills, Code Execution or Memory
  • Code Execution and File Creation in Claude: Calculated Numbers and a Real Excel File
  • Adding and Using Skills in Claude: Let Claude Pick the Skill, Then Teach It Your Format
  • Claude Memory, Curation and Incognito: Keep What Helps, Remove What Has Gone Stale
  • Claude Styles, Preferences and Project Instructions: Three Dials, Three Scopes
  • Claude Projects: Knowledge, Instructions and a Real Workspace You Set Up Once
  • Keeping a Claude Project Current and Connected: Refresh, Prune and Grant the Least
  • Claude Scheduled Tasks: Let Claude Work on a Schedule and Email You the Result
  • Claude Code and Claude for Chrome: What They Are and Who They Are For
  • Anatomy of a Good Prompt: Role, Context, Task, Format and Examples
  • Shaping Claude's Output: Format, Tone and Length in a Few Words
  • Iterating and Refining a Prompt: Read, Diagnose, Adjust, Repeat
  • Five Prompting Patterns for Work: Summarise, Extract, Rewrite, Classify and Draft
  • Why Evaluating AI Output Matters Most: Trust, Then Verify
  • Spotting AI Hallucinations and Fabrications: Four Tells and Where Risk Spikes
  • Fact-Checking Claude's Answers: Four Techniques and a Line-by-Line Claim Log
  • Judging AI Output Quality: Four Questions That Score Any Answer
  • Adapting AI Output for Your Audience: One Answer, Three Readers
  • When a Human Must Review AI Output Before It Ships
  • A Personal Validation Checklist for AI Output: Six Lines, Any Draft
  • Fitting Claude Into Real Work: Where It Helps and Where It Never Should
  • Breaking Big Tasks Into Steps With Claude: Small Asks, Checked Hand-offs
  • Designing a Repeatable Claude Workflow: A Reusable Weekly Report Template
  • Measuring If Claude Is Actually Working: One Number, Before and After
  • Communicating AI Value and Limitations to Stakeholders: The Honest Pitch
  • Data Privacy With Claude: What Never Goes in a Prompt, and How to Redact a Document Before You Paste It
  • Responsible AI Use and Transparency: Helpful, Honest, Harmless, and One Honest Line
  • Troubleshooting a Weak Claude Answer: Name the Cause, Fix One Thing, Then Make It Cheaper
  • 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
  • Claude Code's Built-in Tools: Read, Write, Edit, Bash, Grep and Glob, and When Each One Is the Right Pick
  • The CLAUDE.md Hierarchy: User, Project and Directory Files, How They Stack, and the Team Rule Stuck on One Laptop
  • Split a 600-Line CLAUDE.md: @import Lines, .claude/rules Files and Which One to Pick
  • Path-Specific Rules in Claude Code: paths Globs, When a Rule Loads and the Glob That Matches Nothing
  • Claude Code Slash Commands and Skills: Project vs User Scope, $ARGUMENTS, context: fork and allowed-tools
  • Iterative Refinement with Claude Code: Input/Output Examples, Tests First and the Interview Pattern
  • Claude Code Sessions: Resume by Name, Fork From a Baseline, or Start Fresh With a Summary Card
  • CI Reviews That Don't Repeat Themselves: Prior Findings, Existing Tests and Test Standards in CLAUDE.md
  • Fleet Telemetry for Parallel Coding Agents: Find the Stampede, the Hotspot and the Runaway That Per-Agent Alerts Miss
  • AI Code Review That Earns the Right to Block: Shadow Mode, Calibration Against Human Review, Then a Gate
  • Org-Wide Claude Code: Managed Settings With the Locks On, an MCP Allowlist by Address, and One Pinned LLM Gateway
  • Sharing Skills, Prompts and MCP Servers Across Teams: One Quality Gate Before the Shared Catalog
  • Claude Code Plugins and Marketplaces for an Org: Package a Skill, a Hook and an MCP Server, Check Them, Then Lock the Sources
  • Where Claude Joins a Developer Workflow: Interactive, GitHub Action or claude -p, Then Measure the Outcome
  • An Ops Runbook for Claude Failures: Case Cards, Request IDs, Owners and a Read-Only Investigation
  • 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
  • Validation-Retry Loops for Claude Extraction: Send Back the Exact Errors, and Stop When a Retry Cannot Help
  • Multi-Pass and Multi-Instance Code Review with Claude: A Fresh Reviewer, Per-File Passes and an Integration Pass
  • When a Claude Support Agent Should Escalate: Three Clear Triggers, Not Mood or a Confidence Score
  • Error Propagation Across Subagents: Retry Locally, Then Report the Failure, the Attempts and What You Found
  • Human Review and Confidence Calibration: Check Accuracy by Type and Field Before You Stop Looking
  • Provenance in Multi-Source Research: Keep Every Claim With Its Source and Date, and Show Conflicts Instead of Settling Them
  • Lab: An Extraction Pipeline With a Nullable Schema, Validation-Retry, a 100-Request Batch and Human Review
  • Lab: A Research Pipeline With Parallel Subagents, a Timeout That Keeps Its Partial Results, and a Report With Its Trail
  • Coordinator and Subagents: Decompose, Delegate, Check Coverage, and Call Only the Spokes You Need
  • Passing Context to Subagents: Nothing Is Inherited, So Put Findings, Goal and Criteria in the Prompt
  • Parallel Subagents: Several Task Calls in One Response, Every Result Back in One User Turn
  • Task Decomposition: a Fixed Prompt Chain With an Integration Pass, or a Dynamic Plan That Adapts
  • Prompt Guidance vs Programmatic Gates: Block the Refund Until the Customer Is Verified, Then Hand Off a Card That Stands Alone
  • Scoped Tools per Agent and tool_choice: Three to Five Tools per Role, a Shared One, and auto, any or a Forced Tool
  • Durable Agent Runs: Save a Checkpoint After Every Tool Turn, Resume After a Kill, and Key the Email So It Goes Out Once
  • Resume on the Model the Run Started With: a Run Record That Pins the Model Id, the Prompt Version and the Notes
  • Durable Agent State by Name: an Agent SDK Session Id, a /memories Path or a Managed Agents Memory Store
  • Cache-Safe Instruction Changes and Large Tool Catalogs: Append the New Rule at the End, Defer 57 of 60 Tools With Tool Search
  • One Gateway, One Platform Table: Route a Model Alias to the Claude API, Bedrock or Google Cloud and Check Parity Before the Call
  • OpenTelemetry Tracing for a Claude Agent Loop: A Span for Every Request and Tool Call, and the Switch for Each Surface
  • Debugging Late, Far and Rare Failures in a Claude Agent: Replay the Turns, Follow the Fact, Split the Runs
  • Scheduled and Event-Driven Claude Agents: Managed Agents Deployments, Budgets, Outcomes and Webhooks
  • Latency Engineering for a Claude Agent Loop: Time to First Token vs Total, Streaming, Parallel Tools, the Cache and Effort
  • Claude Prompt Caching Strategy: Pick the TTL by the Quiet Gap, Read Cache Diagnostics, and Warm Before You Fan Out
  • Capstone: One Prompt Change Through the Whole Operating Loop, From CI Gate to Postmortem
  • Reading a Business Requirement Like an Architect: Function, Quality, Constraints and Assumptions
  • From One Claude Call to a System: Input, Processing, Output and the Feedback Loop
  • The Delegation Map: Decide What Claude Owns, What People Keep and What They Share
  • When a Packaged Skill Beats a New Agent (and a Prompt Library)
  • Five Reference Architectures for Claude Systems: Read the Cue, Name the Shape
  • Business Value Pillars for an LLM System: Turn "Cheaper and Faster" Into Targets, Then Pick the Lane
  • Which Requirement Binds? Picking the Claude Surface and Agent Runtime Under Constraints
  • The Claude Model Ladder: Pick the Cheapest Model That Passes, Then Price the Month
  • Zero-Shot, Few-Shot or Reasoning: Pick the Cheapest Prompting Technique the Failure Asks For
  • Choosing the Claude Build Stack: Client SDK, Agent SDK, Claude Code Headless or Managed Agents
  • Authentication and Authorization for Claude Agents: Find the Gaps Hop by Hop
  • Connecting Claude to a Legacy System You Can't Change: The Adapter Pattern
  • MCP, an API/CLI Call or Agent-to-Agent: Choosing How Claude Connects to a Capability
  • Progressive Discovery or Monolithic Context: Load It All, Fetch by Index, or Both
  • Speed Has a Price and the Rate Limit Is the Ceiling: Choosing Model, Effort and Fast Mode per Path
  • Reliability Controls for Claude Apps: Backoff, Idempotency Keys, Fallback Routing and Circuit Breakers
  • Six Metrics, Not One Score: Accuracy, Groundedness, Latency, Cost, Safety and Security for an LLM Agent
  • Diagnosing a Bad Answer: Prompt Failure, Hallucination or Model Mismatch?
  • Human-in-the-Loop Routing: Send Each Agent Action to Auto, Review or Block by Confidence, Reversibility and Cost
  • Working an Architecture Scenario End to End: Mark Hard and Soft Constraints, Cut, Rank, Decide
  • A Regulated Dispute Desk on Claude: Pin the Geography, Gate by Risk, Log Before Release, Fail Closed
  • Global Support Automation Scenario: Cut the Options, Route Each Ticket by Risk, Gate Every Change by Language
  • Architecture Artifact Review Drills: Find What a Diagram, Config, Trace, Eval Table, ADR or Settings File Leaves Out
  • The Architecture Decision Record for a Claude System: Context, Options, Decision, Consequences and the Evidence You Will Need
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Claude Prompt Caching Strategy: Pick the TTL by the Quiet Gap, Read Cache Diagnostics, and Warm Before You Fan Out

Some SupportDesk calls read zero from the cache, and there are three suspects. Ask the API: diagnostics names system_changed (567 tokens lost) for a timestamp, tools_changed for a reorder, and nothing at all for an expired entry. A 1h lifetime halves the cost of quiet bursts (2,040 vs 4,092 units), and warming first turns 3 cold fan-out calls into 1.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Pick the cache lifetime (5m, 1h or none) from the longest quiet gap in your traffic
  • Opt in to cache diagnostics and read cache_miss_reason next to the usage
  • Match each miss type to its fix: stable system text, fixed tool order, append-only history, one model
  • Warm the cache with one call before fanning out parallel requests

Before you start

  • Claude prompt cache breakpoints
  • Claude usage fields

Picture a support agent that answers thousands of tickets a day, all on the same long prompt. Caching should make that cheap, but only if you plan it, and only if you can see why it misses.

Some SupportDesk calls show a cache read of zero, and there are three suspects. Maybe a time line crept into the system text. Maybe a deploy changed the tool order. Or maybe traffic went quiet for eight minutes. Each one leaves the read at zero and writes the whole prefix again at full price. The bill climbs, and nobody knows which it was.

In this article we answer three questions: what to cache, how long to keep it, and what changed. The basics of where breakpoints go are in prompt cache breakpoints. Here we add the lifetime plan, the API's own diagnostics, and warming before a fan-out.

A kitchen that preps ahead

Some prep sits on the counter: it stays ready for five minutes, and every order keeps it fresh. Some goes in the fridge: it lasts an hour, but costs more to prepare. And if someone changes step one, every later step is redone. Prepare what never changes, and keep it as long as the quiet gaps need.

The plan: stable first, lifetime by the gap

The request goes tools, then system text, then the ticket. The first two are the same on every call, so the breakpoint goes right after the system text. Keep a time line, a request id and a reshuffled tool list out of that stable part. The lecture also notes a minimum prompt length (512 tokens in this example); under it, nothing is cached.

The project runs on a stand-in model (the Anthropic SDK on an httpx mock transport, with a simulated prompt cache), so no API key is needed and the replies are test replies. Its token counts are its own (four characters per token), not real ones.

MULT = {"read": 0.05, "write_5m": 1.25, "write_1h": 2.0}     # Sonnet 5.5, as multiples of the base input price


def pick_ttl(gap_seconds):
    """pick a lifetime from the longest quiet gap"""
    if gap_seconds <= 300:
        return "5m"
    if gap_seconds <= 3600:
        return "1h"
    return None


def mark(ttl):
    return {"type": "ephemeral", "ttl": "1h"} if ttl == "1h" else {"type": "ephemeral"}


def build_request(text, ttl="5m", history=(), stamp=None,
                  model=MODEL, tools=TOOLS, tool_choice=None):
    """tools, then system, then messages"""
    system = POLICY if stamp is None else f"Time now: {stamp}. " + POLICY
    head = {"type": "text", "text": system}
    head["cache_control"] = mark(ttl)
    block = {"type": "text", "text": text}
    if history:
        block["cache_control"] = mark(ttl)
    messages = list(history) + [{"role": "user", "content": [block]}]
    req = dict(model=model, max_tokens=256, tools=tools,
               system=[head], messages=messages)
    if tool_choice:
        req["tool_choice"] = tool_choice
    return req

(Excerpt from cache_plan.py.)

  • Gaps within five minutes: the default 5-minute lifetime is enough, because every use refreshes it.
  • Up to an hour: use the 1-hour lifetime, so the entry survives the gap.
  • Longer than that: return None and don't pay to write an entry that will expire before the next call.
  • The price ratios: a write costs 1.25x the base input price at 5 minutes and 2x at 1 hour; a read costs 0.05x on Sonnet 5.5.

5m or 1h for quiet bursts

First, pick_ttl on three example gaps. Then four bursts of three tickets, with several quiet minutes between bursts, run once with each lifetime:

B. how long should the cache live?
gap 120s -> 5m | gap 440s -> 1h | gap 5400s -> None
ttl 5m: 4 bursts of 3 tickets  cold 4  hits 8  cost 4092 units
ttl 1h: 4 bursts of 3 tickets  cold 1  hits 11  cost 2040 units
1h costs 50% less than 5m

With 5 minutes, every burst starts cold: four cold calls. With 1 hour, only the very first call is cold. The 1-hour write costs more, but it is paid once instead of four times, so the input cost halves.

The doctor: ask the API why it missed

Usage tells you that a call missed. Cache diagnostics tells you why. You opt in per request by passing the previous response's id:

"""The cache doctor: send diagnostics with every call, then read the answer next to the usage."""
FIXES = {
    "model_changed": "hold the model constant",
    "tools_changed": "same tools, same order",
    "system_changed": "keep the system text byte-stable",
    "messages_changed": "history is append-only",
    "previous_message_not_found": "send diagnostics every turn",
    "unavailable": "keep tool_choice constant",
}


def ask(client, request, previous_id=None):
    """opt in with the previous response id"""
    return client.beta.messages.create(
        **request, diagnostics={"previous_message_id": previous_id})


def diagnose(r):
    """read the answer next to the usage"""
    u = r.usage
    miss = r.diagnostics and r.diagnostics.cache_miss_reason
    if miss:
        lost = getattr(miss, "cache_missed_input_tokens", None)
        note = f" ({lost} tokens)" if lost else ""
        return f"{miss.type}{note}: {FIXES[miss.type]}"
    if u.cache_read_input_tokens:
        return "hit"
    if u.cache_creation_input_tokens:
        return "entry expired: use the 1h ttl"
    return "under the minimum length: not cached"

diagnostics is a request field on the Messages API. In the Python SDK it goes through client.beta.messages, and the answer comes back on the response as cache_miss_reason, which names the first change it found and how many tokens were lost.

Diagnostics for a changed prompt, the lifetime for a quiet gap cache_miss_reason? from diagnostics yes the prompt changed fix the first change it names cache read above 0? hit prefix written again? yes: entry expired, use the 1h ttl no: under the minimum, not cached
No reported change with a fresh write means time, not the prompt, was the problem.

Nine calls, read two ways

A. why did the cache miss?
steady           read   720  written     0  hit
timestamp        read     0  written   725  system_changed (567 tokens): keep the system text byte-stable
tools reordered  read     0  written   720  tools_changed (740 tokens): same tools, same order
history edited   read   720  written    53  messages_changed (53 tokens): history is append-only
fallback model   read     0  written   720  model_changed (740 tokens): hold the model constant
quiet for 8 min  read     0  written   720  entry expired: use the 1h ttl
tool_choice set  read   720  written     0  unavailable: keep tool_choice constant
too short        read     0  written     0  under the minimum length: not cached
lost the id      read     0  written   720  previous_message_not_found: send diagnostics every turn
  • Timestamp: a time line in the system text. Diagnostics says system_changed, 567 tokens lost. The fix is byte-stable system text.
  • Tools reordered: tools_changed. Same read of zero, same kind of fix: keep the order.
  • History edited: only the 53 tokens after the edit were lost; the rest was still read. History is append-only.
  • Fallback model: the model changed, so model_changed and the whole prefix is written again. Hold the model constant.
  • Quiet for 8 minutes: diagnostics reports nothing, and the read is zero. Nothing changed; the entry expired. That is the case for the 1-hour lifetime, and only that one.
  • Too short: nothing read, nothing written. Under the minimum, never cached.
  • Lost the id: the previous response wasn't sent with diagnostics, so there is nothing to compare. Send it every turn.

Look at the usage column alone: timestamp, tools reordered and quiet-for-8-minutes all read 0 and write about 720. Only diagnostics tells them apart, and they need different fixes.

Warm it first, then fan out

Three tickets arrive at the same moment. Sent together, each one finds nothing to read, and each writes the whole prefix. An entry can be read only after the first response that writes it has started. So send one call ahead, then fan out the rest:

C. fan out
cold fan-out  calls 3  cold 3  hits 0  cost 2751 units
warm first    calls 3  cold 1  hits 2  cost 1022 units
One call writes, then the others read cold fan-out: 2,751 units T-201 write T-202 write T-203 write warm first: 1,022 units T-200 warm: write T-201 read T-202 read first response started 3 cold, 0 hits 1 cold, 2 hits
Same three calls. Warming first leaves one cold call and two hits.

Common mistakes

  • Adding more breakpoints after a deploy breaks the cache. The count isn't the problem; something before the breakpoint changed.
  • Switching every call to the 1-hour lifetime and hoping. It fixes an expired entry, not a changed prompt, and every write costs 2x instead of 1.25x.
  • Turning caching off. Then you pay the full price every time.
  • Reading usage alone. Three different causes looked identical in the usage column. Read diagnostics next to it.
  • Fanning out cold. Parallel calls can't read an entry that doesn't exist yet. Warm first.

For edits that keep the cache intact mid-conversation, see cache-safe instruction changes.

Quick recap

QuestionAnswerIn this run
What to cache?Tools, then system text; breakpoint after the stable part720-token prefix read on a hit
How long?By the longest quiet gap: 5m, 1h or nonequiet bursts: 1h, 2,040 vs 4,092 units
Why did it miss?diagnostics, read with usagesystem_changed, tools_changed, ... or expired
Parallel calls?Warm first, then fan out1,022 vs 2,751 units

Try it yourself

Your traffic has bursts every 50 minutes overnight and every 2 minutes during the day. Use pick_ttl to decide the lifetime for each period, then work out whether one lifetime for the whole day would be cheaper than switching at the shift change.

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 · 140 of 165

Previous
Latency Engineering for a Claude Agent Loop: Time to First Token vs Total, Streaming, Parallel Tools, the Cache and Effort
Next post
Capstone: One Prompt Change Through the Whole Operating Loop, From CI Gate to Postmortem

Related course on Udemy

Claude Certified Developer - Professional (CCDV-P) Exam Prep

Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) 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 kitchen that preps ahead
  • The plan: stable first, lifetime by the gap
  • 5m or 1h for quiet bursts
  • The doctor: ask the API why it missed
  • Nine calls, read two ways
  • Warm it first, then fan out
  • 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 - Professional (CCDV-P) Exam Prep

Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.