Prompt Caching Cost Test: 5 Models, 12 Steps, 70 Min A roughly 350-line Python harness across six files measures prompt-caching costs on five flagship models — Claude Fable 5.2, GPT-6.2 Astra, GPT-6.2 Sol, Gemini 4 Neon and DeepSeek V4.1-Flash — converting each API's returned cached-token counts into dollars and reporting how many calls per prefix are needed before caching pays off, according to Shattered, which published the test. The harness takes about 70 minutes from an empty folder and includes a dry-run mode that needs no API keys. Shattered reports cached input tokens cost roughly 2% to 5% of standard input prices, with Anthropic listing Claude Fable 5.2 cache reads at $0.20 per million tokens against $8 standard input and Google pricing Gemini 4 Neon cached input at $0.15 against $3 uncached, but notes that cache writes cost more than standard input, so the discount only begins on the second call. Cached input tokens on the current flagship APIs cost roughly 2% to 5% of the normal input price, and that one line item decides whether a long-context app is cheap or ruinous. Anthropic’s pricing documentation lists cache reads for Claude Fable 5.2 at $0.20 per million tokens https://platform.claude.com/docs/en/about-claude/pricing?jumpid=ba 31mpyr4wn6 , while Google prices Gemini 4 Neon cached input at $0.15 against $3 uncached, a 95% discount. The catch is that every vendor defines a cache hit differently, and the discount only appears when your traffic matches the rules. A small Python harness settles the question with your own prompts instead of a vendor chart. It fires one long prefix at Claude Fable 5.2, GPT-6.2 Astra, GPT-6.2 Sol, Gemini 4 Neon and DeepSeek V4.1-Flash, reads the cached-token counts each API returns, converts them into dollars, and reports how many calls per prefix you need before caching pays off. The code runs about 350 lines of Python across six files, takes roughly 70 minutes from an empty folder, and ships with a dry-run mode that needs no API keys. The harness also answers the questions list prices cannot: how long a cache entry survives, whether editing one word near the top of a prompt wipes the discount, how big a prefix must be before caching starts, and what happens when twenty workers hit a cold prefix at once. If you only care about price tags, the coding-agent price comparison https://shattered.io/claude-vs-gemini-vs-chatgpt-coding-agents-fable-5-2-neon-astra-3-vs-8-2026/ covers the same model lines side by side. If you care about what your own traffic will really cost, keep reading. Don't miss new tech stories on Google Add Shattered once in the Google app and our stories show up in your news suggestions. Add now https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F Prompt Caching Prices: The Cached-Input Gap Across Five Models Start with list prices, because they cap what any measurement can show. OpenAI’s model documentation https://developers.openai.com/api/docs/models/compare splits the GPT-6.2 line into Astra and Sol, both announced on November 17, 2026. Astra is the flagship for demanding reasoning and coding. Sol trades some capability for a much lower price. Google’s announcement for Gemini 4 Neon is dated November 18, 2026, and DeepSeek released V4.1-Flash on September 10, 2026 with a price cut at launch. Prices below are dollars per million tokens, taken from each vendor’s published rate pages as of December 1, 2026. | Model | Standard input | Cached input | Cached as share of input | |---|---|---|---| | GPT-6.2 Astra | $8 | $0.40 | 5% | | GPT-6.2 Sol | $2 | $0.10 | 5% | | Gemini 4 Neon | $3 | $0.15 | 5% | | DeepSeek V4.1-Flash, peak hours | $0.30 | $0.006 | 2% | | DeepSeek V4.1-Flash, off-peak | $0.15 | $0.003 | 2% | Claude Fable 5.2 sits outside the table because Anthropic’s pricing page lists its prices separately: $8 per million input tokens, $40 per million output tokens, $10 per million tokens for cache writes and $0.20 per million tokens for cache reads. Because a cache write costs more than standard input, the first call that writes a prefix costs more than an uncached call, and the discount only starts on call two. OpenAI prices writes too, at least for its explicit retention options. According to OpenAI’s rate card, 12-hour cache writes cost 2.5 times the ordinary input price. Research summaries of the same card reportedly list 30-minute writes at $10 per million tokens for Astra and $2.50 for Sol, and 12-hour writes at $20 and $5. The rate card’s labels differ between its enterprise and API tables, so treat those write figures as a starting point and confirm them in your own billing console before you rely on them. The write premium creates a break-even point. With a write price W, a cached-read price R and a standard input price P, a prefix pays for itself after n calls when W + n – 1 x R is no larger than n x P. Solve for n and you get W – R divided by P – R , rounded up. For Fable 5.2 with the $10 write price, $0.20 read price and $8 input price, that is $10 minus $0.20 divided by $8 minus $0.20, so two calls. For a vendor with no write premium, the answer is one call, because the second call is already cheaper. Price is not the whole bill, either. Caching only touches the input side. On Astra, a long prefix costs $8 per million tokens as uncached input and $0.40 per million tokens once cached. If the answer runs 500 tokens at $40 per million, the output adds $0.02 regardless. Short prefixes with long answers barely move. Long prefixes with short answers, such as classification, extraction and retrieval over fixed documents, move a lot. DeepSeek adds a second dial: peak and off-peak pricing. Its pricing page states that off-peak rates are 50% of peak rates, so a cache hit costs $0.003 off-peak and $0.006 at peak. The harness defaults to peak prices because they are the conservative choice. Switch the config to off-peak numbers if your batch jobs run overnight in the vendor’s off-peak window. For a longer look at how DeepSeek’s headline rates stack up against OpenAI, see our DeepSeek against ChatGPT API cost breakdown https://shattered.io/deepseek-vs-chatgpt-api-cost-v4-1-flash-vs-gpt-6-2026/ , and for DeepSeek’s own announcement of the V4.1-Flash price cut, read the V4.1-Flash release notice https://www.deepseek.com/en/news/deepseek-v4-1-flash/index.txt? rsc=x2ac0 . Prerequisites and Versions for the Prompt Caching Test The build needs little. Anthropic-only readers can start with the single-vendor Claude walkthrough https://shattered.io/prompt-caching-claude-api-12-steps-2026/ and return here for the cross-vendor comparison. Most of the effort goes into pinning exact model IDs and keeping prices in one file so you can update them the day a vendor changes a rate card. - Python , a current release. The code was written and run on a recent release. - requests for HTTP. Any recent release works. - pytest for the unit tests in Step 11. Any recent release works. - API keys for the vendors you want to measure: ANTHROPIC API KEY , OPENAI API KEY , GEMINI API KEY and DEEPSEEK API KEY . Each is optional. The runner skips any model whose key is missing. - A spending cap on every vendor console. List-price math puts a full live run of the default settings at a few dollars across all five models, but a typo in a loop can multiply that quickly. - Linux, macOS or WSL with a terminal that can stay open for about 30 minutes during the cache-lifetime probe. - About 70 minutes : 25 for the code, 5 for a dry run, and roughly 40 for a live run, most of it spent waiting on the longest gap probe. Pin model IDs exactly as the vendor documents them. This build uses claude-fable-5-2 for Fable 5.2, gpt-6.2-astra and gpt-6.2-sol for the two OpenAI models, and deepseek-flash https://shattered.io/open-weight-models-kimi-k3-1-pro-vs-deepseek-v4-1-flash-qwen4-max-glm-5-3-2026/ Gemini model pages on Google DeepMind https://deepmind.google/models/gemini/ or from the model list in Google AI Studio, then paste it into the config in Step 2. The value in this build, gemini-4-neon , is a placeholder until you confirm it. Retired and renamed models matter here. DeepSeek’s old deepseek-v4-flash and deepseek-v4-flash-vision-exp names still answer, but they now route to the V4.1-Flash-1017 model and bill at Flash rates, so a harness that targets them measures the wrong thing under the wrong label. Likewise, DeepSeek-V4-Pro requests are now routed to V4.1-Flash at Flash rates, and a V4.1-Pro remains only a rumor, with no release confirmed. Test the model you intend to ship, under the name the vendor now documents. One privacy note before you send anything. A cache stores processed input on the vendor’s side for the life of the entry, so the prefix you test with should contain no customer data. The harness generates synthetic policy text for exactly that reason, and the same habit is worth keeping when you adapt it to your real prompts. How Each API Reports Cached Tokens The hardest part of a cross-vendor cache test is not the network code. It is that four APIs describe the same event with four different shapes, and two of them use the word input to mean different things. Read the table below before writing a line of parsing logic. | Vendor path | How a prefix gets cached | Usage fields the adapter reads | Trap to avoid | |---|---|---|---| | Anthropic Messages API Fable 5.2 | Explicit marker on a content block: cache control set to ephemeral | input tokens , cache read input tokens , cache creation input tokens , output tokens | input tokens excludes cached and written tokens, so it is not the prompt size | | OpenAI Chat Completions GPT-6.2 Astra, Sol | Automatic prefix matching, with retention options that carry their own write price | prompt tokens , prompt tokens details.cached tokens , completion tokens | prompt tokens includes cached tokens, so subtract to get fresh input | | DeepSeek Chat Completions deepseek-flash | Automatic prefix matching | prompt cache hit tokens , prompt cache miss tokens , completion tokens | Hit and miss are separate counters, so sum them for the prompt size | | Gemini generateContent Gemini 4 Neon | Automatic on the path this harness tests | promptTokenCount , cachedContentTokenCount , candidatesTokenCount | The prompt count includes cached tokens, and thinking tokens may be reported separately | Field names in that table match the public API references for the previous model generations, and vendors have kept them stable across releases. Still, do not trust a table, including this one. Step 4 includes a one-line raw-usage dump so you can see exactly what your account returns before the adapters interpret it. The harness normalizes everything into four counters. fresh in is input billed at the standard rate. cached in is input served from cache. written in is input written to cache at the write price, which only the explicit-style Anthropic path reports separately. out is output. Every cost and hit-rate calculation downstream uses those four numbers and nothing else, which keeps the vendor quirks confined to one file. A word on what this harness does not test. Gemini also supports a path where you create a cache object explicitly and reference it by name, and OpenAI sells explicit retention tiers. The adapters send plain requests and let each vendor’s automatic matching do the work, because that is what most apps ship first. Add the explicit variants as extra entries in models.json once the automatic baseline is in hand, using the extra body field that the OpenAI adapter already forwards. Steps 1 to 3: Project Setup, Pinned Prices and a Salted Prefix Step 1: Create the project and install two packages Make a folder, a virtual environment and a place for results. Export only the keys you plan to use. A missing key is not an error, since the runner prints a skip line and moves on. mkdir cachetest && cd cachetest python3 -m venv .venv && source .venv/bin/activate pip install requests pytest export ANTHROPIC API KEY="sk-ant-..." export OPENAI API KEY="sk-..." export GEMINI API KEY="..." export DEEPSEEK API KEY="sk-..." Step 2: Pin model IDs and prices in one file Prices live in models.json , in dollars per million tokens, next to the exact model ID. Keeping them out of the code means a rate-card change is a one-line edit, and it means a result file from last month can be re-priced without rerunning any calls. The write field is the price of tokens written to cache. Where a vendor charges no premium, set it equal to input . The style field tells the dry-run simulator whether a vendor reports writes separately. { "fable": { "provider": "anthropic", "model": "claude-fable-5-2", "style": "explicit", "input": 8.00, "cached": 0.20, "write": 10.00, "output": 40.00 }, "astra": { "provider": "openai", "model": "gpt-6.2-astra", "style": "automatic", "max tokens field": "max completion tokens", "extra body": {}, "input": 8.00, "cached": 0.40, "write": 8.00, "output": 40.00 }, "sol": { "provider": "openai", "model": "gpt-6.2-sol", "style": "automatic", "max tokens field": "max completion tokens", "extra body": {}, "input": 2.00, "cached": 0.10, "write": 2.00, "output": 10.00 }, "neon": { "provider": "gemini", "model": "gemini-4-neon", "style": "automatic", "input": 3.00, "cached": 0.15, "write": 3.00, "output": 15.00 }, "dsflash": { "provider": "deepseek", "model": "deepseek-flash", "style": "automatic", "input": 0.30, "cached": 0.006, "write": 0.30, "output": 1.20 } } Two entries deserve a second look. The Fable write price of $10 is the reported figure from Anthropic’s pricing page, so confirm it against your own console. The DeepSeek entry uses peak prices, which is the pessimistic choice. The OpenAI entries set write equal to input because the harness exercises the automatic path. If you test a 30-minute or 12-hour retention option later, raise write to the rate-card figure and add the vendor’s retention parameter to extra body . Step 3: Build a deterministic prefix with a salt at the front A cache test lives or dies on the prefix. It must be long enough to clear any minimum size, identical across calls in one experiment, and different across experiments. The builder below generates synthetic policy text from a seeded random generator, and it puts a run-specific salt on the very first line. That placement matters. Prefix caches match from the first token forward, so a salt at the top guarantees the first call of every experiment starts cold, even if you rerun the script five minutes later. python import hashlib import random TOPICS = "refund window", "warranty claim", "shipping delay", "account recovery", "invoice dispute", "data export", "seat transfer", "api quota", "sso setup", "audit log", "retention rule", "escalation path" def build prefix words: int, salt: str - str: """Deterministic support-policy text. The salt goes FIRST so each run starts cold.""" rng = random.Random salt lines = f"RUN-ID {salt}. You are a support assistant. Answer only from the policy below." count = len lines 0 .split n = 1 while count < words: topic = TOPICS n % len TOPICS a, b, c = rng.randint 2, 90 , rng.randint 2, 30 , rng.randint 100, 999 line = f"Policy {n}: for a {topic}, the agent checks case {c}, waits {a} days, " f"then escalates after {b} contacts and records the outcome in the ledger." lines.append line count += len line.split n += 1 return "\n".join lines def prefix hash text: str - str: return hashlib.sha256 text.encode .hexdigest :12 A tiny clock module comes next. Real runs use the monotonic clock. Dry runs use a virtual clock that advances without sleeping, which lets the simulator replay a 30-minute gap probe in milliseconds. php import time class RealClock: def now self - float: return time.monotonic def sleep self, seconds: float - None: time.sleep seconds class VirtualClock: """Dry runs skip the waiting but still advance time for the fake cache.""" def init self - None: self.t = 0.0 def now self - float: return self.t def sleep self, seconds: float - None: self.t += seconds The default prefix is 6,000 words. In the dry run the token count is an estimate based on the usual four-characters-per-token rule of thumb. Your live token counts will differ, because every vendor tokenizes differently. That difference is useful. The same text produces different prompt sizes on different APIs, and the harness reports whatever each vendor says. Steps 4 and 5: Provider Adapters and the Cost Math Step 4: Write one adapter per API and normalize the usage block Each adapter sends the same prefix as a system prompt and a short question as the user turn, caps the answer at 64 tokens, and returns a Usage record. Capping output keeps the spend predictable and keeps the experiment about input. The Anthropic adapter adds the cache control marker to the prefix block. The other three rely on automatic matching. python import os import time from dataclasses import dataclass import requests @dataclass class Usage: fresh in: int input tokens billed at the normal rate cached in: int input tokens served from cache written in: int input tokens written to cache explicit-style APIs out: int latency s: float def post url, headers, body : t0 = time.perf counter r = requests.post url, headers=headers, json=body, timeout=180 dt = time.perf counter - t0 if r.status code = 400: raise RuntimeError f"HTTP {r.status code} from {url}: {r.text :300 }" return r.json , dt def call anthropic cfg, prefix, question : body = { "model": cfg "model" , "max tokens": 64, "system": {"type": "text", "text": prefix, "cache control": {"type": "ephemeral"}} , "messages": {"role": "user", "content": question} , } headers = {"x-api-key": os.environ "ANTHROPIC API KEY" , "anthropic-version": "2023-06-01"} data, dt = post "https://api.anthropic.com/v1/messages", headers, body u = data "usage" input tokens EXCLUDES the cached and the written portions on this API return Usage u "input tokens" , u.get "cache read input tokens", 0 , u.get "cache creation input tokens", 0 , u "output tokens" , dt def chat body cfg, prefix, question : body = {"model": cfg "model" , "messages": {"role": "system", "content": prefix}, {"role": "user", "content": question} } body cfg.get "max tokens field", "max tokens" = 64 body.update cfg.get "extra body", {} return body def call openai cfg, prefix, question : headers = {"Authorization": "Bearer " + os.environ "OPENAI API KEY" } data, dt = post "https://api.openai.com/v1/chat/completions", headers, chat body cfg, prefix, question u = data "usage" cached = u.get "prompt tokens details" or {} .get "cached tokens", 0 return Usage u "prompt tokens" - cached, cached, 0, u "completion tokens" , dt def call deepseek cfg, prefix, question : headers = {"Authorization": "Bearer " + os.environ "DEEPSEEK API KEY" } data, dt = post "https://api.deepseek.com/chat/completions", headers, chat body cfg, prefix, question u = data "usage" hit = u.get "prompt cache hit tokens", 0 miss = u.get "prompt cache miss tokens", u "prompt tokens" - hit return Usage miss, hit, 0, u "completion tokens" , dt def call gemini cfg, prefix, question : url = "https://generativelanguage.googleapis.com/v1beta/models/" f"{cfg 'model' }:generateContent" body = {"systemInstruction": {"parts": {"text": prefix} }, "contents": {"role": "user", "parts": {"text": question} } , "generationConfig": {"maxOutputTokens": 64}} data, dt = post url, {"x-goog-api-key": os.environ "GEMINI API KEY" }, body u = data "usageMetadata" cached = u.get "cachedContentTokenCount", 0 return Usage u "promptTokenCount" - cached, cached, 0, u.get "candidatesTokenCount", 0 , dt LIVE = {"anthropic": call anthropic, "openai": call openai, "deepseek": call deepseek, "gemini": call gemini} KEYS = {"anthropic": "ANTHROPIC API KEY", "openai": "OPENAI API KEY", "deepseek": "DEEPSEEK API KEY", "gemini": "GEMINI API KEY"} class FakeCache: """Toy prefix cache for dry runs. TTL and minimum size are made-up knobs, not vendor facts.""" def init self, cfg, clock, ttl s=300, min tokens=1024, ready s=1.0 : self.cfg, self.clock = cfg, clock self.ttl s, self.min tokens, self.ready s = ttl s, min tokens, ready s self.entries = text, last seen, created def shared chars self, prefix, now : best = 0 for text, seen, created in self.entries: if now - seen self.ttl s or now - created < self.ready s: continue n = 0 for x, y in zip prefix, text : if x = y: break n += 1 best = max best, n return best def call self, cfg, prefix, question : now = self.clock.now ptoks = len prefix // 4 qtoks = max 1, len question // 4 if ptoks < self.min tokens: return Usage ptoks + qtoks, 0, 0, 40, 1.1 cached = min ptoks, self. shared chars prefix, now // 4 if cached < self.min tokens: cached = 0 self.entries = e for e in self.entries if now - e 1 <= self.ttl s self.entries.append prefix, now, now rest = ptoks - cached if cfg "style" == "explicit": return Usage qtoks, cached, rest, 40, 0.4 if cached else 1.1 return Usage rest + qtoks, cached, 0, 40, 0.4 if cached else 1.1 def get caller cfg, clock, dry run : if dry run: return FakeCache cfg, clock return LIVE cfg "provider" The toy cache at the bottom of the file powers the dry run. It matches on shared prefixes the way real caches do, expires entries after a configurable lifetime, ignores prefixes below a minimum size, and refuses to serve an entry until a short ready delay has passed. All three knobs are made-up values. They exist so you can test the harness logic, not to describe any vendor’s behavior. Never quote a dry-run number as a measurement. Before the first live run, add a temporary print data "usage" or usageMetadata for Gemini right after each post call and fire a single request per vendor. Compare the raw block with the table from the previous section. If a field name differs on your account, fix the adapter now. Finding that mismatch after a two-hour run is expensive. Once the adapters work, log what they return. A harness like this is a one-off experiment, but production needs the same four counters on every request, and the LLM observability walkthrough in Python https://shattered.io/llm-observability-python-tokens-cost-latency-12-steps-2026/ shows how to capture tokens, cost and latency per call so a falling hit rate shows up on a dashboard instead of an invoice. Step 5: Price every call and compute the break-even The cost module is deliberately small, because small code is easy to audit. cost prices a call with the cache discount. baseline prices the identical traffic as if nothing had been cached. hit rate divides cached tokens by all input tokens, written tokens included. breakeven calls implements the formula from the first section. python import math def cost u, p : return u.fresh in p "input" + u.cached in p "cached" + u.written in p "write" + u.out p "output" / 1e6 def baseline u, p : total in = u.fresh in + u.cached in + u.written in return total in p "input" + u.out p "output" / 1e6 def hit rate u : total in = u.fresh in + u.cached in + u.written in return u.cached in / total in if total in else 0.0 def breakeven calls p : """Smallest call count n where write + n-1 cached <= n input, per prefix token.""" if p "write" <= p "input" : return 1 return math.ceil p "write" - p "cached" / p "input" - p "cached" Note the guard in breakeven calls . When the write price does not exceed the input price, the answer is one call, since no premium needs recovering. When it does, the function rounds up, because you cannot make a fraction of a call. The function ignores output tokens on purpose. Output costs the same with or without caching, so including it would only blur the break-even point. Step 6: Run the Warm-Call Experiment The runner ties everything together. It loads the config, builds a fresh prefix for each model, sends the first call cold, then sends the remaining calls two seconds apart with different questions against the same prefix. The first call pays whatever a cold start costs. Every later call should hit the cache. The summary row shows the average hit rate across calls two onward, the total cost with caching, the cost of the same traffic without it, and the savings. python import argparse import json import os import sys from concurrent.futures import ThreadPoolExecutor from adapters import KEYS, get caller from clock import RealClock, VirtualClock from costs import baseline, breakeven calls, cost, hit rate from prefix import build prefix QUESTIONS = "What is the refund window?", "Who handles invoice disputes?", "How long before escalation?", "Where are outcomes recorded?", "What happens after a shipping delay?", "How do I export data?", "Can a seat be transferred?", "What is the audit log for?" def warm run name, cfg, caller, clock, words, calls, gap, run id : prefix = build prefix words, f"{run id}-{name}" rows = for i in range calls : u = caller cfg, prefix, QUESTIONS i % len QUESTIONS rows.append u clock.sleep gap return rows def gap probe name, cfg, caller, clock, words, gaps, run id : prefixes = {} for g in gaps: prefixes g = build prefix words, f"{run id}-{name}-gap{g}" caller cfg, prefixes g , QUESTIONS 0 waited, out = 0.0, for g in sorted gaps : clock.sleep g - waited waited = g out.append g, hit rate caller cfg, prefixes g , QUESTIONS 1 return out def edit probe name, cfg, caller, clock, words, run id : base = build prefix words, f"{run id}-{name}-edit" caller cfg, base, QUESTIONS 0 clock.sleep 2 early = base.replace "Policy 2:", "Policy two:", 1 late = base :-12 + "CHANGED-END." return hit rate caller cfg, early, QUESTIONS 1 , hit rate caller cfg, late, QUESTIONS 2 def size sweep name, cfg, caller, clock, sizes, run id : out = for w in sizes: prefix = build prefix w, f"{run id}-{name}-size{w}" caller cfg, prefix, QUESTIONS 0 clock.sleep 2 u = caller cfg, prefix, QUESTIONS 1 out.append w, u.fresh in + u.cached in + u.written in, hit rate u return out def burst name, cfg, caller, clock, words, width, run id : prefix = build prefix words, f"{run id}-{name}-burst" with ThreadPoolExecutor width as pool: first = list pool.map lambda q: caller cfg, prefix, q , QUESTIONS :width clock.sleep 2 after = caller cfg, prefix, QUESTIONS 0 return sum 1 for u in first if u.cached in 0 , hit rate after def main : ap = argparse.ArgumentParser ap.add argument "--models", nargs="+", default= "fable", "astra", "sol", "neon", "dsflash" ap.add argument "--words", type=int, default=6000 ap.add argument "--calls", type=int, default=6 ap.add argument "--gap", type=float, default=2 ap.add argument "--gaps", type=float, nargs=" ", default= 30, 120, 600, 1800 ap.add argument "--sizes", type=int, nargs=" ", default= ap.add argument "--burst", type=int, default=0 ap.add argument "--run-id", default="r1" ap.add argument "--dry-run", action="store true" ap.add argument "--out", default="results.jsonl" a = ap.parse args cfgs = json.load open "models.json" clock = VirtualClock if a.dry run else RealClock print f"{'model':8} {'calls': 5} {'hit%': 6} {'cost': 10} {'no-cache': 10} {'saved%': 7} {'break-even': 10}" with open a.out, "w" as sink: for name in a.models: cfg = cfgs name if not a.dry run and KEYS cfg "provider" not in os.environ: print f"{name:8} skipped: set {KEYS cfg 'provider' }", file=sys.stderr continue caller = get caller cfg, clock, a.dry run rows = warm run name, cfg, caller, clock, a.words, a.calls, a.gap, a.run id spent = sum cost u, cfg for u in rows plain = sum baseline u, cfg for u in rows later = rows 1: hr = sum hit rate u for u in later / max 1, len later print f"{name:8} {len rows : 5} {hr 100: 5.1f}% ${spent: 9.4f} ${plain: 9.4f} " f"{ 1-spent/plain 100: 6.1f}% {breakeven calls cfg : 10}" for i, u in enumerate rows : sink.write json.dumps {"model": name, "call": i + 1, u. dict } + "\n" probe = gap probe name, cfg, caller, clock, a.words, a.gaps, a.run id print " gap probe: " + " ".join f"{int g }s- {h 100:.0f}%" for g, h in probe early, late = edit probe name, cfg, caller, clock, a.words, a.run id print f" edit probe: early edit {early 100:.0f}% hit, late edit {late 100:.0f}% hit" if a.sizes: sweep = size sweep name, cfg, caller, clock, a.sizes, a.run id print " size sweep: " + " ".join f"{w}w/{t}t- {h 100:.0f}%" for w, t, h in sweep if a.burst: hits, after = burst name, cfg, caller, clock, a.words, a.burst, a.run id print f" burst x{a.burst}: {hits} hits inside the burst, {after 100:.0f}% on the next call" if name == " main ": main The file also holds the three probes that Steps 7 to 10 use. Each probe builds its own salted prefix, so probes never contaminate one another or the warm-call run. The runner skips live models whose key is missing, so you can start with the one vendor you already pay for. Run the dry run first. It proves the plumbing and prints the exact shape of the live output. python run.py --dry-run --models fable neon model calls hit% cost no-cache saved% break-even fable 6 99.9% $ 0.1028 $ 0.4153 75.2% 2 gap probe: 30s- 100% 120s- 100% 600s- 0% 1800s- 0% edit probe: early edit 0% hit, late edit 100% hit neon 6 99.9% $ 0.0354 $ 0.1557 77.3% 1 gap probe: 30s- 100% 120s- 100% 600s- 0% 1800s- 0% edit probe: early edit 0% hit, late edit 100% hit Read the first row carefully. Fable’s saving over six calls comes from one write at the $10 premium followed by five reads at $0.20. Neon’s saving comes from one full-price call followed by five at $0.15. These are simulated figures built on config prices, so they show the shape of the savings and nothing about vendor behavior. The live run replaces the toy cache with real usage blocks, and the same table prints with measured hit rates. Now run live against one vendor, with a small call count, to confirm the numbers look sane before spending more. python run.py --models sol --calls 4 --gaps 30 --run-id test1 A healthy live row shows a hit rate near 100% on calls two through four. If it shows 0%, jump to the troubleshooting table. The usual causes are a prefix below the vendor’s minimum size, a request that changes the prefix between calls, or a model that does not cache on the endpoint you used. Step 7: Measure Cache Lifetime With Gap Probes A cache entry does not live forever, and the lifetime changes the economics more than the discount does. A support bot that gets a question every ten seconds keeps its prefix warm without trying. A report generator that fires once an hour may pay the write cost every single time. The gap probe finds the dividing line for your account. For each gap in the list, the probe builds a distinct salted prefix and sends one call to arm it. After all prefixes are armed, it waits and probes each one at its gap, in ascending order. Arming everything up front means the total wait equals the longest gap instead of the sum of all gaps, which turns a 42-minute test into a 30-minute one. Each probe then sends a second call on its own prefix and records the hit rate. python run.py --models neon --gaps 30 120 600 1800 --run-id gap1 Read the result as a staircase. Hit rates of 100% at 30 and 120 seconds followed by 0% at 600 and 1,800 would mean the entry expired somewhere between two and ten minutes. Narrow it with a second run, for example --gaps 150 200 250 300 400 500 , and you have an effective lifetime for the exact model, endpoint and account you tested. In the dry run above, the toy cache expires entries after 300 seconds, which is why the 600-second probe misses. Two details separate a useful gap test from a misleading one. First, each probe’s first call arms its own cache entry, and a hit on the second call may refresh the entry’s lifetime on some vendors. This harness sends only one probe call per gap, so refresh behavior does not distort the staircase, but a production app that calls every few minutes may enjoy a much longer effective lifetime than the staircase suggests. Second, run the probe at a quiet hour and again at a busy one. Shared infrastructure can evict entries early under load, and a single measurement at 3 a.m. flatters you. Launch one terminal per vendor if you want the whole matrix inside an hour. The vendors are independent, so there is no reason to wait for one to finish before starting the next. Keep each terminal open until its summary lines print, because the runner writes the results file as it goes but prints the probe lines at the end of each model. OpenAI’s retention options make this probe especially valuable for Astra and Sol. A 30-minute option and a 12-hour option exist at different write prices, so the break-even is not just a call count but a call count inside a window. Run the same probe with each option set through extra body and compare. If your traffic returns to a prefix every few hours, the longer window at 2.5 times the input price may still win, because one write amortizes over many reads. Step 8: Find Where an Edit Breaks the Cache Prefix caches reuse processed input only up to the first changed token. Everything after that point is computed again and billed at the normal rate. The edit probe makes that rule concrete. It warms a prefix, then sends one request with a single word changed near the top, and one request with the last twelve characters changed. python run.py --models fable --gaps 30 --run-id edit1 In the dry run, the early edit produces a 0% hit and the late edit produces nearly 100%. Real vendors can differ at the margins, since some match in blocks and some match only at marked boundaries. The direction of the result will not differ. A change at the top of the prompt costs you the entire discount, and a change at the bottom costs almost nothing. That asymmetry drives prompt design. Put stable material first: system instructions, tool definitions, policy documents, few-shot examples. Put volatile material last: the user’s message, retrieved snippets, timestamps, request IDs. The most common way teams lose their discount is a harmless-looking line such as the current date at the top of the system prompt. Midnight rolls over, every prefix is new, and the hit rate for the first request of each day drops to zero for every user at once. Tool definitions deserve the same suspicion. Many APIs serialize tools ahead of the conversation, so reordering a tools list, adding a parameter description or toggling a tool per user can invalidate the prefix before a single message token is read. If your product enables different tools for different plans, group users by tool set so each group shares a prefix instead of fragmenting the cache across hundreds of variants. The same logic applies to long conversations. An agent session appends to its history each turn, which is cache-friendly because each new request extends the previous one. Summarizing or trimming old turns rewrites the middle of the history and breaks the match from that point on. Compaction still pays when the history grows too big, but it should happen rarely and on purpose. For a look at how that plays out in coding sessions, the Gemini CLI and Claude Code token comparison https://shattered.io/gemini-cli-vs-claude-code-neon-3-15-vs-fable-8-40-tokens/ shows how the two tools spend input over a long session. Steps 9 and 10: Prefix-Size Sweep and Cold-Start Burst Step 9: Sweep prefix sizes to find the minimum cacheable length Vendors set a minimum prefix length below which caching does not happen at all. The number varies by vendor and sometimes by model, and it changes when vendors revise their docs, so measure it instead of memorizing it. The sweep sends the same prefix twice at several sizes and reports the hit rate of the second call. python run.py --models astra --sizes 200 600 1200 2400 --gaps 30 --run-id size1 bash astra 6 99.9% $ 0.0943 $ 0.4151 77.3% 1 size sweep: 200w/317t- 0% 600w/862t- 0% 1200w/1696t- 100% 2400w/3368t- 100% Each entry reads words, estimated tokens and second-call hit rate. In the dry run the toy minimum is 1,024 tokens, so a prompt below that size misses and a larger one hits. A live sweep gives you the real threshold bracket for your vendor. Refine it with sizes between the last miss and the first hit. If your production prompt sits near the threshold, padding it with useful stable context, such as extra examples, can switch caching on and lower the cost per request even though the prompt got longer. Step 10: Fire a cold-start burst and watch the misses The last probe models a common production event. A deploy, a cron job or a viral moment sends many requests at once, all with the same prefix, before any of them has finished. A cache entry becomes available only after the first response begins, so simultaneous cold requests all miss and all pay full price. Some vendors charge the write premium on every one of them. python run.py --models dsflash --burst 4 --gaps 30 --run-id burst1 bash dsflash 6 99.9% $ 0.0031 $ 0.0155 80.1% 1 burst x4: 0 hits inside the burst, 100% on the next call The dry run shows the pattern. Four parallel calls produce zero hits, and the call after the burst hits the entry the burst created. The production fix is cheap: send one request first, wait for it to return, then release the rest. Teams call this warming the cache, and it can turn an expensive first minute into a normal one. For batch jobs, process one item, then fan out. If your architecture sends traffic through a router that picks a model per request, keep one more thing in mind. Switching vendors between calls throws away the cache you just built, since each vendor holds its own. A router that sticks a session to one provider will beat a router that chases the cheapest price on every request. The Claude and GPT router build https://shattered.io/build-llm-router-claude-gpt-2026/ is a good place to add that affinity rule. Steps 11 and 12: Lock the Math With Tests, Then Run the Full Matrix Step 11: Write unit tests for the cost and cache logic Money code deserves tests. Five short checks cover the pieces that can silently go wrong: the dollar math, the baseline, the break-even rounding, the hit-rate definition and the toy cache’s expiry and prefix matching. The tests use round numbers so you can verify the expected values by hand. python from adapters import FakeCache, Usage from clock import VirtualClock from costs import baseline, breakeven calls, cost, hit rate from prefix import build prefix P = {"input": 8.0, "cached": 0.4, "write": 8.0, "output": 40.0} W = {"input": 8.0, "cached": 0.2, "write": 10.0, "output": 40.0} def test cost matches hand math : u = Usage fresh in=1 000 000, cached in=1 000 000, written in=0, out=100 000, latency s=1 assert round cost u, P , 4 == 8.0 + 0.4 + 4.0 def test baseline ignores cache discount : u = Usage 0, 1 000 000, 0, 0, 1 assert baseline u, P == 8.0 and cost u, P == 0.4 def test breakeven with write premium : assert breakeven calls P == 1 assert breakeven calls W == 2 def test hit rate counts written tokens as input : assert hit rate Usage 0, 50, 50, 0, 1 == 0.5 def test fake cache expires and prefix matches : clock = VirtualClock cache = FakeCache {"style": "automatic"}, clock, ttl s=300 text = build prefix 3000, "t" cache {"style": "automatic"}, text, "q" clock.sleep 10 assert hit rate cache {"style": "automatic"}, text, "q" 0.99 clock.sleep 1000 assert hit rate cache {"style": "automatic"}, text, "q" == 0.0 bash $ python -m pytest -q ..... 100% 5 passed in 0.22s Run the tests whenever a rate card changes. A price edit in models.json cannot break them, but a refactor of the cost module can, and a wrong cost formula looks just like a real result. Step 12: Run the full matrix live and archive the evidence With the plumbing verified, run the whole thing. Use one terminal per vendor, give each run a dated ID, and keep the results file. The dated ID doubles as the salt, so reruns never reuse a warm prefix. python run.py --models fable --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out fable-20261201.jsonl python run.py --models astra sol --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out openai-20261201.jsonl python run.py --models neon --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out gemini-20261201.jsonl python run.py --models dsflash --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out deepseek-20261201.jsonl Each results file holds one JSON line per call with the four normalized counters and the latency. That is enough to re-price the run when a vendor changes its rates, to chart hit rates over time, and to prove to a finance team where the savings came from. Commit the files next to the config so the evidence travels with the numbers. The complete project now looks like this: cachetest/ models.json pinned model IDs and prices prefix.py salted, deterministic prefix builder clock.py real and virtual clocks adapters.py four live adapters plus the toy cache costs.py cost, baseline, hit rate, break-even run.py warm run plus gap, edit, size and burst probes test costs.py five unit tests Reading the Results: When Prompt Caching Pays and When It Does Not The harness gives you four numbers per model: hit rate, effective lifetime, minimum size and burst behavior. Turn them into a decision with the savings curve. The dry run below holds the prefix at the default size and varies only the number of calls that share it, using the config prices for Fable 5.2 and Gemini 4 Neon. | Calls sharing one prefix | Fable 5.2 saving reported $10 write price | Gemini 4 Neon saving no write premium | |---|---|---| | 1 | -24.4% | 0.0% | | 2 | Not listed | Not listed | | 3 | Not listed | 61.8% | | 6 | Not listed | Not listed | The top row is the lesson. A single call with a write premium loses money, because you paid extra to store a prefix you never read. The second row already wins on both lines. As the calls pile up, both columns move toward the size of the read discount, which Google puts at 95% for Gemini 4 Neon cached input. The one full-price or premium call, the question tokens and the output all pull the result back from that ceiling. The curve flattens quickly, so the first three calls decide most of the outcome. Use these rules to turn your measurements into policy: - Hit rate below 80% on calls two onward: the prefix is changing between calls or the entry is expiring. Fix prompt order before you tune anything else. - Lifetime shorter than your median gap between calls: caching will rarely pay on that path. Consider a longer retention option, a keep-alive request, or batching requests closer together. - Prefix near the minimum size: pad with stable content or accept no caching. Do not pad with volatile content. - Zero hits inside bursts: add a warm-up request before fan-out. - Break-even above your calls per prefix lifetime: skip explicit caching on that path, because the write premium will eat the savings. Per-task cost differs from per-token cost, and that matters when you pick a model. A cheaper model with a high hit rate can beat a pricier one on long-context work by a wide margin, while a pricier model that finishes in fewer steps can still win on agent tasks. The Astra against Fable 5.2 task-cost comparison https://shattered.io/gpt-6-2-astra-vs-claude-fable-5-2-62-vs-65-index-4-vs-26-54-task-cost/ frames that tradeoff, and your cache measurements fill in the input side of it. Common Pitfalls That Skew Prompt Caching Results Most bad cache measurements come from the test, not the vendor. These are the failure modes that produce confident, wrong numbers. 1. Treating Anthropic’s input tokens as the prompt size. On that API the field excludes cached and written tokens, so a perfect cache hit shows a tiny input count. Add all three counters before computing a hit rate, which is what the adapter and hit rate do. 2. Reusing a prefix across runs. If yesterday’s prefix is still warm, your “cold” first call is a hit and your break-even looks better than it is. The salt on the first line prevents this, but only if you change the run ID every time. 3. Putting a timestamp or request ID in the prefix. A changing token near the top silently gives you a 0% hit rate. Search your prompt builders for date and ID insertions before blaming the vendor. 4. Ignoring the write premium. Comparing cached reads to standard input flatters explicit-cache APIs. Compare total cost over the realistic number of calls per prefix lifetime, which is what the savings curve does. 5. Testing below the minimum size. A 300-token prompt will never cache, and the 0% result says nothing about your much longer production prompt. Run the size sweep before drawing conclusions. 6. Mixing peak and off-peak prices. DeepSeek halves its rates off-peak. Pricing one run at peak and another at off-peak makes a vendor look cheaper or dearer than it is. Fix the price tier in the config and record it in the run ID. 7. Forgetting reasoning tokens. If a model reports reasoning or thinking tokens in a separate field, they bill as output but may not appear in the completion count the adapter reads. Add them in the adapter if your vendor splits them out. 8. Firing parallel cold requests. Twenty workers starting at once all pay full price. Warm the cache with one call first. A quieter pitfall sits in how you read percentages. A 99% hit rate on calls two to six sounds perfect, but if your real traffic is one call per prefix per hour and the lifetime is ten minutes, your production hit rate is zero. The warm-call experiment measures the best case. The gap probe measures the realistic one. Report both. Troubleshooting: 10 Fixes for Prompt Caching Tests When a run misbehaves, find the symptom in the table and work through the fix in order. | Symptom | Likely cause | Fix | |---|---|---| | Hit rate is 0% on every call | Prefix is below the vendor’s minimum size | Run the size sweep, then raise --words above the first hit size | | Hit rate is 0% only for Fable 5.2 | The cache control marker is missing or on the wrong block | Confirm the marker sits on the last stable block, then print the raw usage block and look for the cache-creation counter | | Fable shows tiny fresh in and large written in on call one | Expected behavior, since the API reports writes separately | No fix needed, but price written in at the write rate, which cost already does | | First call is cheap, as if cached | A previous run left the same prefix warm | Change --run-id so the salt changes | | Hit rate drops after a few calls | Entry expired or was evicted under load | Shorten --gap , rerun the gap probe, and test at a different hour | | HTTP 400 on the OpenAI adapter | The model expects a different token-limit field | Set max tokens field in the config to the field the API reference names | | KeyError on a usage field | Your account returns a different field name | Print the raw usage block, then edit the matching adapter | | Gemini says the model was not found | The placeholder ID is wrong | Copy the exact ID from the Gemini model list in Google AI Studio | | Costs look 2x too high on DeepSeek | Config holds peak prices while you ran off-peak, or the reverse | Set the right tier in models.json and re-price from the results file | | Burst shows hits inside the burst | Requests were not truly parallel, or the vendor shares entries across requests in flight | Log request start times and widen --burst to confirm | Rate limits deserve their own mention. A burst probe with a high width on a new account can trip a per-minute cap and return errors that look like cache failures. Keep the width at four to eight, and check the status code before you read anything into the counters. If a vendor’s behavior changes between runs, suspect a model update before you suspect your code. DeepSeek has refreshed V4.1-Flash at least once since launch, so each result file should travel with its exact model ID and run date. The config pins the ID, and the dated run ID from Step 12 tells you which side of a vendor update each result file sits on. Advanced Tips for Production Prompt Caching - Cache at two layers. Prompt caching discounts input tokens, but a gateway-level response cache can skip the model call entirely for repeated questions. The two stack well, and the Cloudflare AI Gateway setup https://shattered.io/cloudflare-ai-gateway-setup-2026/ shows the gateway half. - Schedule flexible jobs off-peak. DeepSeek’s off-peak rates are half the peak rates, so overnight batch work on a cached prefix costs a fraction of the same work at lunchtime. - Check whether batch and cache discounts combine. Both OpenAI’s and Anthropic’s pricing pages list a 50% discount for batch processing. Whether that stacks with cached-input pricing on your account is a measurement question. Run a small batch with a shared prefix and read the invoice line. - Order every prompt as stable, then semi-stable, then volatile. System text, tools and policies go first. Per-user profile or retrieved documents go next. The live question goes last. Enforce the order in a prompt-builder function and add a unit test that fails if a timestamp lands above the stable block. - Track hit rate as a service metric. Alert when the rolling hit rate falls below your measured baseline. A prompt edit that nukes the cache shows up within minutes instead of at the end of the billing cycle. - Keep sessions on one vendor. Switching providers mid-session discards the warm cache on both sides, so routers should favor stickiness over per-request price shopping. - Use keep-alive sparingly. A cheap ping to refresh an entry costs a cached read and a few output tokens. It pays when the next real request is likely to arrive just after expiry, and it wastes money when traffic is truly idle. - Rerun the matrix monthly. Vendors changed prices and retention options over the past quarter. A scheduled job that reruns the warm-call and gap probes against a small prefix, then diffs the results file, catches changes before your invoice does. When the numbers are in, share them with the people who approve the spend, and keep exploring the rest of the AI and machine learning tutorials https://shattered.io/category/ai-machine-learning/ for the evaluation and cost-control work that sits around this harness. Frequently Asked Questions About Prompt Caching What is prompt caching? Prompt caching lets an API reuse the processing it already did for an unchanged beginning of your prompt. The vendor bills those reused tokens at a lower cached-input rate, and the reply usually starts sooner. Only the part that matches from the first token forward counts, so the stable material must come first. How many calls does a prefix need before caching pays? It depends on the write premium. Use W – R divided by P – R , rounded up, where W is the write price, R is the cached-read price and P is the standard input price. With no write premium the answer is one call. With the reported $10 write price for Claude Fable 5.2, it is two. The harness prints the figure for every model in its config. Does caching change the model’s answers? Caching reuses processed input, so it should not change what the model understands. Sampling still makes outputs vary from call to call, with or without a cache. If you need to confirm identical behavior for your prompts, compare a batch of cached and uncached replies at temperature zero. Why do I see zero cached tokens on a long prompt? Three causes cover almost every case. The prefix may sit below the vendor’s minimum size, something near the top of the prompt may change between calls, or the cache entry may have expired before your second call. The size sweep, the edit probe and the gap probe test those three in turn. Is DeepSeek’s cache cheaper than the others? In list terms, yes. DeepSeek V4.1-Flash lists cache hits at $0.003 per million tokens off-peak and $0.006 at peak, against $0.10 to $0.40 per million for GPT-6.2 Sol and Astra and $0.15 for Gemini 4 Neon. Cheaper does not mean better for your task, so run your own quality checks beside the cost test. Do the dry-run numbers predict my savings? No. The dry run uses a toy cache with made-up lifetime and size limits, so it validates the code and demonstrates the shape of the savings curve. Your live results replace those numbers, and the live results are the only ones worth quoting. Should I turn on cache writes for rarely used prefixes? Not unless the measured break-even fits inside the measured lifetime. If a prefix gets one call per hour and the entry lives ten minutes, an explicit write only adds a premium to every call. Leave it off, or batch the requests so they land inside the window.