Zero Labs
Industry News / AI

Prompt Caching on Claude: Cut Input Costs 78% (The Math Nobody Writes Down)

Source · Towards AI By Vishnu Kannaujia

From the publisher’s feed, collected in the ZeroLabs newsroom.

Prompt Caching Is a Cost-Architecture Decision, Not a FlagIf you use Claude Code, you’ve already been running one of the most aggressive prompt-caching setups in production — you just never had to lift a finger for it. Open a session in a big repo, let Claude read a dozen files, ask a follow-up, and notice the second turn comes back faster and cheaper than the first. That’s not the model stretching before a workout. That’s the cache quietly doing its job while you take the credit.Here’s the thing nobody tells you until the invoice does: the moment you stop using Claude Code and start building your own thing on the API — an agent, a RAG service, a batch job — that free lunch ends. Caching stops being automatic. Now you decide where the cache boundaries go, and that one decision is worth 70–90% of your input bill on the workloads where it counts. Most blog posts treat caching like a light switch. It’s more like laying out a struct so it fits in a cache line — the layout is the optimization. Flip it on without thinking and you’ll get cache money; place it wrong and you’ll get a cache miss and a heart-rate spike when finance forwards you the bill.So let’s start from what you already know, take a quick tour of how caching actually works on Claude, and then build up to the part nobody writes down: where to put the breakpoints, which TTL to pick, and how to prove your hit rate from the terminal instead of praying to the billing dashboard.You’ve already been using prompt cachingPicture what Claude Code does on every turn. Its system prompt and tool definitions are big and basically frozen, so they get cached once and replayed at a tenth of the price. The files it read and the conversation so far ride along as a stable prefix, so each new question reuses everything that came before it. That’s the whole reason a marathon agent session — fifty turns deep into the same codebase — doesn’t bankrupt you. Without caching you’d re-pay for the entire context window on every single message, which is the LLM equivalent of buying a new car every time you want to drive to work.Carry one lesson into your own builds: caching pays off most exactly when you’ve got a big, stable chunk of context you hit over and over. System prompts. Tool schemas. A retrieved document set. A long chat. If that’s your workload — and for agents and RAG it almost always is — caching isn’t a nice-to-have. It’s the line between a unit cost your CFO smiles at and one that gets your project quietly “deprioritized.”What “caching” means on Claude — the quick tourClaude’s prompt cache is an ephemeral prefix cache. Three facts define it, and honestly that’s the whole syllabus:It’s prefix-based. You drop a cache breakpoint at a point in your prompt. Everything up to and including that point gets stored as a reusable prefix. Next request, Claude replays that prefix as long as the tokens match exactly — and bails the instant one doesn’t.It’s ephemeral, with two TTLs. A cached prefix lives 5 minutes (default) or 1 hour (opt-in). Every read resets the timer, so an active session keeps its own cache warm and cozy.It covers the whole prompt. Tools, system prompt, message content — anywhere you place a breakpoint, as long as the prefix clears a minimum of ~1,024 tokens for Sonnet/Opus-class models.Everything else flows from that first bullet, so tattoo this on your brain: you’re not caching a prompt, you’re caching a prefix.The one mechanic everything follows fromBecause the cache matches a prefix top-down, two consequences fall right out:Order matters. Your cache is only as long as its unchanging prefix, so stable stuff goes first, volatile stuff goes last.Invalidation cascades forward. Change one token near the top and everything below it gets reprocessed. Change something near the bottom and you barely feel it.Sort by volatility, put the breakpoint above the churn, keep the moving parts at the bottom.That picture is the entire discipline. A breakpoint is exactly that — a break point, not a breaking point, as long as you respect the gradient.The pricing, as ratiosAbsolute per-token prices shuffle around with every model release, so don’t memorize dollars — memorize ratios relative to the base input price. There are three, and they don’t move:Read 0.1× · uncached 1.0× · 5-min write 1.25× · 1-hour write 2.0×A cache hit costs one-tenth of sending the tokens fresh. A write carries a one-time premium — 25% extra for the 5-minute window, 100% extra for the 1-hour window — paid only on the request that fills the cache. Reads cost the same 0.1× no matter which TTL you wrote with. You pay the TTL surcharge once, at write time, and then you read at a discount until the clock runs out. There’s no such thing as a free launch — but a cache hit at 0.1× is the closest the API gets.The break-even formula worth memorizingThe real question for any block is brutally simple: how many reads until the write premium pays itself off? Versus not caching, a write costs an extra (W − 1) per token (W = write multiplier); each later read saves (1 − R) per token (R = 0.1). Set savings ≥ premium and you get the only formula you need:breakeven_reads = (W − 1) / (1 − R)5-minute TTL: (1.25 − 1) / 0.9 ≈ 0.28 → you’re in the black after the first read.1-hour TTL: (2 − 1) / 0.9 ≈ 1.11 → break even on the second read.That makes the TTL call mechanical instead of vibes-based. Will the prefix get read again within five minutes? 5-minute TTL — it’s basically free after one hit. Will the gap blow past five minutes but you’ll still land two-plus reads inside an hour? 1-hour TTL. Neither? Then don’t cache that block — you’d be paying a write premium for a cache that goes cold before it earns its keep.Choosing the TTL from your traffic shapeTTL is a function of your inter-request gap, not your mood, because every read slides the expiry forward:Requests (interactive chat, a tight agent loop): 5-minute TTL. The window self-refreshes; pay 1.25× once, read at 0.1× ever after. Keep it warm and it never has to come back from the cold.Requests 5–60 min apart (a sporadic support queue sharing one fat system prompt): 1-hour TTL, if you’ll get two-plus reads before it lapses.Requests > 1 hour apart: the prefix is stone cold every time. Caching can’t save you here — go optimize something else.A worked exampleTake a RAG assistant with a stable 20,000-token prefix (system prompt + tool defs + retrieved docs) and a short user message each turn, over a 10-turn session where turns land seconds apart. We’ll count only the prefix cost — the dynamic tail is the same either way.No caching: every turn re-sends the prefix at full freight — 10 × 20,000 × 1.0 = 200,000 units.5-minute cache, one breakpoint at the end of the prefix: 20,000 × 1.25 to write on turn 1, then 9 × 20,000 × 0.1 to read on turns 2–10 — 25,000 + 18,000 = 43,000 units.A 78.5% haircut on the cost that dominates this workload.The same session on a 1-hour TTL runs 58,000 units (−71%) — worse here, because you’d pay the 2× write premium for a window the session never needed. For anything that fits inside five minutes, the cheaper TTL wins. Penny-wise, prefix-wise.Placing breakpoints in a real requestHere’s the layout as a curl against the Messages endpoint. The system field is an array of blocks so you can drop a breakpoint exactly where you want it; the same cache_control marker works on the last tool and on message content.curl https://api.anthropic.com/v1/messages \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d '{ "model": "claude-sonnet-4-5", "max_tokens": 1024, "tools": [ { "name": "search_docs", "description": "...", "input_schema": {} }, { "name": "run_query", "description": "...", "input_schema": {}, "cache_control": { "type": "ephemeral" } } ], "system": [ { "type": "text", "text": "You are a support assistant for ..." }, { "type": "text", "text": " ...20K tokens of stable context... ", "cache_control": { "type": "ephemeral" } } ], "messages": [ { "role": "user", "content": "What changed in the v3 billing API?" } ] }'A breakpoint on the last tool caches the whole tool block; one on the final system block caches the system prompt and everything above it. The volatile user message sits after the last breakpoint and gets reprocessed cheaply every call — right where volatility belongs.For the 1-hour window you opt in per breakpoint (behind the extended-TTL beta header — double-check the current header string in the docs before you ship):{ "type": "ephemeral", "ttl": "1h" }You get four breakpoints per request, and stacking them costs nothing extra — they’re a budget to spend, not hoard. Drop one at each boundary between volatility tiers (end of tools, end of system prompt, end of retrieved context, end of conversation history) so a change in a lower tier doesn’t nuke the cheaper-to-cache tiers above it. Four breakpoints, no breakdowns.Measuring it in the terminalNone of this is real until you can see the hit rate — and every response hands it to you in usage. Pipe the call through jq:curl -s https://api.anthropic.com/v1/messages ... | jq '.usage'First call — the cache gets written:{ "input_tokens": 32, "cache_creation_input_tokens": 20000, "cache_read_input_tokens": 0, "output_tokens": 415}Second call inside the window — the cache gets read:{ "input_tokens": 40, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 20000, "output_tokens": 388}cache_creation_input_tokens bill at the write premium, cache_read_input_tokens at 0.1×, plain input_tokens at the base rate. Log all three and compute a hit ratio over a window — straight from a JSONL log of usage objects:jq -s ' (map(.cache_read_input_tokens) | add) as $hit | (map(.cache_read_input_tokens + .cache_creation_input_tokens + .input_tokens) | add) as $tot | { hit_rate: ($hit / $tot) }' usage_log.jsonlPut that number on a dashboard per route and watch it after every prompt change. The bill is a lagging indicator; the hit rate is the leading one. A sudden dip means somebody slipped volatility near the top of the prompt — and that’s your cue to go hunting through the anti-patterns below before the next billing cycle hunts you.Anti-patterns that quietly tank your hit rateThese fail silently. Nothing throws, nothing pages you — caching just ghosts you.Volatile content above a breakpoint. A "Current time: ..." line at the top changes every request, so the prefix match dies at token one and nothing caches. About time you moved it below the last breakpoint — or deleted it.Non-deterministic ordering. Tool defs or retrieved chunks emitted in a different order each time (hello, iterating an unsorted dict or set) make a different token sequence and a different cache key. Sort it and forget it.Reformatting every request. Re-serializing the same JSON with different whitespace or key order changes the bytes even when the content is byte-for-byte “the same.” The cache disagrees.Caching below the minimum. A prefix under ~1,024 tokens never engages. Small print, small prefix, no cache. Check the usage fields.The multi-tenant trap. Personalizing the top of the prompt per user ("You are assisting Vishnu (Acme, enterprise)...") gives every user a unique prefix and kills cross-user sharing. Put shared content (tools, base system prompt) first under its own breakpoint, and shove per-user content below it. Now thousands of users share one warm prefix for the expensive common part — that’s the kind of sharing that scales.The takeawayPrompt caching rewards engineers who treat the prompt as a data structure with a volatility gradient: stable bytes up top, volatile bytes at the bottom, breakpoints on the boundaries. Hold the pricing in your head as three ratios and one formula — breakeven_reads = (W − 1) / (1 − R) — and the payoff on prefix-heavy workloads is a 70–90% cut in input cost. But the cache is exact and unforgiving: it matches tokens, not intentions. The discipline isn’t flipping a flag. It’s keeping your prefix byte-stable and proving it with the hit-rate metric every time you ship — the same thing Claude Code has been quietly doing for you this whole time, while you got the applause.Prompt Caching on Claude: Cut Input Costs 78% (The Math Nobody Writes Down) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.