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, 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 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.
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 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, and for DeepSeek’s own announcement of the V4.1-Flash price cut, read the V4.1-Flash release notice.
Prerequisites and Versions for the Prompt Caching Test #
The build needs little. Anthropic-only readers can start with the single-vendor Claude walkthrough 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_KEYandDEEPSEEK_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-flashGemini model pages on Google DeepMind 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.
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.
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.
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"]
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 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.
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.
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 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 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.
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 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.
- Treating Anthropic’s
input_tokensas 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 andhit_ratedo. - 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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 largewritten_in on call one |
Expected behavior, since the API reports writes separately | No fix needed, but price written_in at the write rate, whichcost 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 theCloudflare AI Gateway setup 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 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.