{"slug": "prompt-caching-cost-test-5-models-12-steps-70-min", "title": "Prompt Caching Cost Test: 5 Models, 12 Steps, 70 Min", "summary": "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.", "body_md": "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.\n\nA 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.\n\nThe 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.\n\nDon't miss new tech stories on Google\n\nAdd Shattered once in the Google app and our stories show up in your news suggestions.\n\n[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)\n\n## Prompt Caching Prices: The Cached-Input Gap Across Five Models\n\nStart 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.\n\n| Model | Standard input | Cached input | Cached as share of input | \n|---|---|---|---|\n| GPT-6.2 Astra | $8 | $0.40 | 5% | \n| GPT-6.2 Sol | $2 | $0.10 | 5% | \n| Gemini 4 Neon | $3 | $0.15 | 5% | \n| DeepSeek V4.1-Flash, peak hours | $0.30 | $0.006 | 2% | \n| DeepSeek V4.1-Flash, off-peak | $0.15 | $0.003 | 2% | \n\nClaude 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.\n\nOpenAI 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.\n\nThe 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.\n\nPrice 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.\n\nDeepSeek 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).\n\n## Prerequisites and Versions for the Prompt Caching Test\n\nThe 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.\n\n- **Python** , a current release. The code was written and run on a recent release.\n- **requests** for HTTP. Any recent release works.\n- **pytest** for the unit tests in Step 11. Any recent release works.\n- **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.\n- **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.\n- **Linux, macOS or WSL** with a terminal that can stay open for about 30 minutes during the cache-lifetime probe.\n- **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.\n\nPin 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.\n\nRetired 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.\n\nOne 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.\n\n## How Each API Reports Cached Tokens\n\nThe 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.\n\n| Vendor path | How a prefix gets cached | Usage fields the adapter reads | Trap to avoid | \n|---|---|---|---|\n| 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 | \n| 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 | \n| 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 | \n| 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 | \n\nField 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.\n\nThe 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.\n\nA 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.\n\n## Steps 1 to 3: Project Setup, Pinned Prices and a Salted Prefix\n\n### Step 1: Create the project and install two packages\n\nMake 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.\n\n```\nmkdir cachetest && cd cachetest\npython3 -m venv .venv && source .venv/bin/activate\npip install requests pytest\n\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\nexport OPENAI_API_KEY=\"sk-...\"\nexport GEMINI_API_KEY=\"...\"\nexport DEEPSEEK_API_KEY=\"sk-...\"\n```\n\n### Step 2: Pin model IDs and prices in one file\n\nPrices 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.\n\n```\n{\n  \"fable\": {\n    \"provider\": \"anthropic\",\n    \"model\": \"claude-fable-5-2\",\n    \"style\": \"explicit\",\n    \"input\": 8.00, \"cached\": 0.20, \"write\": 10.00, \"output\": 40.00\n  },\n  \"astra\": {\n    \"provider\": \"openai\",\n    \"model\": \"gpt-6.2-astra\",\n    \"style\": \"automatic\",\n    \"max_tokens_field\": \"max_completion_tokens\",\n    \"extra_body\": {},\n    \"input\": 8.00, \"cached\": 0.40, \"write\": 8.00, \"output\": 40.00\n  },\n  \"sol\": {\n    \"provider\": \"openai\",\n    \"model\": \"gpt-6.2-sol\",\n    \"style\": \"automatic\",\n    \"max_tokens_field\": \"max_completion_tokens\",\n    \"extra_body\": {},\n    \"input\": 2.00, \"cached\": 0.10, \"write\": 2.00, \"output\": 10.00\n  },\n  \"neon\": {\n    \"provider\": \"gemini\",\n    \"model\": \"gemini-4-neon\",\n    \"style\": \"automatic\",\n    \"input\": 3.00, \"cached\": 0.15, \"write\": 3.00, \"output\": 15.00\n  },\n  \"dsflash\": {\n    \"provider\": \"deepseek\",\n    \"model\": \"deepseek-flash\",\n    \"style\": \"automatic\",\n    \"input\": 0.30, \"cached\": 0.006, \"write\": 0.30, \"output\": 1.20\n  }\n}\n```\n\nTwo 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`.\n\n### Step 3: Build a deterministic prefix with a salt at the front\n\nA 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.\n\n``` python\nimport hashlib\nimport random\n\nTOPICS = [\"refund window\", \"warranty claim\", \"shipping delay\", \"account recovery\",\n          \"invoice dispute\", \"data export\", \"seat transfer\", \"api quota\",\n          \"sso setup\", \"audit log\", \"retention rule\", \"escalation path\"]\n\ndef build_prefix(words: int, salt: str) -> str:\n    \"\"\"Deterministic support-policy text. The salt goes FIRST so each run starts cold.\"\"\"\n    rng = random.Random(salt)\n    lines = [f\"RUN-ID {salt}. You are a support assistant. Answer only from the policy below.\"]\n    count = len(lines[0].split())\n    n = 1\n    while count < words:\n        topic = TOPICS[n % len(TOPICS)]\n        a, b, c = rng.randint(2, 90), rng.randint(2, 30), rng.randint(100, 999)\n        line = (f\"Policy {n}: for a {topic}, the agent checks case {c}, waits {a} days, \"\n                f\"then escalates after {b} contacts and records the outcome in the ledger.\")\n        lines.append(line)\n        count += len(line.split())\n        n += 1\n    return \"\\n\".join(lines)\n\ndef prefix_hash(text: str) -> str:\n    return hashlib.sha256(text.encode()).hexdigest()[:12]\n```\n\nA 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.\n\n``` php\nimport time\n\nclass RealClock:\n    def now(self) -> float:\n        return time.monotonic()\n\n    def sleep(self, seconds: float) -> None:\n        time.sleep(seconds)\n\nclass VirtualClock:\n    \"\"\"Dry runs skip the waiting but still advance time for the fake cache.\"\"\"\n    def __init__(self) -> None:\n        self.t = 0.0\n\n    def now(self) -> float:\n        return self.t\n\n    def sleep(self, seconds: float) -> None:\n        self.t += seconds\n```\n\nThe 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.\n\n## Steps 4 and 5: Provider Adapters and the Cost Math\n\n### Step 4: Write one adapter per API and normalize the usage block\n\nEach 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.\n\n``` python\nimport os\nimport time\nfrom dataclasses import dataclass\n\nimport requests\n\n@dataclass\nclass Usage:\n    fresh_in: int      # input tokens billed at the normal rate\n    cached_in: int     # input tokens served from cache\n    written_in: int    # input tokens written to cache (explicit-style APIs)\n    out: int\n    latency_s: float\n\ndef _post(url, headers, body):\n    t0 = time.perf_counter()\n    r = requests.post(url, headers=headers, json=body, timeout=180)\n    dt = time.perf_counter() - t0\n    if r.status_code >= 400:\n        raise RuntimeError(f\"HTTP {r.status_code} from {url}: {r.text[:300]}\")\n    return r.json(), dt\n\ndef call_anthropic(cfg, prefix, question):\n    body = {\n        \"model\": cfg[\"model\"],\n        \"max_tokens\": 64,\n        \"system\": [{\"type\": \"text\", \"text\": prefix,\n                    \"cache_control\": {\"type\": \"ephemeral\"}}],\n        \"messages\": [{\"role\": \"user\", \"content\": question}],\n    }\n    headers = {\"x-api-key\": os.environ[\"ANTHROPIC_API_KEY\"],\n               \"anthropic-version\": \"2023-06-01\"}\n    data, dt = _post(\"https://api.anthropic.com/v1/messages\", headers, body)\n    u = data[\"usage\"]\n    # input_tokens EXCLUDES the cached and the written portions on this API\n    return Usage(u[\"input_tokens\"], u.get(\"cache_read_input_tokens\", 0),\n                 u.get(\"cache_creation_input_tokens\", 0), u[\"output_tokens\"], dt)\n\ndef _chat_body(cfg, prefix, question):\n    body = {\"model\": cfg[\"model\"],\n            \"messages\": [{\"role\": \"system\", \"content\": prefix},\n                         {\"role\": \"user\", \"content\": question}]}\n    body[cfg.get(\"max_tokens_field\", \"max_tokens\")] = 64\n    body.update(cfg.get(\"extra_body\", {}))\n    return body\n\ndef call_openai(cfg, prefix, question):\n    headers = {\"Authorization\": \"Bearer \" + os.environ[\"OPENAI_API_KEY\"]}\n    data, dt = _post(\"https://api.openai.com/v1/chat/completions\",\n                     headers, _chat_body(cfg, prefix, question))\n    u = data[\"usage\"]\n    cached = (u.get(\"prompt_tokens_details\") or {}).get(\"cached_tokens\", 0)\n    return Usage(u[\"prompt_tokens\"] - cached, cached, 0, u[\"completion_tokens\"], dt)\n\ndef call_deepseek(cfg, prefix, question):\n    headers = {\"Authorization\": \"Bearer \" + os.environ[\"DEEPSEEK_API_KEY\"]}\n    data, dt = _post(\"https://api.deepseek.com/chat/completions\",\n                     headers, _chat_body(cfg, prefix, question))\n    u = data[\"usage\"]\n    hit = u.get(\"prompt_cache_hit_tokens\", 0)\n    miss = u.get(\"prompt_cache_miss_tokens\", u[\"prompt_tokens\"] - hit)\n    return Usage(miss, hit, 0, u[\"completion_tokens\"], dt)\n\ndef call_gemini(cfg, prefix, question):\n    url = (\"https://generativelanguage.googleapis.com/v1beta/models/\"\n           f\"{cfg['model']}:generateContent\")\n    body = {\"systemInstruction\": {\"parts\": [{\"text\": prefix}]},\n            \"contents\": [{\"role\": \"user\", \"parts\": [{\"text\": question}]}],\n            \"generationConfig\": {\"maxOutputTokens\": 64}}\n    data, dt = _post(url, {\"x-goog-api-key\": os.environ[\"GEMINI_API_KEY\"]}, body)\n    u = data[\"usageMetadata\"]\n    cached = u.get(\"cachedContentTokenCount\", 0)\n    return Usage(u[\"promptTokenCount\"] - cached, cached, 0,\n                 u.get(\"candidatesTokenCount\", 0), dt)\n\nLIVE = {\"anthropic\": call_anthropic, \"openai\": call_openai,\n        \"deepseek\": call_deepseek, \"gemini\": call_gemini}\nKEYS = {\"anthropic\": \"ANTHROPIC_API_KEY\", \"openai\": \"OPENAI_API_KEY\",\n        \"deepseek\": \"DEEPSEEK_API_KEY\", \"gemini\": \"GEMINI_API_KEY\"}\n\nclass FakeCache:\n    \"\"\"Toy prefix cache for dry runs. TTL and minimum size are made-up knobs, not vendor facts.\"\"\"\n    def __init__(self, cfg, clock, ttl_s=300, min_tokens=1024, ready_s=1.0):\n        self.cfg, self.clock = cfg, clock\n        self.ttl_s, self.min_tokens, self.ready_s = ttl_s, min_tokens, ready_s\n        self.entries = []  # (text, last_seen, created)\n\n    def _shared_chars(self, prefix, now):\n        best = 0\n        for text, seen, created in self.entries:\n            if now - seen > self.ttl_s or now - created < self.ready_s:\n                continue\n            n = 0\n            for x, y in zip(prefix, text):\n                if x != y:\n                    break\n                n += 1\n            best = max(best, n)\n        return best\n\n    def __call__(self, cfg, prefix, question):\n        now = self.clock.now()\n        ptoks = len(prefix) // 4\n        qtoks = max(1, len(question) // 4)\n        if ptoks < self.min_tokens:\n            return Usage(ptoks + qtoks, 0, 0, 40, 1.1)\n        cached = min(ptoks, self._shared_chars(prefix, now) // 4)\n        if cached < self.min_tokens:\n            cached = 0\n        self.entries = [e for e in self.entries if now - e[1] <= self.ttl_s]\n        self.entries.append((prefix, now, now))\n        rest = ptoks - cached\n        if cfg[\"style\"] == \"explicit\":\n            return Usage(qtoks, cached, rest, 40, 0.4 if cached else 1.1)\n        return Usage(rest + qtoks, cached, 0, 40, 0.4 if cached else 1.1)\n\ndef get_caller(cfg, clock, dry_run):\n    if dry_run:\n        return FakeCache(cfg, clock)\n    return LIVE[cfg[\"provider\"]]\n```\n\nThe 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.\n\nBefore 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.\n\nOnce 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.\n\n### Step 5: Price every call and compute the break-even\n\nThe 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.\n\n``` python\nimport math\n\ndef cost(u, p):\n    return (u.fresh_in * p[\"input\"] + u.cached_in * p[\"cached\"]\n            + u.written_in * p[\"write\"] + u.out * p[\"output\"]) / 1e6\n\ndef baseline(u, p):\n    total_in = u.fresh_in + u.cached_in + u.written_in\n    return (total_in * p[\"input\"] + u.out * p[\"output\"]) / 1e6\n\ndef hit_rate(u):\n    total_in = u.fresh_in + u.cached_in + u.written_in\n    return u.cached_in / total_in if total_in else 0.0\n\ndef breakeven_calls(p):\n    \"\"\"Smallest call count n where write + (n-1)*cached <= n*input, per prefix token.\"\"\"\n    if p[\"write\"] <= p[\"input\"]:\n        return 1\n    return math.ceil((p[\"write\"] - p[\"cached\"]) / (p[\"input\"] - p[\"cached\"]))\n```\n\nNote 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.\n\n## Step 6: Run the Warm-Call Experiment\n\nThe 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.\n\n``` python\nimport argparse\nimport json\nimport os\nimport sys\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom adapters import KEYS, get_caller\nfrom clock import RealClock, VirtualClock\nfrom costs import baseline, breakeven_calls, cost, hit_rate\nfrom prefix import build_prefix\n\nQUESTIONS = [\"What is the refund window?\", \"Who handles invoice disputes?\",\n             \"How long before escalation?\", \"Where are outcomes recorded?\",\n             \"What happens after a shipping delay?\", \"How do I export data?\",\n             \"Can a seat be transferred?\", \"What is the audit log for?\"]\n\ndef warm_run(name, cfg, caller, clock, words, calls, gap, run_id):\n    prefix = build_prefix(words, f\"{run_id}-{name}\")\n    rows = []\n    for i in range(calls):\n        u = caller(cfg, prefix, QUESTIONS[i % len(QUESTIONS)])\n        rows.append(u)\n        clock.sleep(gap)\n    return rows\n\ndef gap_probe(name, cfg, caller, clock, words, gaps, run_id):\n    prefixes = {}\n    for g in gaps:\n        prefixes[g] = build_prefix(words, f\"{run_id}-{name}-gap{g}\")\n        caller(cfg, prefixes[g], QUESTIONS[0])\n    waited, out = 0.0, []\n    for g in sorted(gaps):\n        clock.sleep(g - waited)\n        waited = g\n        out.append((g, hit_rate(caller(cfg, prefixes[g], QUESTIONS[1]))))\n    return out\n\ndef edit_probe(name, cfg, caller, clock, words, run_id):\n    base = build_prefix(words, f\"{run_id}-{name}-edit\")\n    caller(cfg, base, QUESTIONS[0])\n    clock.sleep(2)\n    early = base.replace(\"Policy 2:\", \"Policy two:\", 1)\n    late = base[:-12] + \"CHANGED-END.\"\n    return hit_rate(caller(cfg, early, QUESTIONS[1])), hit_rate(caller(cfg, late, QUESTIONS[2]))\n\ndef size_sweep(name, cfg, caller, clock, sizes, run_id):\n    out = []\n    for w in sizes:\n        prefix = build_prefix(w, f\"{run_id}-{name}-size{w}\")\n        caller(cfg, prefix, QUESTIONS[0])\n        clock.sleep(2)\n        u = caller(cfg, prefix, QUESTIONS[1])\n        out.append((w, u.fresh_in + u.cached_in + u.written_in, hit_rate(u)))\n    return out\n\ndef burst(name, cfg, caller, clock, words, width, run_id):\n    prefix = build_prefix(words, f\"{run_id}-{name}-burst\")\n    with ThreadPoolExecutor(width) as pool:\n        first = list(pool.map(lambda q: caller(cfg, prefix, q), QUESTIONS[:width]))\n    clock.sleep(2)\n    after = caller(cfg, prefix, QUESTIONS[0])\n    return sum(1 for u in first if u.cached_in > 0), hit_rate(after)\n\ndef main():\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--models\", nargs=\"+\", default=[\"fable\", \"astra\", \"sol\", \"neon\", \"dsflash\"])\n    ap.add_argument(\"--words\", type=int, default=6000)\n    ap.add_argument(\"--calls\", type=int, default=6)\n    ap.add_argument(\"--gap\", type=float, default=2)\n    ap.add_argument(\"--gaps\", type=float, nargs=\"*\", default=[30, 120, 600, 1800])\n    ap.add_argument(\"--sizes\", type=int, nargs=\"*\", default=[])\n    ap.add_argument(\"--burst\", type=int, default=0)\n    ap.add_argument(\"--run-id\", default=\"r1\")\n    ap.add_argument(\"--dry-run\", action=\"store_true\")\n    ap.add_argument(\"--out\", default=\"results.jsonl\")\n    a = ap.parse_args()\n\n    cfgs = json.load(open(\"models.json\"))\n    clock = VirtualClock() if a.dry_run else RealClock()\n    print(f\"{'model':8} {'calls':>5} {'hit%':>6} {'cost':>10} {'no-cache':>10} {'saved%':>7} {'break-even':>10}\")\n    with open(a.out, \"w\") as sink:\n        for name in a.models:\n            cfg = cfgs[name]\n            if not a.dry_run and KEYS[cfg[\"provider\"]] not in os.environ:\n                print(f\"{name:8} skipped: set {KEYS[cfg['provider']]}\", file=sys.stderr)\n                continue\n            caller = get_caller(cfg, clock, a.dry_run)\n            rows = warm_run(name, cfg, caller, clock, a.words, a.calls, a.gap, a.run_id)\n            spent = sum(cost(u, cfg) for u in rows)\n            plain = sum(baseline(u, cfg) for u in rows)\n            later = rows[1:]\n            hr = sum(hit_rate(u) for u in later) / max(1, len(later))\n            print(f\"{name:8} {len(rows):>5} {hr*100:>5.1f}% ${spent:>9.4f} ${plain:>9.4f} \"\n                  f\"{(1-spent/plain)*100:>6.1f}% {breakeven_calls(cfg):>10}\")\n            for i, u in enumerate(rows):\n                sink.write(json.dumps({\"model\": name, \"call\": i + 1, **u.__dict__}) + \"\\n\")\n            probe = gap_probe(name, cfg, caller, clock, a.words, a.gaps, a.run_id)\n            print(\"         gap probe: \" + \"  \".join(f\"{int(g)}s->{h*100:.0f}%\" for g, h in probe))\n            early, late = edit_probe(name, cfg, caller, clock, a.words, a.run_id)\n            print(f\"         edit probe: early edit {early*100:.0f}% hit, late edit {late*100:.0f}% hit\")\n            if a.sizes:\n                sweep = size_sweep(name, cfg, caller, clock, a.sizes, a.run_id)\n                print(\"         size sweep: \" + \"  \".join(f\"{w}w/{t}t->{h*100:.0f}%\" for w, t, h in sweep))\n            if a.burst:\n                hits, after = burst(name, cfg, caller, clock, a.words, a.burst, a.run_id)\n                print(f\"         burst x{a.burst}: {hits} hits inside the burst, {after*100:.0f}% on the next call\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nThe 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.\n\nRun the dry run first. It proves the plumbing and prints the exact shape of the live output.\n\n```\npython run.py --dry-run --models fable neon\nmodel    calls   hit%       cost   no-cache  saved% break-even\nfable        6  99.9% $   0.1028 $   0.4153   75.2%          2\n         gap probe: 30s->100%  120s->100%  600s->0%  1800s->0%\n         edit probe: early edit 0% hit, late edit 100% hit\nneon         6  99.9% $   0.0354 $   0.1557   77.3%          1\n         gap probe: 30s->100%  120s->100%  600s->0%  1800s->0%\n         edit probe: early edit 0% hit, late edit 100% hit\n```\n\nRead 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.\n\nNow run live against one vendor, with a small call count, to confirm the numbers look sane before spending more.\n\n```\npython run.py --models sol --calls 4 --gaps 30 --run-id test1\n```\n\nA 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.\n\n## Step 7: Measure Cache Lifetime With Gap Probes\n\nA 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.\n\nFor 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.\n\n```\npython run.py --models neon --gaps 30 120 600 1800 --run-id gap1\n```\n\nRead 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.\n\nTwo 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.\n\nLaunch 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.\n\nOpenAI’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.\n\n## Step 8: Find Where an Edit Breaks the Cache\n\nPrefix 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.\n\n```\npython run.py --models fable --gaps 30 --run-id edit1\n```\n\nIn 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.\n\nThat 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.\n\nTool 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.\n\nThe 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.\n\n## Steps 9 and 10: Prefix-Size Sweep and Cold-Start Burst\n\n### Step 9: Sweep prefix sizes to find the minimum cacheable length\n\nVendors 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.\n\n```\npython run.py --models astra --sizes 200 600 1200 2400 --gaps 30 --run-id size1\nbash\nastra        6  99.9% $   0.0943 $   0.4151   77.3%          1\n         size sweep: 200w/317t->0%  600w/862t->0%  1200w/1696t->100%  2400w/3368t->100%\n```\n\nEach 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.\n\n### Step 10: Fire a cold-start burst and watch the misses\n\nThe 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.\n\n```\npython run.py --models dsflash --burst 4 --gaps 30 --run-id burst1\nbash\ndsflash      6  99.9% $   0.0031 $   0.0155   80.1%          1\n         burst x4: 0 hits inside the burst, 100% on the next call\n```\n\nThe 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.\n\nIf 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.\n\n## Steps 11 and 12: Lock the Math With Tests, Then Run the Full Matrix\n\n### Step 11: Write unit tests for the cost and cache logic\n\nMoney 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.\n\n``` python\nfrom adapters import FakeCache, Usage\nfrom clock import VirtualClock\nfrom costs import baseline, breakeven_calls, cost, hit_rate\nfrom prefix import build_prefix\n\nP = {\"input\": 8.0, \"cached\": 0.4, \"write\": 8.0, \"output\": 40.0}\nW = {\"input\": 8.0, \"cached\": 0.2, \"write\": 10.0, \"output\": 40.0}\n\ndef test_cost_matches_hand_math():\n    u = Usage(fresh_in=1_000_000, cached_in=1_000_000, written_in=0, out=100_000, latency_s=1)\n    assert round(cost(u, P), 4) == 8.0 + 0.4 + 4.0\n\ndef test_baseline_ignores_cache_discount():\n    u = Usage(0, 1_000_000, 0, 0, 1)\n    assert baseline(u, P) == 8.0 and cost(u, P) == 0.4\n\ndef test_breakeven_with_write_premium():\n    assert breakeven_calls(P) == 1\n    assert breakeven_calls(W) == 2\n\ndef test_hit_rate_counts_written_tokens_as_input():\n    assert hit_rate(Usage(0, 50, 50, 0, 1)) == 0.5\n\ndef test_fake_cache_expires_and_prefix_matches():\n    clock = VirtualClock()\n    cache = FakeCache({\"style\": \"automatic\"}, clock, ttl_s=300)\n    text = build_prefix(3000, \"t\")\n    cache({\"style\": \"automatic\"}, text, \"q\")\n    clock.sleep(10)\n    assert hit_rate(cache({\"style\": \"automatic\"}, text, \"q\")) > 0.99\n    clock.sleep(1000)\n    assert hit_rate(cache({\"style\": \"automatic\"}, text, \"q\")) == 0.0\nbash\n$ python -m pytest -q\n.....                                                                    [100%]\n5 passed in 0.22s\n```\n\nRun 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.\n\n### Step 12: Run the full matrix live and archive the evidence\n\nWith 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.\n\n```\npython run.py --models fable --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out fable-20261201.jsonl\npython run.py --models astra sol --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out openai-20261201.jsonl\npython run.py --models neon --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out gemini-20261201.jsonl\npython run.py --models dsflash --sizes 600 1200 2400 --burst 4 --run-id 20261201 --out deepseek-20261201.jsonl\n```\n\nEach 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.\n\nThe complete project now looks like this:\n\n```\ncachetest/\n  models.json      pinned model IDs and prices\n  prefix.py        salted, deterministic prefix builder\n  clock.py         real and virtual clocks\n  adapters.py      four live adapters plus the toy cache\n  costs.py         cost, baseline, hit rate, break-even\n  run.py           warm run plus gap, edit, size and burst probes\n  test_costs.py    five unit tests\n```\n\n## Reading the Results: When Prompt Caching Pays and When It Does Not\n\nThe 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.\n\n| Calls sharing one prefix | Fable 5.2 saving (reported $10 write price) | Gemini 4 Neon saving (no write premium) | \n|---|---|---|\n| 1 | -24.4% | 0.0% | \n| 2 | Not listed | Not listed | \n| 3 | Not listed | 61.8% | \n| 6 | Not listed | Not listed | \n\nThe 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.\n\nUse these rules to turn your measurements into policy:\n\n- **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.\n- **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.\n- **Prefix near the minimum size:** pad with stable content or accept no caching. Do not pad with volatile content.\n- **Zero hits inside bursts:** add a warm-up request before fan-out.\n- **Break-even above your calls per prefix lifetime:** skip explicit caching on that path, because the write premium will eat the savings.\n\nPer-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.\n\n## Common Pitfalls That Skew Prompt Caching Results\n\nMost bad cache measurements come from the test, not the vendor. These are the failure modes that produce confident, wrong numbers.\n\n1. **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.\n2. **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.\n3. **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.\n4. **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.\n5. **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.\n6. **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.\n7. **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.\n8. **Firing parallel cold requests.** Twenty workers starting at once all pay full price. Warm the cache with one call first.\n\nA 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.\n\n## Troubleshooting: 10 Fixes for Prompt Caching Tests\n\nWhen a run misbehaves, find the symptom in the table and work through the fix in order.\n\n| Symptom | Likely cause | Fix | \n|---|---|---|\n| 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 | \n| 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 | \n| 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 | \n| First call is cheap, as if cached | A previous run left the same prefix warm | Change `--run-id` so the salt changes | \n| 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 | \n| 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 | \n| KeyError on a usage field | Your account returns a different field name | Print the raw usage block, then edit the matching adapter | \n| 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 | \n| 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 | \n| 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 | \n\nRate 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.\n\nIf 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.\n\n## Advanced Tips for Production Prompt Caching\n\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n\nWhen 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.\n\n## Frequently Asked Questions About Prompt Caching\n\n### What is prompt caching?\n\nPrompt 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.\n\n### How many calls does a prefix need before caching pays?\n\nIt 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.\n\n### Does caching change the model’s answers?\n\nCaching 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.\n\n### Why do I see zero cached tokens on a long prompt?\n\nThree 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.\n\n### Is DeepSeek’s cache cheaper than the others?\n\nIn 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.\n\n### Do the dry-run numbers predict my savings?\n\nNo. 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.\n\n### Should I turn on cache writes for rarely used prefixes?\n\nNot 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.", "url": "https://wpnews.pro/news/prompt-caching-cost-test-5-models-12-steps-70-min", "canonical_source": "https://shattered.io/prompt-caching-cost-test-fable-5-2-astra-neon-deepseek-12-steps-2026/", "published_at": "2026-12-01 15:17:00+00:00", "updated_at": "2026-12-01 15:43:26.773037+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "ai-tools", "developer-tools", "mlops"], "entities": ["Anthropic", "Claude Fable 5.2", "OpenAI", "GPT-6.2 Astra", "GPT-6.2 Sol", "Google", "Gemini 4 Neon", "DeepSeek V4.1-Flash"], "also_reported_by": [], "takeaway": "Cached input runs about 2% to 5% of standard input price across the five models, but because cache writes cost more than standard input — Anthropic charges $10 per million tokens for writes versus $8 for input — a prefix only pays off from the second call onward.", "recommendation": {"advice": "Measure your own prefix traffic with a harness that reads each API's cached-token counts before assuming vendor discounts; with write premiums like Anthropic's $10 versus $8 input, caching only pays from the second call.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/prompt-caching-cost-test-5-models-12-steps-70-min", "markdown": "https://wpnews.pro/news/prompt-caching-cost-test-5-models-12-steps-70-min.md", "text": "https://wpnews.pro/news/prompt-caching-cost-test-5-models-12-steps-70-min.txt", "jsonld": "https://wpnews.pro/news/prompt-caching-cost-test-5-models-12-steps-70-min.jsonld"}}