Skip to content
BLOG / PRODUCTION AIAdvanced

Prompt caching in production: KV cache engineering guide

How to order prompts for high KV cache hit rates across Anthropic, OpenAI and Gemini: monotonic ordering, dynamic tailing, and the cost math.

Bhavin Mistry November 15, 2026 11 min readLast reviewed

Topics:Cost and production

A single dynamic timestamp or fluctuating session variable placed at the top of a system prompt silently destroys your prompt caching rate, turning a large discount on cached input into a full-price API bill. In high-throughput AI systems processing multi-turn agent conversations, extensive document repositories, or large codebases, Key-Value (KV) cache prefix discipline is the single highest-ROI optimization an engineering team can implement.

TL;DR

Prompt caching works through exact, byte-level prefix matching of the transformer model's Key-Value tensor states across requests. To keep cache hit rates high, prompts must follow strict monotonic ordering: static system instructions first, tool schemas second, persistent reference documents third, and variable user context at the very tail. Anthropic and OpenAI both bill cache reads at about a tenth of the normal input price on most current models, and Google Gemini passes on savings for cache hits, but any modification before a cached breakpoint completely invalidates all subsequent tokens.

How transformer KV caching works under the hood

During the prefill phase of transformer inference, the model computes attention keys and values for every input token. This process scales quadratically with sequence length, causing noticeable Time-to-First-Token (TTFT) latency when prompts exceed 10,000 tokens. When prompt caching is active, the inference provider stores these calculated KV matrices in GPU High Bandwidth Memory (HBM) or ultra-fast NVMe tiers.

When a subsequent request arrives sharing an identical token prefix, the inference engine skips the prefill calculation for the cached segment, jumping directly to generating output tokens.

Price of a cache read relative to base input tokens on most Claude models
0.1x
Anthropic prompt caching documentation, read 16 November 2026
Largest discount OpenAI states for cached input tokens ("up to 95%")
95%
OpenAI prompt caching guide, read 16 November 2026
Default cache lifetime on Anthropic, refreshed each time the cache is used
5 min
Anthropic prompt caching documentation
What the providers' documentation states about prompt caching

Neither guide puts a percentage on the latency gain. Both say responses start sooner when a prefix is cached, so measure time to first token on your own prompts.

Because cache lookup relies on cryptographic hash matching of token arrays, tokenization boundaries matter. A trailing space or altered newline changes the BPE token sequence and causes an immediate cache miss.

The monotonic prefix ordering rule

The golden rule of prompt caching is monotonic volatility ordering: arrange components from the lowest rate of change to the highest rate of change.

  1. Step 1: 1. Static system prompt

    Core model persona, behavioral boundaries, and company formatting standards (changes monthly).

  2. Step 2: 2. Machine-readable tool definitions

    JSON schemas and parameter documentation for all registered agent tools (changes on deployment).

  3. Step 3: 3. Immutable reference corpus

    Enterprise handbook, API documentation, or domain database records (changes daily or per-tenant).

  4. Step 4: 4. Stable conversation history

    Multi-turn user and assistant messages, pinned and appended sequentially.

  5. Step 5: 5. Ephemeral runtime parameters

    Current UTC timestamp, user prompt, and live session variables (appended strictly at the tail).

The monotonic prefix assembly pipeline

If you place Current time: 2026-11-15T17:30:00Z in your system prompt, every request generates a unique prefix hash, forcing a 0% cache hit rate. Moving that single line to the final user message immediately restores cache hits across your user base.

Provider comparison: Anthropic, OpenAI, and Google Gemini

While the concept of KV caching is universal, each major model provider implements caching with distinct mechanics, minimum thresholds, and pricing structures.

Anthropic Claude (Explicit Breakpoints)

  • Mechanism: Explicit cache_control: { type: "ephemeral" } breakpoints (up to 4 per request), or one top-level cache_control field for automatic caching.
  • Minimum Threshold: 512 to 4,096 tokens, depending on the model.
  • Pricing: Cache reads at 0.1x the base input price on most models (lower on some of the newest); 5-minute cache writes at 1.25x and 1-hour writes at 2x.
  • Cache TTL: 5 minutes by default, refreshed on each cache hit; a 1-hour option is available.

OpenAI (Automatic Prefix Caching)

  • Mechanism: Automatic prefix matching, enabled by default on supported models; explicit breakpoints are optional on GPT-5.6 and later.
  • Minimum Threshold: 1,024 tokens on GPT-5.6 and later; it varies with request settings on earlier models.
  • Pricing: Cached input is discounted by up to 95%; cache reads are 0.1x ordinary input on most GPT-5.6 and later models.
  • Cache TTL: A 30-minute minimum by default on GPT-5.6 and later. On earlier models, typically 5 to 10 minutes of inactivity, with an extended option of up to 24 hours.

Google Gemini (Implicit and Explicit Caching)

  • Mechanism: Implicit caching is on by default for Gemini 2.5 and newer models. Explicit cache objects are limited to supported Gemini 3 and 2.5 models through the generateContent API.
  • Minimum Threshold: 2,048 tokens on Gemini 2.5 models; 4,096 tokens on Gemini 3 and 4 models.
  • Pricing: Savings are passed on automatically when a request hits the cache; Google's caching overview does not state a rate, so check its pricing page.
  • Cache TTL: Managed by Google for implicit caching; the overview does not state a lifetime.
Provider prompt caching mechanics

These details are from each provider's documentation as read on 16 November 2026. They change often, so check the linked pages before you rely on a number.

Interactive ToolClient-Side Zero Latency

KV Cache & Prompt Caching Economics Calculator

Calculate exact monthly infrastructure savings, token economics, and TTFT latency reduction across frontier models.

32,000 tokens

System instructions, schemas, few-shot examples, and ingested RAG documentation chunks.

800 tokens
10,000 calls/day

Total API requests invoking this prompt structure across your user base.

85%

Target >80% by keeping prompt headers strictly static and ordering dynamic inputs last.

Projected Monthly Savings
$20,952.00(65.0% reduction)
Monthly Cost (No Cache)
$32,220.00
Monthly Cost (With Cache)
$11,268.00
Uncached TTFT Latency
~2908 ms
Cached TTFT Latency
~712 ms (-76%)
Cost Allocation Efficiency65% saved

Based on Claude 3.5 Sonnet rates (Anthropic): $3/M input, $0.3/M cached read.

Production implementation: building a prefix-disciplined prompt assembler

To guarantee cache hits across your engineering organization, implement an architectural prompt assembler that enforces token order programmatically. Individual developers should never concatenate raw prompt strings.

// Production Monotonic Prompt Assembler
interface CacheablePayload {
  systemPrompt: string;
  tools: Record<string, unknown>[];
  tenantDocuments: string[];
  history: Array<{ role: "user" | "assistant"; content: string }>;
  runtimeContext: {
    timestamp: string;
    userId: string;
    userQuery: string;
  };
}

export function buildMonotonicClaudePrompt(payload: CacheablePayload) {
  return {
    system: [
      {
        type: "text",
        text: payload.systemPrompt,
        // Breakpoint 1: Static Persona & Guardrails
        cache_control: { type: "ephemeral" }
      },
      {
        type: "text",
        text: JSON.stringify(payload.tenantDocuments),
        // Breakpoint 2: Tenant Knowledge Corpus
        cache_control: { type: "ephemeral" }
      }
    ],
    tools: payload.tools.map((tool, index) => {
      // Breakpoint 3: Cache tool definitions on the final tool
      if (index === payload.tools.length - 1) {
        return { ...tool, cache_control: { type: "ephemeral" } };
      }
      return tool;
    }),
    messages: [
      ...payload.history,
      // Dynamic state is strictly appended in the final user message
      {
        role: "user",
        content: `[Context: ${payload.runtimeContext.timestamp} | User: ${payload.runtimeContext.userId}]\n${payload.runtimeContext.userQuery}`
      }
    ]
  };
}

Before (Dynamic System Prompt)

  • Current timestamp embedded on line 2 of system prompt.
  • Cache hit rate: 0%, because every request has a unique prefix.
  • Every request pays the full input price and full prefill time for an 18,000-token context.

After (Monotonic Prefix Alignment)

  • Timestamp relocated to final user message payload.
  • Cache hit rate: high, limited only by cold starts and cache expiry.
  • Requests that hit the cache pay the cache-read rate on the shared prefix and start responding sooner.
Illustrative scenario: moving a timestamp out of the system prompt (not a measurement)

Managing cache eviction and cold starts

Prompt caches are not permanent databases. In high-density clusters, GPU memory pressure triggers Least Recently Used (LRU) evictions when idle times exceed provider TTLs.

  • If

    Spiky, unpredictable traffic

    Choose

    Keep-alive heartbeat cron (pings cache every 4m 30s)

    Because

    Prevents cache eviction; minor idle token cost

  • If

    Predictable high-volume queues

    Choose

    Batch incoming requests by shared tenant prefix

    Because

    Maximizes hit rate without artificial pings

  • If

    Large reference documents reused over long gaps

    Choose

    A longer cache lifetime, such as Anthropic's 1-hour option

    Because

    Fewer cold starts; cache writes cost more

Architectural strategy for cache longevity

Frequently asked questions

How much does prompt caching reduce API latency? Prompt caching primarily reduces Time-to-First-Token (TTFT) by eliminating the prefill computation on cached tokens. Neither Anthropic's nor OpenAI's guide puts a percentage on the gain, and it depends on how long the cached prefix is. Measure TTFT on your own prompts with caching on and off. Output token generation speed is unaffected.

Does changing whitespace or punctuation invalidate the prompt cache? Yes. Prompt caching relies on deterministic token IDs. Any change in punctuation, whitespace, capitalization, or formatting alters the Byte-Pair Encoding (BPE) tokens, causing an immediate cache miss for that token and every subsequent token in the sequence.

Why does my Anthropic API call show a cache write instead of a cache read? The first request with a new prefix creates the cache entry, which incurs a cache write charge (a 25% surcharge over standard input pricing). Subsequent identical requests within the 5-minute TTL window read from the cache at the cache-read rate (0.1x the base input price on most Claude models).

Can I cache dynamic user conversation history? Yes. In multi-turn chat applications, append new turns sequentially without modifying past messages. By placing a cache breakpoint on the second-to-last message, you cache the cumulative conversation history up to the latest exchange.

How does prompt caching interact with temperature and sampling settings? Temperature, top_p, and output constraints have no impact on KV cache hits. The KV cache stores representations of input prompt tokens computed during prefill. Sampling parameters only govern the autoregressive decoding of new output tokens.

What is the minimum prompt size required to trigger caching? It depends on the model. Claude needs 512 to 4,096 tokens; OpenAI needs 1,024 tokens on GPT-5.6 and later; Gemini needs 2,048 tokens on 2.5 models and 4,096 tokens on Gemini 3 and 4 models. Prompts smaller than these limits bypass the cache and bill at standard input rates.

Sources

Cost and reliability

Your next step

Reading is the start. Turn it into skill: read the chapter, practise on something real, check the numbers, then follow a path.

  1. Read · ChapterCost and reliability
  2. Practise · Debug challengeCost blowup after launch
  3. Use a free toolAI cost calculator
  4. Follow a roadmapAI platform engineer roadmap
All articles on Cost and production
#prompt caching#kv cache#caching#cost#context engineering

Discuss this article

Got a question, a counter-example or a correction? Bring it to the community.

Join the discussion

Email updates

Enjoyed this? Get the next guide by email.

One email when something substantial is published. No digests, no daily drip. Unsubscribe in one click.

We will email you a confirmation link first, then send an occasional email when a substantial guide is published. Unsubscribe in one click. Stored with our email provider (Resend), never sold or shared. See the privacy policy.

Prefer a feed reader? Follow by RSS.