Prompt Caching: Mechanics, Pricing, and Architecture
Table of content
Prompt caching is an LLM inference optimization that stores and reuses the intermediate key-value (KV) attention tensors generated for the unchanged beginning of a prompt (the prefix), skipping redundant prefill computation across requests. As of November 2026, major commercial providers discount cached token reads by 90% to 97.5% compared to standard input rates, and they also cut time-to-first-token (TTFT) latency because cached prefixes skip recomputation.
This article is written for backend engineers, AI architects, and technical founders building production LLM applications. You will learn how prefix caching operates under the hood, how OpenAI, Anthropic, and Google price and route cached prefixes, why caches silently invalidate in production, and how to structure requests for high hit rates.
What is prompt caching and how does KV cache reuse work?
Prompt caching is an LLM inference optimization that stores and reuses the intermediate key-value (KV) attention tensors generated for the unchanged beginning of a prompt (the prefix), skipping redundant prefill computation across requests. When an LLM processes a request, inference happens in two phases: the prefill phase, where the transformer computes attention states across all input tokens in parallel, and the decode phase, where it generates output tokens one by one. If you understand how to build an LLM from scratch, you know that prefill computation scales with the length of the input sequence. Without LLM KV cache reuse, sending a 50,000-token system prompt and document context on every turn forces the GPU cluster to recalculate the exact same key and value matrices from token zero.
Prefix caching eliminates that repeated work by hashing the initial token sequence and storing the resulting mathematical representations from the transformer attention layers in high-speed memory. When a subsequent request arrives with an identical opening sequence, the inference engine loads the stored KV tensors and computes attention only for the new tokens appended at the end. In OpenAI’s API, this mechanism cuts input costs by up to 95% and shortens time to first token on long prompts.
Caching only changes the cost and speed of prefill computation; it does not expand model capacity. Cached prompt prefixes still count toward a model’s total context window limit and rate limits, because the attention mechanism must still attend to those KV states in memory during generation.
Workloads with high prefix-to-suffix ratios gain the largest speed and cost improvements from prompt caching: 1. Agentic workflows that pass extensive tool definitions and structured output schemas on every execution step. 2. Coding assistants that embed repository trees and codebase summaries at the start of each prompt. 3. Long-form document or book analysis where users run multiple queries against a static text corpus. 4. Few-shot prompting pipelines that include dozens of static examples before the user query, as well as multi-turn conversational chatbots.
Prompt caching pricing, TTLs, and token minimums across providers
As of November 2026, OpenAI, Anthropic, and Google discount cached prompt reads by 90% to 97.5% compared to standard input rates, though each provider enforces distinct minimum token thresholds, write multipliers, and cache lifetimes. When you model how much it costs to build an AI system, separating uncached input tokens from cache writes and cache reads is essential for accurate unit economics.
OpenAI prompt caching pricing on GPT-5.6 and later models (including the GPT-6 family) bills cache writes at 1.25x the standard uncached input-token rate for the default 30-minute lifetime, or 2.5x if you configure an optional 12-hour minimum lifetime in the Responses API. Subsequent cache reads cost 0.1x the ordinary input rate (a 90% discount) on most models, dropping to 0.05x (a 95% discount) on GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol, and GPT-6.1 Terra. The minimum cacheable prompt length is 1,024 tokens, excluding hidden OpenAI system content. You can verify current per-model token rates in the OpenAI API documentation.
Anthropic’s Claude API sets a default cache time-to-live (TTL) of 5 minutes, refreshed at no extra cost whenever a cache hit occurs, and bills 5-minute cache writes at 1.25x the base input token price. If your workflow has longer pauses between turns, an optional 1-hour TTL is available with writes billed at 2x the base input price. Cache reads and refreshes cost 0.1x the base input price for most Claude models, 0.05x for Claude Opus 5.5 ($0.20/MTok vs $4/MTok base) and Claude Sonnet 5.5 ($0.10/MTok vs $2/MTok base), and 0.025x (a 97.5% discount) for Claude Fable 5.2 and Mythos 5.2 ($0.20/MTok vs $8/MTok base) and Claude Fable 5.1 and Mythos 5.1 ($0.25/MTok vs $10/MTok base). Minimum cacheable token lengths vary by model generation: 512 tokens for Claude Fable 5.2, Mythos 5.2, Fable 5.1, Mythos 5.1, Opus 5.5, Opus 5, Sonnet 5.5, Fable 5, Mythos 5, and Haiku 5.5; 1,024 tokens for Opus 4.8, Sonnet 5, and Sonnet 4.6; 2,048 tokens for Opus 4.7; and 4,096 tokens for Opus 4.6, Opus 4.5, and Haiku 4.5. Current model tiers and billing rules are listed in the Claude platform documentation.
For Gemini context caching on Google Cloud Vertex AI, customers pay 10% of the standard input token cost (a 90% discount) for cached tokens across supported Gemini 2.5 and newer models. Implicit caches are retained dynamically for up to a maximum of 24 hours. Minimum input token thresholds for implicit caching are 2,048 tokens on Gemini 2.5 Flash and Pro, and 4,096 tokens on Gemini 3.1 Pro Preview, 3.6 Flash, 3.8 Flash, and Gemini 4 models such as Gemini 4 Argon.
| Criterion | OpenAI (GPT-5.6 / GPT-6 family) | Anthropic (Claude 5 / 5.5 / 5.1 series) | Google (Gemini 2.5 / 3 / 4 Argon) |
|---|---|---|---|
| Activation mode (implicit vs explicit) | Implicit by default; explicit breakpoints also supported | Automatic via top-level flag or explicit block breakpoints | Implicit by default; explicit only on Gemini 2.5 and 3 via generateContent |
| Minimum cacheable tokens | 1,024 tokens (excluding hidden system content) | 512 tokens (5.5, 5.2, 5.1, and most 5 models); 1,024 to 4,096 on older 4.x/5 models | 2,048 tokens (Gemini 2.5); 4,096 tokens (Gemini 3.x and 4 Argon) |
| Cache write cost multiplier | 1.25x (30-min default TTL); 2.5x (12-hr Responses API TTL) | 1.25x (5-min default TTL); 2.0x (1-hr optional TTL) | Implicit caching enabled by default (retained dynamically up to 24h) |
| Cache read cost multiplier (discount) | 0.1x on most models (90% off); 0.05x on GPT-6.2 Astra/Sol and GPT-6.1 Sol/Terra (95% off) | 0.1x on most; 0.05x on Opus/Sonnet 5.5; 0.025x on Fable/Mythos 5.2 and 5.1 | 0.1x standard input cost (90% discount) on Vertex AI |
| Default and extended TTL | 30 minutes default; 12 hours minimum optional in Responses API | 5 minutes default (refreshed on hit); 1 hour optional | Dynamic retention up to 24 hours maximum for implicit caches |
| Max explicit breakpoints per request | Up to 4 cache writes permitted per request | Up to 4 content blocks with cache_control |
Explicit objects supported on Gemini 2.5/3; not supported on Gemini 4 models |
How OpenAI, Anthropic, and Google implement prefix caching
OpenAI and Google enable implicit prefix caching automatically by default, whereas Anthropic requires either a top-level automatic flag or up to four explicit cache_control breakpoints placed directly on content blocks. Choosing between implicit vs explicit prompt caching affects how you route requests, place cache boundaries, and inspect token usage.
OpenAI routing, Responses API, and GPT-6 diagnostics
OpenAI caches the full rendered context in strict sequence: hidden system message, tool definitions and schemas, developer messages, and conversation history (including text, images, documents, and supported audio). For GPT-5.6 and later models, both implicit caching and up to four explicit cache writes per request are supported. Under the hood, OpenAI routes incoming requests to specific inference machines using a hash of the initial prompt tokens (the exact count varies by model), combined on models before GPT-5.6 with an optional prompt_cache_key parameter. OpenAI advises keeping traffic to about 15 requests per minute (RPM) for each cache key; bursts above that can overflow to other machines, causing a one-time cache miss on each new machine. Setting prompt_cache_key routing intentionally lets you group related tenant sessions without exceeding the per-machine RPM ceiling.
If you run reasoning models, prefer OpenAI’s Responses API, which keeps reasoning state across turns and is the API OpenAI’s caching guidance is built around. The Responses API persists raw or encrypted chain-of-thought reasoning tokens across turns when you pass previous_response_id, keeping the internal token sequence intact. For GPT-5.6 and later models, OpenAI also provides a Prompt Caching Dashboard, a Prompt Cache Diagnostics tool, cache prewarming, and the ability to adjust reasoning.effort between turns via a configuration_update without invalidating the cached prefix.
Anthropic Claude cache_control and lookback windows
In Anthropic’s Claude API, you can activate Claude prompt caching cache_control in two ways: automatic caching by placing a single top-level cache_control: {"type": "ephemeral"} field in the request body, or explicit cache breakpoint optimization by attaching cache_control to up to four individual content blocks.
{
"model": "claude-sonnet-5-5",
"cache_control": { "type": "ephemeral" },
"tools": [
{
"name": "query_database",
"description": "Execute a read-only SQL query.",
"input_schema": { "type": "object", "properties": { "sql": { "type": "string" } } }
}
],
"system": [
{
"type": "text",
"text": "You are a senior database administrator...",
"cache_control": { "type": "ephemeral" }
}
],
"messages": [
{ "role": "user", "content": "Inspect the index usage on the orders table." }
]
}
Anthropic constructs cache prefixes in the strict order tools -> system -> messages. When evaluating a request, the engine uses a 20-block backward lookback window from each cache_control breakpoint to find matching prefix hashes written by prior requests. Cache lifetime is measured from the start of the request rather than the end of the response, and if you fire concurrent requests against a cold prefix, the new cache entry only becomes available for hits after the first response begins streaming. When reading the response usage object, note that input_tokens reports only the uncached tokens after the final breakpoint; you must sum cache_read_input_tokens + cache_creation_input_tokens + input_tokens to get total input tokens.
Google Gemini implicit vs explicit context caching
Google’s Gemini API runs implicit context caching by default across all Gemini 2.5 and newer models once the prompt crosses the 2,048-token or 4,096-token model threshold. Explicit context caching, where developers create and reference a named cache object, is only supported on Gemini 2.5 and Gemini 3 models through the generateContent API and is not supported on Gemini 4 models or in the Google Interactions API, which only supports implicit context caching.
Why prompt caches miss: silent invalidation and context engineering conflicts
Prompt caches fail silently whenever a single token changes near the start of a prompt, meaning dynamic timestamps, reordered JSON keys, tool changes, or mid-conversation history compaction will force a full-price prefill rebuild without raising an API error. When budgeting infrastructure in a SaaS development cost guide, silent prompt cache invalidation is one of the most common reasons production LLM bills exceed projections.
Every provider requires an exact token-by-token prefix match from the beginning of the rendered context. If an engineer injects the current DateTime.UtcNow string into the top of the system prompt, or serializes user session metadata using a dictionary with non-deterministic JSON key ordering, the hash of the first block changes on every call. The API returns a valid completion, but your telemetry will show zero cached read tokens and 100% uncached or cache-write tokens.
Dynamic tool management is a second major source of invalidation. Because OpenAI and Anthropic place tool definitions at the start of the prompt hierarchy, adding, removing, or reordering a single tool mid-conversation invalidates the entire system prompt and message history that follow. On reasoning models, changing reasoning effort parameters in older APIs also broke the prefix, though on supported GPT-6 models OpenAI allows adjusting reasoning.effort between turns via a configuration_update without invalidating the cached prefix. Switching from OpenAI’s Responses API to Chat Completions lowers cache utilization on reasoning models because intermediate chain-of-thought tokens are not persisted across turns.
Finally, teams face a structural conflict in context engineering vs prompt caching. Traditional context engineering techniques such as conversation compaction, periodic LLM summarization of old turns, or naive sliding-window truncation modify or drop early messages in the messages array. The moment you drop turn 1 and turn 2 to save context space, the token sequence shifts from the beginning of the conversation history, forcing a full cache rebuild on every subsequent turn. Even model fallbacks break caching: prompt caches are isolated per model, so retrying a refused or rate-limited request on a backup model normally triggers a cold cache write unless you use provider-specific mitigation like Anthropic’s fallback-credit-2026-07-01 beta header, which issues a fallback_credit_token to waive the fresh cache-write penalty on the fallback model.
How to structure prompts for maximum cache hit rates
To maximize cache hit rates, structure every request as an append-only prefix where static system instructions, schemas, and tool definitions appear first, cached examples or documents sit in the middle, and volatile per-turn data is strictly appended at the end. Applying disciplined cache breakpoint optimization keeps multi-turn inference predictable when estimating 2026 custom software development costs.
Follow this step-by-step architecture to keep prefixes stable across turns:
- Freeze your tool definitions at the top of the payload. In OpenAI, keep the
toolsarray completely static across all turns and restrict which tools the model may call on a given turn using theallowed_toolsparameter. In Anthropic’s Claude API, usedefer_loading(via the tool search tool) or pass theinline-tools-2026-09-15beta header to injecttool_additionblocks mid-conversation so new tools load without altering the initialtoolsprefix. - Isolate static system prompts and output schemas from per-request state. Never interpolate timestamps, user IDs, or request UUIDs into the system block; append them inside the final user message or a trailing developer message instead. Enforce deterministic JSON serialization (sorted keys) for any structured data embedded in the prompt.
- Place explicit cache breakpoints at structural boundaries. Both OpenAI (GPT-5.6+) and Anthropic allow up to four explicit breakpoints per request. Place breakpoint 1 after
tools, breakpoint 2 after your staticsysteminstructions and few-shot examples, breakpoint 3 after large uploaded reference documents, and breakpoint 4 near the end of the prior conversation history. On Claude, ensure incremental updates occur within the 20-block backward lookback window of your breakpoints. - Persist reasoning state across turns. When calling OpenAI reasoning models, use the Responses API and pass
previous_response_idon every follow-up turn so encrypted or raw chain-of-thought tokens remain cached. - Shard high-throughput routing keys. Because OpenAI routes requests by hashing the initial prompt tokens and recommends about 15 RPM per cache key, assign a consistent
prompt_cache_keyper user session or tenant cohort (on GPT-5.6 and later the key is optional and mainly separates cache accounting) so traffic distributes cleanly without overflowing a single machine. - Monitor true token accounting in CI and production. Use OpenAI’s Prompt Caching Dashboard and Prompt Cache Diagnostics tool on GPT-6 models, and configure your Anthropic telemetry to sum
cache_read_input_tokens + cache_creation_input_tokens + input_tokensrather than relying oninput_tokensalone.
Data privacy, Zero Data Retention, and multi-tenant timing attacks
Prompt caches store internal attention tensors in volatile memory rather than raw text, making them compatible with Zero Data Retention (ZDR) policies, but sharing KV caches across tenants in self-hosted serving engines exposes prompts to timing side-channel attacks.
When enterprise security teams review LLM KV cache reuse, their first concern is whether cached prompts violate compliance agreements. Because the cache stores internal mathematical representations (key-value tensors from transformer attention layers) rather than raw text or multimodal input tokens, commercial prompt caching is eligible for Zero Data Retention (ZDR) policies.
However, how those KV tensors are scoped across users matters for security. In multi-tenant LLM serving environments, such as unisolated self-hosted vLLM or SGLang deployments where global prefix caching is turned on across all users, sharing KV caches across tenants introduces a timing side-channel vulnerability. Published attacks including PROMPTPEEK, EarlyBird, and InputSnatch exploit this behavior by sending probe requests and measuring Time-to-First-Token (TTFT) latency differences. Because a cache hit returns the first token significantly faster than a cache miss, an attacker can test candidate continuations and reconstruct another user’s private prompt token-by-token. Commercial API providers mitigate this vulnerability by scoping caches strictly to the organization level or applying per-principal cryptographic salts to prefix hashes, and self-hosted engineering teams must enforce the same per-tenant salt isolation.
Frequently asked questions
Below are direct answers to the most common engineering and billing questions about prompt caching across major LLM providers.
Do cached tokens still count toward the LLM context window and rate limits?
Yes, cached prompt prefixes count in full toward a model’s total context window limit and token rate limits. Prompt caching reduces the price you pay for repeated input tokens and speeds up prefill processing, but the transformer still holds those key-value states in memory and attends to them during token generation.
Does prompt caching store raw user text or violate Zero Data Retention (ZDR)?
No, prompt caching does not store raw text or raw multimodal input tokens, and it is eligible for Zero Data Retention (ZDR) policies. The inference engine retains only the intermediate mathematical representations, specifically the key-value (KV) tensors produced by the transformer attention layers.
How do I calculate total input tokens in Anthropic’s Claude API when caching is active?
Calculate total input tokens by summing cache_read_input_tokens + cache_creation_input_tokens + input_tokens from the response usage object. In the Claude API, the input_tokens field only reports the uncached tokens that appear after your final cache breakpoint, not the entire prompt.
What happens to the cache when parallel requests hit an uncached prefix at the same time?
Concurrent requests sent before the initial cache write finishes will result in cache misses. In Anthropic’s Claude API, cache lifetime starts when the request is initiated, and a newly written cache entry only becomes available for cache hits after the first response begins streaming back to the client.
Are prompt caches shared across different models or fallback retries?
No, prompt caches are strictly isolated per model. If a primary model refuses a request and your application retries on a different fallback model, the fallback model cannot read the primary model’s KV cache; however, Anthropic’s fallback-credit-2026-07-01 beta header provides a fallback_credit_token so you are not penalized with a fresh cache-write charge on the fallback model.
Is it safe to share a prefix cache across users in self-hosted vLLM or SGLang deployments?
No, sharing an unisolated KV cache across different tenants in self-hosted vLLM or SGLang deployments exposes private prompts to timing side-channel attacks such as PROMPTPEEK, EarlyBird, and InputSnatch. Attackers can measure Time-to-First-Token (TTFT) latency differences to deduce cached tokens one by one, so you must isolate caches per organization or hash prefixes with per-principal cryptographic salts.
Engineering cache-aware LLM pipelines with Diatom Enterprises
Cache hit rate is an architecture decision, not a provider setting. It depends on how you order tools, system instructions, documents, and history, how you route tenants, and what your telemetry measures. If you are building or optimizing an LLM application and want caching, cost tracking, and data isolation designed in from the start, our custom AI development services can help.