Fix LLM Prompt Caching Misses: 90% Hit Rates on OpenAI, Claude & Gemini

Eliminate cached_tokens: 0 and cache_read_input_tokens: 0 bugs caused by JSON key drift, dynamic timestamps, tool reordering, and min-token floors.

Checked 4 Dec 2026·Published 4 Dec 2026·9 min read·Raw .md
In brief
  • LLM KV-caches hash exact token prefixes: a single ISO timestamp, unsorted MCP tool array, or mutated JSON schema key at token 50 invalidates 20,000 downstream tokens.
  • On Anthropic Claude, broken cache prefixes with cache_control enabled actively increase input bills by 25% ($2.50 vs $2.00/1M on Sonnet 5.5) due to repeated cache-write surcharges.
  • Canonicalize tool schemas, push volatile user/time metadata to the end of the final user turn, verify model-specific minCacheTokens (1,024 to 4,096), and pass OpenAI prompt_cache_key.

Prompt caching promises an effortless 75% to 90% discount on repeated input tokens, slashing gpt-5 input from $1.25 to $0.125 per million tokens and claude-sonnet-5.5 reads from $2.00 to $0.20. Yet when engineering teams inspect raw invoice telemetry after a month in production, a shocking percentage discover cached_tokens: 0 and cache_read_input_tokens: 0 across millions of agent calls.

Worse still, silent cache misses do not merely forfeit a discount. On Anthropic models, mutating a marked cache prefix on every call actively penalizes your bill by +25% on cache writes while simultaneously multiplying your Input Tokens Per Minute (ITPM) consumption by 10x, often triggering unexpected HTTP 429 rate-limit cascades during traffic spikes.

Why is my LLM usage returning zero cached tokens despite identical templates?

Transformer KV-caching operates on exact, contiguous byte-and-token prefixes from token 0 onward, not semantic similarity or template names. Mutating even a single token near the top of your request (including unordered tool schemas, per-request ISO timestamps, or tenant IDs) forces a 100% KV recomputation downstream.

When an inference engine evaluates your request, it flattens your tools array, system instructions, and messages array into one linear sequence of token IDs and hashes fixed-block prefixes against in-memory GPU/host KV stores. There is no fuzzy matching: if token 42 changes from "09:14:01Z" to "09:14:02Z", tokens 43 through 35,000 miss the cache completely.

Inspect the exact usage objects returned on a silent cache miss across all three providers so your logging pipeline catches regressions on day one:

{
  "openai_miss": {
    "prompt_tokens": 18420,
    "completion_tokens": 390,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    }
  },
  "anthropic_write_penalty_loop": {
    "input_tokens": 310,
    "cache_creation_input_tokens": 18110,
    "cache_read_input_tokens": 0,
    "output_tokens": 390
  },
  "gemini_miss": {
    "promptTokenCount": 18420,
    "candidatesTokenCount": 390,
    "cachedContentTokenCount": 0,
    "totalTokenCount": 18810
  }
}

Look closely at anthropic_write_penalty_loop. Here, the engineer placed cache_control: { "type": "ephemeral" } at the end of an 18,110-token system prompt, but interpolated Current timestamp: 2026-12-04T00:37:19.402Z on line 3. Every single API call misses the existing cache, allocates a brand-new 18,110-token cache block billed at 1.25x ($2.50/1M on Sonnet 5.5 instead of $2.00/1M), and lets that block expire untouched 5 minutes later.

How do prompt caching rules, thresholds, and write costs compare across models?

OpenAI and Google Gemini Implicit Caching apply zero cache-write surcharges (1.0x write), whereas Anthropic charges a 1.25x write fee on 5-minute ephemeral caches; meanwhile, minimum cacheable prefix floors jump from 1,024 tokens on GPT-5 and Sonnet 5.5 up to 2,048 on Haiku 5.5 and 4,096 on Gemini 3.1 Pro.

Many production cache drops happen during cost-optimization migrations, for instance, moving a 1,600-token classification prompt from claude-sonnet-5.5 (minCacheTokens: 1,024) to claude-haiku-5.5 (minCacheTokens: 2,048), or testing a 3,200-token RAG instruction set on gemini-3.1-pro (minCacheTokens: 4,096). Below the model's exact token floor, providers silently skip caching without throwing an HTTP error.

Model (Verified Dec 2026) Base Input / 1M Cache Write / 1M Cache Read / 1M Read Discount Min Cacheable Tokens Mechanism & Routing Hint
GPT-5 (gpt-5) $1.25 $1.25 (1.0x) $0.125 90% 1,024 (+128 steps) Automatic prefix + prompt_cache_key
GPT-5 mini (gpt-5-mini) $0.25 $0.25 (1.0x) $0.025 90% 1,024 (+128 steps) Automatic prefix + prompt_cache_key
GPT-4.1 (gpt-4.1) $2.00 $2.00 (1.0x) $0.50 75% 1,024 (+128 steps) Automatic prefix + prompt_cache_key
o4-mini (o4-mini) $1.10 $1.10 (1.0x) $0.55 50% 1,024 (+128 steps) Automatic prefix + prompt_cache_key
Claude Sonnet 5.5 $2.00 $2.50 (1.25x) $0.20 90% 1,024 Explicit cache_control (up to 4 breakpoints)
Claude Opus 5.5 $5.00 $6.25 (1.25x) $0.50 90% 1,024 Explicit cache_control (up to 4 breakpoints)
Claude Haiku 5.5 (<=100K) $0.10 $0.125 (1.25x) $0.01 90% 2,048 Explicit cache_control (up to 4 breakpoints)
Gemini 3.1 Pro (<=200K) $2.00 $2.00 (1.0x) $0.20 90% 4,096 Implicit prefix cache + Explicit cachedContents
Gemini 2.5 Flash $0.30 $0.30 (1.0x) $0.075 75% 2,048 Implicit prefix cache + Explicit cachedContents

Let's verify Anthropic's break-even math so you know exactly when to attach cache_control. For a cacheable prefix P, an uncached sequence of N calls inside a 5-minute window costs N * 1.00P. With ephemeral caching, 1 write (1.25P) plus N - 1 reads (0.10P each) costs:

CachedCost(N) = 1.25P + 0.10 * (N - 1) * P = (1.15 + 0.10N) * P

At N = 1 (zero reuse inside 5 minutes), you pay 1.25P (25% loss). At N = 2 (a single cache hit within 5 minutes), you pay 1.35P versus 2.00P uncached, an immediate 32.5% savings. At N = 10, you pay 2.15P versus 10.00P (78.5% savings). Cache every prefix reused at least once per 5 minutes, and omit cache_control on ultra-sparse (< 1 call per 5 min) single-tenant prompts.

What are the five hidden code bugs that destroy prefix cache hit rates?

Five recurring application bugs cause over 95% of real-world cache misses: system-prompt timestamps/UUIDs, non-deterministic MCP tool registration order, object-key serialization drift in JSON schemas, rolling message-history truncation at index 0, and missing prompt_cache_key shard hints on OpenAI.

Walk through your request serializer and eliminate each of these anti-patterns:

1. dynamic metadata injected above static instructions

Starting a system prompt with "Today is 2026-12-04T09:41:12Z. User: usr_9921 (Plan: Pro)" ahead of 14,000 tokens of static domain rules creates a unique prefix hash every second. Append volatile session strings at the end of the final user message (or after your last cache_control breakpoint). If the model only needs the calendar date, round it to "2026-12-04".

2. async MCP tool discovery reordering the tools array

Loading MCP or plugin manifests via Promise.all([fetchGithubTools(), fetchLinearTools()]) or filtering tools dynamically per user role changes array order across cold starts, invalidating the tools root prefix and your entire system prompt behind it. Always sort tools alphabetically by tool.name and enforce role permissions inside tool handlers when possible.

3. Non-Deterministic JSON key ordering in schemas

Conditional property insertion in JavaScript (if (flag) schema.properties.meta = ...), Python set iteration, or Go map marshaling shifts JSON key order across worker boots. Although {"a":1,"b":2} and {"b":2,"a":1} parse identically, they tokenize into distinct sequences, breaking both tools[].input_schema and response_format schemas (see stopping structured JSON truncation retry loops).

4. Sliding-Window chat slicing (messages.slice(-10))

Dropping the oldest turn (messages.shift()) on every request shifts message #2 into slot #1, invalidating 100% of conversational KV-cache on every turn past turn 10. Keep history append-only for K turns (1..20), then compact 1..15 once on turn 21 to preserve a 93%+ multi-turn hit rate.

5. missing prompt_cache_key under High-Concurrency OpenAI Fan-Out

OpenAI routes cached prefixes using the initial ~256 tokens plus prompt_cache_key. At >15 RPS on a shared 15,000-token prompt, omitting prompt_cache_key (or overloading one key past ~15 RPM per host replica) spills requests onto cold replicas. Shard deterministically via workflow-v3:s${tenantHash % 4}.

How much money does fixing a broken 20K-Token agent prefix actually save?

Raising cache hits from 0% to 92% on a 20,000-token agent running 5 million monthly calls saves $95,737/month on GPT-5, $195,730/month on Claude Sonnet 5.5 (versus a write-penalty miss loop), and $153,180/month on Gemini 3.1 Pro.

Take a production coding agent running 5,000,000 turns/month with an 18,500-token static prefix, 1,500 dynamic user tokens (20,000 input total; 92.5B static + 7.5B dynamic monthly), and 500 output tokens (2.5B monthly):

  • Claude Sonnet 5.5 ($2.00 base, $2.50 write, $0.20 read, $10.00 output):
    • Broken cache_control (100% write penalty): 92,500M * $2.50 ($231,250) + $15,000 dynamic + $25,000 output = $271,250/mo.
    • Canonical prefix (92% read, 8% write): $17,020 reads + $18,500 writes + $15,000 dynamic + $25,000 output = $75,520/mo ($195,730/mo saved).
  • GPT-5 ($1.25 base, $0.125 read, $10.00 output):
    • 0% hit: $125,000 input + $25,000 output = $150,000/mo → 92% prefix hit: $54,262.50/mo ($95,737.50/mo saved).
  • Gemini 3.1 Pro (<=200K: $2.00 base, $0.20 read, $12.00 output):
    • 0% hit: $200,000 input + $30,000 output = $230,000/mo → 92% prefix hit: $76,820/mo ($153,180/mo saved).

Test your own static-to-dynamic token split in our LLM API Pricing Calculator.

How do you build a deterministic prefix serializer in TypeScript?

Recursively sort all JSON schema keys and tool declarations alphabetically, freeze static instructions in an immutable prefix block, append timestamps and tenant IDs at the end of the final user message, and log a SHA-256 prefix hash to catch drift in CI.

Use this zero-dependency canonical builder in Node.js services or memory-constrained edge gateways (avoiding buffer bloat that triggers Cloudflare Workers Error 1102 memory spikes):

import { createHash } from "node:crypto";

export interface ToolSpec {
  name: string;
  description: string;
  inputSchema: Record<string, unknown>;
}

export interface TurnContext {
  isoTimestamp: string;
  tenantId: string;
  userPrompt: string;
}

export function canonicalizeJson<T>(val: T): T {
  if (Array.isArray(val)) return val.map(canonicalizeJson) as unknown as T;
  if (val !== null && typeof val === "object") {
    return Object.fromEntries(
      Object.entries(val as Record<string, unknown>)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([k, v]) => [k, canonicalizeJson(v)])
    ) as T;
  }
  return val;
}

export function normalizeTools(tools: ToolSpec[]): ToolSpec[] {
  return [...tools]
    .sort((a, b) => a.name.localeCompare(b.name))
    .map((t) => ({ name: t.name, description: t.description.trim(), inputSchema: canonicalizeJson(t.inputSchema) }));
}

export function prefixFingerprint(systemPrompt: string, tools: ToolSpec[]): string {
  return createHash("sha256")
    .update(JSON.stringify({ tools: normalizeTools(tools), system: systemPrompt }))
    .digest("hex")
    .slice(0, 16);
}

export function buildAnthropicCachedRequest(
  systemPrompt: string,
  tools: ToolSpec[],
  history: Array<{ role: "user" | "assistant"; content: string }>,
  turn: TurnContext
) {
  const sorted = normalizeTools(tools);
  return {
    prefixHash: prefixFingerprint(systemPrompt, sorted),
    body: {
      model: "claude-sonnet-5.5",
      max_tokens: 1024,
      tools: sorted.map((t, i) => ({
        name: t.name,
        description: t.description,
        input_schema: t.inputSchema,
        ...(i === sorted.length - 1 ? { cache_control: { type: "ephemeral" as const } } : {}),
      })),
      system: [{ type: "text", text: systemPrompt, cache_control: { type: "ephemeral" as const } }],
      messages: [
        ...history,
        {
          role: "user" as const,
          content: `${turn.userPrompt}\n\n<context tenant="${turn.tenantId}" ts="${turn.isoTimestamp}" />`,
        },
      ],
    },
  };
}

export function buildOpenAiCachedRequest(systemPrompt: string, tools: ToolSpec[], turn: TurnContext, shards = 4) {
  const sorted = normalizeTools(tools);
  const hash = prefixFingerprint(systemPrompt, sorted);
  const shard = createHash("sha256").update(turn.tenantId).digest()[0] % Math.max(1, shards);
  return {
    prefixHash: hash,
    body: {
      model: "gpt-5",
      prompt_cache_key: `agent:${hash}:s${shard}`,
      tools: sorted.map((t) => ({
        type: "function" as const,
        function: { name: t.name, description: t.description, strict: true, parameters: t.inputSchema },
      })),
      messages: [
        { role: "system" as const, content: systemPrompt },
        { role: "user" as const, content: `${turn.userPrompt}\n\n[tenant=${turn.tenantId} ts=${turn.isoTimestamp}]` },
      ],
    },
  };
}

Logging prefixHash on every outbound LLM span turns debugging from guesswork into an instant diff: if prefixHash changes between two consecutive requests for the same workflow, a tool definition or system string mutated upstream.

How do you verify live cache hit ratios before deploying to production?

Execute two sequential curl calls spaced 2 seconds apart with identical static prefixes and distinct user queries, confirm the second response reports cached_tokens >= 1024 (or cache_read_input_tokens >= 1024), and enforce an automated alert if production read ratios dip below 70%.

Run this two-shot verification test in staging whenever modifying prompt templates, MCP tool registries, or model IDs:

# Call 1 warms the prefix cache; Call 2 (2 seconds later) MUST report cache_read_input_tokens > 0
for i in 1 2; do
  curl -sS https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d @staging-canonical-payload.json | jq '.usage'
  sleep 2
done

Complete this five-point verification checklist before signing off:

  1. Assert prefixHash stability in unit tests: Snapshot computePrefixFingerprint() across two fresh worker boots to verify async tool loading and JSON schema generation never permute keys.
  2. Verify model-specific minCacheTokens clearance: Confirm your static prefix exceeds 1,024 tokens for gpt-5/claude-sonnet-5.5, 2,048 tokens for claude-haiku-5.5/gemini-2.5-flash, and 4,096 tokens for gemini-3.1-pro.
  3. Track Anthropic write-to-read ratio: Alert immediately if sum(cache_creation_input_tokens) > sum(cache_read_input_tokens) over any 15-minute window, that inequality proves you are losing money on broken ephemeral writes.
  4. Compact chat history in discrete epochs: Replace per-turn messages.slice(-N) truncation with epoch compaction every 10–15 turns so multi-turn conversational prefixes remain byte-stable between compactions.
  5. Tune OpenAI prompt_cache_key shard count: Keep per-key request volume below ~15 requests per minute per shard so load balancers neither scatter cold prefixes nor overflow a single host replica.

Model your own stack numbersSimulate your exact monthly token, prompt caching, and Batch API bill

Open Calculator →

Common edge cases

Why does Anthropic bill me 25% more when cache_read_input_tokens stays at 0?

Anthropic charges a 1.25x cache-write rate ($2.50/1M on Claude Sonnet 5.5 and $6.25/1M on Opus 5.5) whenever a cache_control breakpoint misses and writes a fresh 5-minute entry. If a dynamic timestamp or user ID mutates that prefix on every call, every request pays the 25% write surcharge with zero discounted reads.

Why did switching from Claude Sonnet 5.5 to Haiku 5.5 or Gemini 3.1 Pro drop my cache hits to zero?

Minimum cacheable token thresholds vary by model. A 1,500-token system prompt clears the 1,024-token floor on GPT-5 and Claude Sonnet 5.5, but silently falls below the 2,048-token floor on Claude Haiku 5.5 and Gemini 2.5 Flash and the 4,096-token floor on Gemini 3.1 Pro.

Does changing one tool definition invalidate my system prompt cache?

Yes across both OpenAI and Anthropic. Provider KV-caches serialize tool declarations at the very root of the prompt hierarchy (tools -> system -> messages), so adding, removing, or reordering a single tool invalidates every cached token in the system prompt and message history.

How long do prompt caches stay warm across OpenAI, Anthropic, and Google Gemini?

OpenAI automatic prefix caches and Anthropic default ephemeral caches stay warm for roughly 5 to 10 minutes of inactivity (sliding on each hit), with optional extended TTL tiers on Anthropic and explicit configurable TTLs on Google Gemini Context Caching.

What changed1
  • 2026-12-04: Verified rate-limit headers, caching thresholds, and token billing mechanics against December 2026 OpenAI, Anthropic, and Gemini API specs.
Sources checked4

Spotted a provider quota or SDK change since 4 Dec 2026? Send a verification note →

Related troubleshooting runbooks