← Inference From First Principles

Claude, Caching and API-Level Optimization

What a provider's prompt-caching contract lets an application see, and what it does not: a mock that implements only the documented rules, two different internals that the contract cannot tell apart, break-even request rates for the two lifetimes, workloads priced at dated published prices, and an opt-in harness that refuses to spend money unless it is told to.

A twelve-turn chat has a 3,000-token system prompt, and the user takes about ten seconds between replies. Under the synthetic workload and the Claude Sonnet 5.5 prices recorded on 22 October 2026, caching the system prompt alone costs 72% of an uncached conversation; automatic caching of the growing conversation costs 38%. Extend the user’s median pause to ten minutes and those ratios become 101% and 103%: the five-minute entries commonly expire before reuse, and a fresh write costs more than ordinary input. With a one-hour automatic cache the ten-minute-pause scenario costs 47% instead. These are whole-conversation cost ratios, including the unchanged output charge; they are not provider measurements.

The useful question is therefore not simply whether a prompt can be cached. It is whether the particular prefix will be reused, under which lifetime, before its write premium is wasted.

Every number in that comparison is modelled. The program in this chapter represents selected rules in Anthropic’s published prompt-caching documentation, applies them to synthetic request sequences, and bills the resulting synthetic usage at a price snapshot dated 22 October 2026. It sends no requests to Anthropic. The book forbids paid API experiments without explicit authorisation, and none was given. Accordingly, the experiments can check the code’s consistency with the documented rules, derive economic thresholds and prepare tests for future verification; they cannot establish actual cache-hit rates, provider latency, eviction behaviour or the correctness of every rule as implemented by the live API.

The API exposes usage accounting, not a physical cache diagram. input_tokens, cache_creation_input_tokens and cache_read_input_tokens reveal how a request was billed; they do not reveal tensor layout, device placement, physical memory consumption or the provider’s eviction implementation. This chapter constructs two different stores that produce identical usage for a 4,000-request trace. That establishes non-identifiability from those observations, not an inability to test any provider behaviour or a proof that all possible implementations are indistinguishable.

The question

Chapter 16 built and measured a prefix cache using Chapter 14’s paged KV blocks. There we controlled cache identity, capacity, sharing and eviction, and could inspect timing and memory. A hosted-model application controls none of those internals. It supplies cache_control on a request and receives usage fields on the response. Here we distinguish three layers: documented API behaviour, the mock’s interpretation of that behaviour, and observations a real provider experiment would have to supply. Only the middle layer is executed in this chapter.

What does the caching documentation actually specify, including prefix identity, per-model minima, time-to-live, lookback and concurrent first writes? When does a 1.25× five-minute write or 2× one-hour write repay its premium, at the published model-specific read price? How does that decision change for conversations, agent loops, documents and bursts? How should an application diagnose a zero-read result, and what can its usage records legitimately reveal about storage? The final question is deliberately narrow: usage accounting alone does not identify the implementation, even though sufficiently controlled live observations can test whether the API behaves as documented.

Where this sits

Chapter 16 is the self-hosted comparison: it measures cache allocation, eviction, tenancy and timing where we own the runtime. This chapter uses Anthropic’s documented contract instead. The documentation states that caches are isolated across organisations and, on the Claude API, across workspaces; that is a provider statement, not an independently verified absence of side channels. Chapter 31 showed that deterministic rendering governs token-prefix identity; the hosted API requires an exact matching prefix, although its tokenizer and internal representation are not visible here. Chapter 2’s artefact manifest is the right place to record the model identifier, prompt and tool versions, breakpoint placement, cache TTL, pricing snapshot and whether usage was simulated or observed. Chapters 25 and 30 also matter: the live harness must not turn an estimate into an unapproved bill.

Where the starter was wrong

The starter’s mock called a request eligible if its tokens summed to at least 1,024, and credited every eligible request with a saving of 0.9, which its own comment called “a documented discount placeholder”. Its output cannot describe real cache economics because it omits model-specific eligibility, the price of writes versus reads, prefix identity and elapsed time. Each has a corresponding documented rule.

The minimum cacheable prefix depends on the model. The 22 October 2026 source snapshot lists 512 tokens for Fable 5.1, Opus 5.5, Sonnet 5.5 and Haiku 5.5, but 4,096 for Opus 4.6, Opus 4.5 and Haiku 4.5. A 1,500-token prefix can therefore qualify on one model and fall below the threshold on another. The relevant quantity is the token count up to the breakpoint, not an arbitrary total of all request text. The result of a below-minimum breakpoint is ordinary processing without an error, not a reduced read price.

A first cache write is a premium, not a 90% discount: the documented prices are 1.25× the ordinary input rate for five minutes and 2× for one hour. Reusing an eligible prefix costs 0.1× on most supported models, 0.05× on the recorded Opus 5.5 and Sonnet 5.5 prices, and 0.025× on Fable 5.1. The model, its exact prefix, and the time between requests jointly determine whether paying the premium makes sense. These are billed input-token multipliers; output charges remain in the total bill.

The starter had no cumulative prefix identity, breakpoint, TTL, tools/system/messages hierarchy, 20-position lookback or charged read: cache_read_tokens was always zero. The starter’s script and its tests are left as they were, and nothing in this chapter comes from them.

What the API shows, and what it does not

One contract, two internals

Anthropic documents the Messages API as stateless: the caller resends the relevant conversation with each request. Prompt caching changes the processing and billing of a reusable prefix, not the requirement to provide the conversation again. The provider states that caching does not change output generation. This chapter did not run the same prompt with and without caching against Claude, so output equivalence is reported by the documentation, not demonstrated by the mock.

The request can put cache_control: {"type": "ephemeral"} on selected content blocks, with "ttl": "1h" for the longer duration, or place one cache_controlat the top level so the provider selects the last eligible block automatically. The response'susageincludesinput_tokens(ordinary input not billed as a cache write or read),cache_creation_input_tokens(newly written), andcache_read_input_tokens(reused). Acache_creationobject further separates the five-minute and one-hour writes;output_tokensis billed separately. The documented identity istotal_input_tokens = input_tokens + cache_creation_input_tokens + cache_read_input_tokens. Merely reading input_tokens` as all submitted input would badly undercount a cached request.

The documented behavioural rules used here are: cumulative prefix identity in the order tools → system → messages; exact matching of content through the candidate breakpoint; a model-specific minimum cacheable prefix; a maximum of four breakpoints, including automatic placement; five-minute and one-hour lifetimes refreshed by reuse and measured from the start of the request; at most 20 backward positions searched per breakpoint, including the breakpoint itself; and visibility of a newly written entry only after the writing request has begun its response. When both durations occur in a prompt, one-hour breakpoints precede five-minute breakpoints. The documentation also specifies special handling of consecutive tool-use and tool-result blocks in the lookback count. These are public API statements, not claims that the lab has inspected the provider’s code.

The public contract is much less specific about physical implementation. It does not expose the memory allocator, location of cache state, representation of attention data, admission under pressure or eviction policy. The mock treats the published TTL as exact and assumes matching entries survive until expiry; that is a simplifying model, not a measured availability guarantee. Conversely, a usage record can reveal that an expected hit did not occur, but usually cannot identify whether the cause was changed content, a short prefix, expiry, a missed lookback, isolation or some other condition. Those ambiguities are a reason to collect controlled request traces, not to infer the provider’s architecture from three counters.

A provider, as documented

examples/ch32/cache_lab.py implements MockProvider, a small executable interpretation of the selected rules above. Each synthetic Block has a tier, kind, content identity, supplied token count and optional breakpoint; a Request names the model and its ordered blocks. Neither the content strings nor their token counts are produced by Claude’s tokenizer. MockProvider.send(req, now) validates the constructed request, looks for existing cumulative-prefix entries and produces a synthetic Usage record. It has a configurable first-response delay and supports two interchangeable stores. It does not model the full Messages API, hidden provider implementation, rate limits or cache pressure.

for idx, _ in bps:                              # for each breakpoint ...
    for j in self.window(req, idx, self.lookback):   # ... look at it and back up to 20 positions
        e = self.store.get(ids, j)
        if e is not None and e.expires > now and e.available_at <= now:
            hits.append(e); highest = max(highest, cum[j]); break

The mock takes the longest prefix found among the eligible lookback hits as the read span, then bills new content up to the final breakpoint as writes and the suffix as ordinary input. It inserts an entry at each qualifying breakpoint and renews an entry’s expiry when read. Crucially, the implementation counts each token only once when several cold breakpoints are present. That agrees with the intended partitioning of its Usage object, but the original research explicitly identified the multi-breakpoint cold-write allocation as an assumption requiring provider verification. Thus send is a candidate model of the public semantics, not a proof that all overlapping or mixed-TTL cases will be charged this way.

bill multiplies the synthetic usage buckets by a frozen 22 October 2026 price table: ordinary input, five-minute writes, one-hour writes, cache reads and output, all per million tokens. For Sonnet 5.5 that snapshot is $2 / $2.50 / $4 / $0.10 / $10** respectively; for Fable 5.1 it is **$10 / $12.50 / $20 / $0.25 / $50; for Haiku 4.5 it is $1 / $1.25 / $2 / $0.10 / $5. Opus 5.5 and Haiku 5.5 have their own rows in the implementation. These prices were independently checked against the public pricing page for this revision, but they are not timeless constants. The tests also price a documentation-style usage record consisting of 2,048 ordinary input tokens, 1,800 read tokens, 148 five-minute write tokens, 100 one-hour write tokens and 503 output tokens. In a live application, model version, pricing modifiers, token-count basis and observation date must accompany every USD result.

The documented behaviours, one at a time

The following cases exercise individual rules inside the mock, including its own assumptions where the provider documentation is incomplete. They establish reproducible program behaviour. They do not validate the mock against real Anthropic usage, and an unexpected live result would require checking the fixture and the rule before attributing it to a provider error.

Minimum length. With the Sonnet 5.5 threshold set to 512, a synthetic 511-token cacheable prefix writes and reads nothing on two requests; a 512-token prefix writes on the first and reads on the second. For Haiku 4.5, the tested transition is between 4,095 and 4,096. This shows the mock enforces its per-model table and silently treats ineligible prefixes as ordinary input. It does not establish the actual provider token count of any text string, since the lab supplies lengths as numbers rather than tokenizing with Claude.

Cumulative prefix matching. The fixture declares 1,500 tokens of tools, 1,500 of system text, then 1,500 of history and a 100-token question, with explicit breakpoints at tools and system. Changing only the question reads the 3,000-token cached prefix. Changing the system text still reuses the 1,500-token tools prefix but writes a new 1,500-token segment. Changing the tools makes both old prefixes ineligible and writes the 3,000 tokens afresh. The result illustrates ordered-prefix invalidation in the mock; an application should also canonicalise tool schemas and other serialized fields that precede a breakpoint.

Lifetime and renewal. In the mock an entry written at request start t=0 is readable at t=299 seconds under the five-minute option and not at t=301; the corresponding one-hour test is 3,599 versus 3,601 seconds. Thirty requests spaced four minutes apart give 29 reads after the first write, while six-minute gaps give none. These are exact boundaries because the simulated clock and expiry rule are exact. The documentation measures lifetime from request start and refreshes it on use; real scheduling delay, long streaming responses and provider-specific availability remain outside this experiment.

First-response availability and parallel requests. The mock makes a new entry readable after a simulated 1.5-second delay to first response. Sixteen requests with one 15,000-token shared prefix, sent before any first response, produce sixteen writes and no reads, costing 1.23 times the no-cache scenario in this priced fixture. Staggering them until after the first response produces one write and fifteen reads, costing 0.195 times. This is a powerful scheduling implication of the documented availability condition; the 1.5-second response-start delay and the financial amounts belong to the mock, not measured Claude latency. Waiting can also add latency, so a real system should compare both cost and end-to-end response time.

Lookback. A breakpoint checks up to 20 positions counting itself. If a conversation appends 19 ordinary blocks, the mock’s moving automatic breakpoint still finds the earlier entry; appending 20 pushes that entry to position 21 and gives no read. Placing an explicit breakpoint back at the known shared prefix recovers the hit even after 30 appended blocks. A consecutive run of synthetic tool results is counted as one position, matching a documented Claude API rule. Lookback searches for previously written entries, not merely any text that happens to be unchanged; a stable prefix with no prior cache write cannot magically become a hit.

Request validation. The mock rejects five explicit breakpoints, a full set of four explicit markers plus automatic placement, incompatible TTLs on the final explicit and automatic marker, and one-hour placement after five-minute placement. It also rejects blocks outside its internal tools/system/messages order. Most of these mirror documented 400-response constraints, but the internal Block.level ordering check is not itself a Messages API request schema. Calling every mock refusal an observed provider HTTP 400 would overstate the evidence. The accepted counterexamples include one-hour before five-minute and a same-TTL automatic marker that becomes a no-op.

Mixed TTLs. An explicitly cached 3,000-token tools prefix at one hour, followed by a 2,000-token system segment at five minutes and a 100-token uncached question, yields a modelled 3,000-token one-hour write, a 2,000-token five-minute write and 100 ordinary input tokens. The creation breakdown sums to cache_creation_input_tokens. This is a useful accounting invariant, but the exact allocation among overlapping cold breakpoints is the place most worth testing with real usage records.

Volatile text. If a timestamp precedes a breakpoint, ten requests thirty seconds apart write ten distinct prefixes and the mock records no reads. Put the changing timestamp after a breakpoint on the stable system prefix and the first request writes while nine subsequent requests read. Neither pattern identifies the reason for a miss from cache_read_input_tokens alone. A diagnosis needs the serialized prefix, the breakpoint placement, model, workspace and request timing, recorded without leaking sensitive prompt content.

One contract, two internals

HashStore indexes cumulative-prefix entries in a dictionary; TrieStore indexes prefixes through a tree of blocks whose common branches are counted once. Both are deliberately small, constructed abstractions. They do not claim to implement actual attention caching, and their memory_tokens() reports a logical token accounting model, not measured bytes of resident KV tensors. Because both stores present the same get and put behaviour to MockProvider, they let us ask how much a usage record could tell an external observer about storage.

The identity experiment generated 4,000 synthetic requests: forty conversations built from three tool sets and six system prompts, growing by turns with varied cache markers, TTLs and models, and averaging roughly forty seconds between requests. Both stores processed the same trace. Their usage records were identical for all 4,000 requests; 3,494 requests had some cache read. At the end, HashStore.memory_tokens() counted 110,700 logical prefix tokens over nineteen live entries while TrieStore.memory_tokens() counted 67,700 with shared paths. These are model counters, not GPU/CPU allocation measurements or provider bills.

The two accounting totals differ by about 1.6×, while all the externally visible usage records in this trace agree. This is an observational-equivalence example: the recorded API fields cannot distinguish these particular stores on these requests. It does not prove the stores are equivalent on every possible request, or that the provider uses a dictionary, trie or KV tensor layout of either kind. Nor does it follow that nothing can be inferred from API behaviour: repeatability, threshold crossings and response metadata can test documented contract properties. The defensible boundary is between observable billing semantics and unobserved physical internals.

A mismatch between a live usage record and a model prediction would falsify the model’s prediction for that case. It would not by itself establish that the provider violated its contract: the mocked token counts, content identity, workspace, model version, time-to-first-response, hidden prompt contributions or interpretation of a documentation clause might be wrong. The harness below is a starting point for controlled comparison of which usage buckets are non-zero, not a complete differential conformance suite.

When a write pays for itself

When a write pays for itself

For one stable, cache-eligible prefix, normalise the ordinary input charge to 1, let a miss write the prefix at multiplier w (1.25 at five minutes or 2 at one hour), and let a hit read it at multiplier r. If a fraction p of repeated requests are cache hits, the stationary average prefix-input cost is p r + (1 − p) w, versus 1 without caching. Caching breaks even when the expression is below 1. The derivation excludes cold-start effects, output, uncached suffixes, provider-specific minimums, eviction and other pricing modifiers; it is not a promise about a whole request’s saving.

p > (w − 1) / (w − r)

For the recorded Sonnet 5.5 read multiplier of 0.05, the thresholds are 20.8% for a five-minute cache and 51.3% for a one-hour cache. They are 20.4% and 50.6% for Fable 5.1 (r = 0.025), and 21.7% and 52.6% for Haiku 4.5 (r = 0.1). The threshold depends primarily on the premium paid on a miss. This is a per-prefix, eligible-traffic comparison; a conversation with substantial output costs or an ineligible short prefix will have different whole-request economics.

Assume requests for the same unchanged eligible prefix form a stationary Poisson process of rate λ and each read renews a usable entry’s TTL T. The interarrival time then has an exponential distribution, so p = 1 − exp(−λT). Combining it with the break-even probability gives λ* = −ln(1 − p*) / T. Under this model, Sonnet 5.5 breaks even at about 2.80 requests/hour for five minutes and 0.72 requests/hour for one hour. The table is the expected price of that prefix’s input, divided by its ordinary input price—not the entire API request including new content and output:

requests per hour 5-minute 1-hour
0.25 1.225 1.569
0.5 1.201 1.233
1 1.154 0.767
2 1.066 0.314
4 0.910 0.086
8 0.666 0.051
12 0.491 0.050
30 0.149 0.050
120 0.050 0.050

Under those assumptions, a five-minute cache with fewer than about three requests per hour for a stable eligible prefix costs more than ordinary input on average; the one-hour cache breaks even at about 0.72 requests per hour. At one per hour, the model predicts a 23% reduction in that prefix’s input charge with one-hour caching but a 15% premium with five-minute caching. At very high reuse rates both converge toward the read multiplier of 0.05. These are thresholds for repeated identical prefixes, not instructions to cache or avoid caching an entire application based on its aggregate request rate.

A consistency experiment sent Poisson arrival times at 0.5, 1, 2, 4, 12, 60 and 600 requests per hour through the mock, with a fixed synthetic 10,000-token prefix and at most 3,000 requests per setting. The observed synthetic multiples differed from the analytic formula by at most 0.015. Because the simulator and the equation share the same assumptions, this checks implementation and arithmetic; it is not independent empirical validation of the provider’s cache-hit probabilities.

Real arrivals are neither necessarily Poisson nor all directed at one identical prefix. Human pauses, shared tool contexts, dynamic system fields and bursty fan-out create different interarrival distributions per reusable cache key. A real application should estimate gaps between opportunities to reuse each canonical prefix, include its model-specific minimum and observed usage buckets, and compare five-minute, one-hour and no-cache policies over representative traces. Moving or varying a breakpoint changes the identity of the object being analysed; the same scalar request rate is then insufficient.

Workloads

Workloads: where caching helps

All values in this section are synthetic total-bill multiples produced by the mock from selected workload shapes and a price table recorded on 22 October 2026. The table entries are not tokenized Claude conversations, real API responses or observed latency changes. The distinction matters: the break-even analysis above prices only a repeated prefix; the workload simulations also include assumed suffix and output-token costs, and those can dilute or reverse the apparent saving.

A chat. The fixture uses twelve turns, a synthetic 3,000-token system prompt, 300 tokens per user message, 400 generated tokens per answer and an eight-second response duration. User pauses are sampled from a log-normal distribution, with the displayed median; there are 300 simulated conversations per cell. The following are whole-conversation price multiples under four breakpoint policies:

median pause system prompt only (5m) automatic (5m) automatic (1h) system 1h, chat 5m
10 s 0.72 / 0.71 / 1.00 0.38 / 0.36 / 0.47 0.45 / 0.44 / 0.55 0.40 / 0.38 / 0.47
60 s 0.73 / 0.72 / 1.00 0.40 / 0.39 / 0.49 0.45 / 0.44 / 0.55 0.41 / 0.40 / 0.49
240 s 0.86 / 0.86 / 1.00 0.71 / 0.70 / 0.76 0.45 / 0.44 / 0.55 0.58 / 0.57 / 0.76
600 s 1.01 / 1.01 / 1.00 1.03 / 1.03 / 1.03 0.47 / 0.46 / 0.57 0.77 / 0.76 / 1.03

Each table cell reports Sonnet 5.5 / Fable 5.1 / Haiku 4.5 using the snapshot’s prices and each model’s cache eligibility. Sonnet and Opus 5.5 have equal multipliers for this workload, though their USD amounts differ because their base prices differ. The table shows three important interactions. First, caching only the 3,000-token system prompt misses savings from the growing conversation; automatic placement catches much more reusable content when turns are close together. Second, at a four-minute median pause many gaps exceed five minutes, making automatic five-minute writes expensive; a one-hour TTL can perform better even with its higher write price. Third, Haiku 4.5’s documented 4,096-token minimum makes the 3,000-token system-only breakpoint ineligible, so its entire column remains 1.00. This is not a general ranking of providers, models or prompt-caching policies.

An agent loop. The synthetic loop has fifteen steps four seconds apart, with 2,000 tokens of tools, 3,000 of system prompt, an initial 400-token task and 1,500 new tokens for a tool call and response at each step. Static breakpoints at tools and system price at 0.74× the uncached Sonnet 5.5 bill; automatic caching prices at 0.23× (0.21× Fable 5.1; 0.27× Haiku 4.5), as the reusable span grows from 5,400 tokens at step two by 1,500 each iteration. Adding those static breakpoints to automatic placement changes nothing in this particular mock trace. A live agent may mutate tool definitions, reorder serialized fields, edit context, run parallel branches or take longer than the TTL; those behaviours would need distinct measurements.

A repeatedly questioned document. The model sees a synthetic 20,000-token document, a 200-token question and a 300-token answer per request. At half a request per hour, both TTL choices cost about 1.18× uncached because writes seldom repay themselves. At two per hour the mock yields 1.04× for five minutes and 0.35× for one hour; at twelve it yields 0.52× and 0.13×; at sixty both are approximately 0.13×. The ratios include the assumed output charge; they are not predictions of document-answering quality, tokenizer efficiency or real provider cache persistence.

A parallel burst. Sixteen requests share a synthetic 15,000-token prefix, each with a 300-token task and 200-token answer. In the Sonnet 5.5 price model, dispatching them before any first response costs $0.64**, compared with **$0.52 uncached. Letting the first response begin before sending the others yields roughly $0.10. This is the modelled cost of the first-response availability rule, not a claim that delaying the batch is faster. For latency-sensitive fan-out, the additional dependency and resulting tail latency could outweigh the input-token saving.

What the usage fields give away, and what to look at

A zero cache_read_input_tokens value is a symptom, not a cause. It can arise from an ineligible prefix, a changed earlier block, unstable tool serialization, a different model or workspace, a changed thinking configuration, expiry, concurrent writes before the first response, or a shared prefix pushed outside the 20-position window. In some cases the response also shows a cache write; in others it shows only ordinary input. Those distinctions are important. Anthropic documents a cache-diagnostics facility for comparing successive prompts, but it was not run for this chapter. No conclusion about hidden eviction or data isolation should be drawn from a zero read alone.

An application’s minimal per-response telemetry is the model ID, request and prefix identity (preferably a privacy-preserving fingerprint rather than raw confidential content), workspace or relevant billing scope, cache-control placement and TTL, start time, response-start time where observable, the three input usage counts, the TTL-specific creation breakdown, output tokens, price-snapshot version and computed bill. It should check that the counts sum and compare cache hit/read share, write share, cost per served request and latency over time. A billing trend is meaningful only after separating changes in traffic mix, tokenisation, prompt composition and list prices from changes in cache behaviour.

The opt-in harness

examples/ch32/live_harness.py contains three opt-in, unexecuted API probes: send a shared prefix twice, send an intended below-minimum prefix twice, and send a pair concurrently before either response can establish a cache entry. They compare whether creation and read usage buckets are non-zero, rather than exact token counts, because the mock assigns token counts and does not invoke Claude’s tokenizer. The tests use an injected fake transport. No paid request or real token-count validation was performed for this book.

The harness requires CH32_LIVE=1, an ANTHROPIC_API_KEY in the environment, an explicit --max-usd, --yes-i-will-be-charged, and either the provider’s base URL or a separate opt-in for a custom one. Without these gates its default command prints a plan and sends nothing. It estimates input tokens by characters divided by 3, charges the estimate as if all input were one-hour writes, and includes each request’s configured maximum output tokens. For the Sonnet 5.5 write-then-read fixture it reports about $0.012. This is a planning estimate, not an upper bound on provider billing: real tokenisation, request overhead, future prices or other modifiers may exceed it. The post-response spending check can detect an overrun only after the billed request, and the concurrent-pair path has no intermediate check. Therefore --max-usd is not a guaranteed hard spending cap. Treat the harness as unqualified for budget-enforced live use until that limitation is fixed and retested.

Its fake-transport tests exercise missing gates, a non-provider base URL from the environment, request structure, identical prefix bytes across the pair, TTL placement, expected nonzero usage buckets and a post-response spend overrun. Those tests establish that the current control flow refuses some accidental invocations; they cannot certify an upper cost limit, provider headers or live correctness. Before authorising use with real credentials, add a tokenizer-grounded or defensible upper-limit estimator, strict positive finite budget validation, a reservation of estimated funds before each send, a process-wide cap for parallel sends, and a provider-response reconciliation that records unexpected usage and stops further requests. Review the currently configured API version against the provider documentation before running.

What the numbers do not show

  • No provider requests. The results are mock outputs, algebra and dated public prices—not real Claude usage, hits, latency or eviction observations.
  • Contract interpretation is not provider conformance. The mock’s exact TTL, supplied token counts, cold-write allocation and abstract block grammar simplify documented behaviour; some API edge cases may be missing.
  • Documentation is time-dependent. The original research read summaries of portions of provider pages on 22 October 2026. The principal prompt-caching and pricing rules used here were checked again against public documentation for this editorial revision; that does not freeze future changes.
  • Synthetic traffic and counting. Conversations, output lengths and pauses are constructed. Claude tokenisation is not performed, and different models may produce different numbers of tokens for the same content.
  • Break-even restrictions. The analytic thresholds assume one eligible stable prefix with Poisson reuse, perfect TTL availability and fixed prices. They do not give an unconditional whole-request saving.
  • No physical storage measurements. The hash/trie comparison counts logical tokens under assumed storage models; it says nothing about provider KV tensors, memory bytes or eviction.
  • No measured latency. Waiting for a first response can increase end-to-end latency even if it reduces the cached-input bill.
  • The live harness is not a hard budget enforcement system. Its input-token count is heuristic and its cap check is retrospective; no real API requests or charges were made.
  • Isolation is provider-described. Workspace and organisation boundaries are documented policies, not independently probed privacy or side-channel guarantees.

Inference Lab increment

examples/ch32/cache_lab.py adds:

  • Price, PRICES, MIN_CACHEABLE, and Usage, with bill and uncached_bill using the 22 October 2026 snapshot.
  • Block, Request and MockProvider, which validate an abstract ordered request, place breakpoints, search existing entries, and produce synthetic usage.
  • HashStore and TrieStore, interchangeable logical stores used to demonstrate observational non-identifiability on a fixed trace.
  • breakeven_hit_probability, hit_probability, expected_prefix_multiple and breakeven_rate_per_hour, with explicit Poisson and stable-prefix assumptions.
  • Synthetic chat, agent-loop, document and parallel-request workload generators, and contract, identity, breakeven and workloads commands.

examples/ch32/live_harness.py adds experiment_requests, estimate_cost_usd, check_gates, run and compare_with_mock. Its provider transport is gated and its mock comparison checks nonzero usage buckets, but the estimate is based on characters per token and cannot enforce the stated cap as a guaranteed financial limit. The live path is NOT_RUN and should not be presented as budget-qualified without the additional safeguards specified above.

To check the mock against the documented rules and print the break-even table:

python examples/ch32/cache_lab.py contract
python examples/ch32/cache_lab.py breakeven

The chapter’s engineering rule is: treat hosted prompt caching as an observable billing contract, not a window into the provider’s physical cache. Preserve and version the stable prefix, place its breakpoint before volatile fields, choose TTLs from per-prefix reuse gaps, and inspect all usage buckets against a dated price table. For parallel fan-out, explicitly weigh the cost of early duplication against the latency cost of waiting for a first response. For a paid test, obtain authorisation, verify the model and API contract, and enforce a credible cost bound before sending requests. A mock can justify a hypothesis; only measured provider responses can confirm its prediction.

What you should now be able to do

  • Identify the documented cache-control options, model-specific eligibility, prefix-ordering rules and the three input usage fields; compute the full input total correctly.
  • Derive the break-even hit probability and Poisson request rate for one eligible, unchanged prefix, and explain why the result is not a whole-request guarantee.
  • Show how TTL, the 20-position lookback, automatic breakpoints, volatile context and first-response availability change simulated cache accounting.
  • Reproduce and interpret the chat, agent-loop, document and parallel-burst cost models without describing them as provider measurements.
  • Explain why identical usage from two mock stores cannot identify the underlying storage mechanism.
  • Design privacy-conscious cache telemetry that distinguishes misses, writes and ordinary input.
  • Review a paid harness and identify why a heuristic cost estimate plus a post-response check cannot guarantee --max-usd.

Key terms

  • Breakpoint: the marked end of a prefix eligible for lookup and potential cache creation.
  • Cumulative prefix identity: the exact ordered content through a breakpoint, used to match previously written entries.
  • Lifetime (TTL): the documented validity period, starting at request start and refreshed when an entry is used.
  • Cache write / read: newly processed cached-prefix input charged at the TTL-specific write rate, versus reused input charged at the read rate.
  • Lookback window: at most twenty candidate positions examined backwards from a breakpoint, counting the breakpoint itself.
  • Minimum cacheable prefix: a per-model length below which marking a prefix produces no cache write or hit.
  • Usage partition: input_tokens, cache_creation_input_tokens and cache_read_input_tokens; their sum accounts for total input.
  • Contract: documented externally observable behaviour; not an implementation description.
  • Break-even probability: a hit fraction above which the average eligible-prefix input bill beats uncached input under explicit assumptions.
  • Non-identifiability: two different internal models give the same observations over a specified set of requests.
  • Preflight estimate versus spending cap: a prediction of charge is not a guaranteed bound, and an after-the-fact stop cannot prevent an already incurred charge.

Reader exercises

  1. Audit without spending. Run the contract, identity, breakeven and workloads commands locally. Verify usage partitioning and record versions, seeds and dated prices.
  2. Repair the live budget guard. Reject non-finite, zero and negative budgets; obtain an actual token count or a proven conservative bound for every payload; reserve the worst-case amount before each send, including the parallel pair; and test that no allowed execution can exceed the cap through already launched requests.
  3. Verify with explicit permission. Only after the guard is qualified, run the smallest paid experiment with an authorised key and budget; compare model/version, prefix token counts, cache-write/read buckets and request timing with the mock. Record disagreements without calling them provider faults prematurely.
  4. Replace Poisson gaps with anonymised real interarrival times for each stable prefix, and recompute the TTL decision including cold starts and output costs.
  5. Model an agent whose tool schemas reorder or whose system date changes on every turn; test whether canonicalising those inputs restores reuse.
  6. Add the Batch API and other pricing modifiers to the dated cost model, distinguishing independently documented discounts from the chapter’s assumptions.
  7. Add pre-warming with max_tokens: 0 to the mock and evaluate both its monetary cost and the delay before a new entry becomes usable.
  8. Model cache eviction and isolation as explicit alternative hypotheses; find request traces that distinguish their usage predictions without claiming to identify physical storage.
  9. Compare the provider-style billing model with Chapter 16’s measured self-hosted cache: tokens of prefill avoided, first-token latency and the cost of maintaining cache state.
  10. Extend Chapter 2’s manifest with canonical prefix hash, model, endpoint, workspace scope, breakpoint/TTL policy, pricing date, simulation-versus-provider evidence status and a content-privacy policy.

References

Provider contract and dated pricing

  • Anthropic, Prompt caching — documented automatic and explicit breakpoints, TTLs, minimums, lookback, first-response availability, usage accounting, isolation and limitations; originally researched 22 October 2026 and checked again for this revision.
  • Anthropic, Messages API — stateless messages, content blocks, cache_control, model and API-version parameters; referenced as provider documentation, not tested live.
  • Anthropic, Pricing — price table and cache-write/read multipliers. All numerical examples in this chapter retain the 22 October 2026 snapshot, rather than silently repricing past experiments.

Evidence in this chapter

Claim Evidence status and limits
Anthropic describes prefix matching, caching minima, 5-minute/1-hour TTLs, twenty-position lookback, usage partition and scope isolation Provider documentation; not independently verified by API calls
The mock reproduces the configured thresholds, prefix changes, synthetic TTL boundaries, concurrent first writes, lookback and mixed TTL accounting Modelled from documented rules and explicitly identified assumptions
Two different stores produce identical usage for 4,000 synthetic requests but count 110,700 versus 67,700 logical stored tokens Book experiment on two constructed stores; not actual resident KV memory
The Sonnet 5.5 per-prefix break-even hit probabilities are 20.8% (5m) and 51.3% (1h), with Poisson thresholds of 2.80 and 0.72 requests/hour Derived for one unchanged eligible prefix with stationary Poisson reuse and perfect TTL availability
Synthetic Poisson mock results agree with the analytic prefix-cost formula to 0.015 Model-vs-equation consistency check, not independent provider validation
Chat, agent-loop, document and burst cost multiples Simulated with assigned token counts, workloads and prices dated 22 October 2026
A 3,000-token system-only breakpoint falls short of the 4,096-token Haiku 4.5 minimum Modelled from documented per-model eligibility
Hash/trie results identify Anthropic’s memory layout, tensor representation or eviction Not inferable from these counters; no provider implementation observed
live_harness.py enforces a hard USD ceiling Not established: heuristic token estimate, retrospective stop and concurrent sends prevent a hard-cap claim
Anthropic responses, real hit ratios, provider latency, actual charges, cache eviction or side-channel behaviour NOT_RUN / NOT_MEASURED
Prompt Cache, PagedAttention and SGLang results apply to the Claude backend Not claimed; they provide external systems context only

Implementation status

  • Manuscript: content/books/inference/32-chapter.md.
  • Runnable model: examples/ch32/cache_mock.py (original starter, unchanged) and examples/ch32/cache_lab.py (documented-rule mock, two logical stores, billing, break-even and workload simulations).
  • Provider harness: examples/ch32/live_harness.py (opt-in; exercised only through fake transports; NOT_RUN with paid API credentials). Its budget mechanism still needs qualification.
  • Tests: tests/test_ch32_cache.py (starter) and tests/test_ch32_cache_lab.py (32 recorded no-network tests spanning usage partition, lookback, TTL boundaries, mixed breakpoints, synthetic identity, algebra, prices and fake-transport gates). The test count is a repository statement, not a test run during this editorial revision.
  • Evidence: research/ch32/sources.md, research/ch32/results.json, research/ch32/build_results.py and research/evidence-register.md.
  • Repository verification command: python -m unittest discover -s tests -v. The paid harness must not be run to verify editorial changes.

The chapter keeps draft = false for the website, but its evidential status is still research-backed simulation, not a validated production integration. The most important outstanding qualification is to replace the live harness’s heuristic spending estimate with a defensible pre-send bound and to validate the cache-accounting model against authorised real usage. Chapter 33 proceeds to reasoning models, where extra output and thinking-token costs make these distinctions still more important.