AI Coding Agents
OpenAI prompt_cache_key: How Cache Routing Actually Works
On supported OpenAI models before GPT-5.6, a stable prompt_cache_key helps route requests that share a reusable prefix to the same machine. On GPT-5.6 and later, routing is automatic, breakpoints determine which prefix boundaries are eligible for reuse, and an optional key separates cache reuse and accounting by customer or user.
On supported OpenAI models before GPT-5.6, a stable prompt_cache_key helps route requests that share a reusable prefix to the same machine. On GPT-5.6 and later, routing is automatic, breakpoints determine which prefix boundaries are eligible for reuse, and an optional key separates cache reuse and accounting by customer or user.
This distinction is easy to miss because OpenAI still ships both descriptions. The current prompt caching guide covers two regimes, while the archived Prompt Caching 201 cookbook documents the pre-GPT-5.6 behavior in more operational detail. Everything below labels which regime each rule belongs to.
How OpenAI decides which machine sees your request
Cached states live on individual machines. A request can reuse a cached prefix only if it reaches a machine holding a matching entry that has not expired, so routing is the mechanism that makes cache hits possible at all. Per the current guide, routing for a given model inside an organization and processing region depends on three inputs:
- Current machine load and available capacity.
- A hash of the initial tokens after the hidden OpenAI content, including tool definitions when present. The guide adds that the number of tokens hashed varies by model.
- A supplied
prompt_cache_key, which separates cache reuse between groups of requests and helps optimize cache routing on models before GPT-5.6.
Two boundary conditions fall out of this design. Caches are not shared across organizations, and they cannot be reused across regional processing boundaries. A prompt cached in one processing region will not serve a request processed in another.
How much of the prompt is hashed
The archived cookbook cites roughly 256 initial tokens. The current guide says the count varies by model and that the hash includes tool definitions when present. Keep early content and tool definitions stable, then measure reuse with your actual rendered prompt. The hash helps choose a machine, while a cache hit requires a match through an eligible prefix boundary. Two requests can therefore hash alike even when content farther into the prefix prevents reuse.
What the key adds on models before GPT-5.6
When you supply a prompt_cache_key, it is combined with the routing hash to increase stickiness: requests sharing a prefix and a key are more likely to reach the same engine and reuse its cached KV state. The cookbook describes the case where this pays off most, different requests that share the same initial context but diverge later.
In OpenAI’s cookbook example, a coding customer’s hit rate rose from 60% to 87% after adopting prompt_cache_key.
Read usage.input_tokens_details.cached_tokens in Responses or usage.prompt_tokens_details.cached_tokens in Chat Completions. If repeated requests show zero billed reads, check the model’s minimum cacheable prefix length, confirm the rendered prefix and eligible boundary match, and check retention before investigating routing. On Responses models that support prompt_cache_options, check usage.input_tokens_details.cache_write_tokens as well. A token billed as a write is excluded from the read count, including on an upgrade from 30-minute to 12-hour coverage. For the cross-provider version, see measuring prompt cache hit rate.
Azure OpenAI’s November 6, 2026 guide recommends reusing prompt_cache_key for requests that share long common prefixes on models before GPT-5.6. The parameter is available independently of the API version.
Sizing keys around the 15 requests per minute target
The current OpenAI guide targets about 15 requests per minute in total across all prefixes using each key on models before GPT-5.6. The archived cookbook gives roughly 15 requests per minute per prefix and key pair. Use the current per-key total to size your groups. Traffic above the target can overflow to machines that may need to compute the prefix before they can serve a hit.
For an initial estimate, assume a shared system prefix serves support agents at 180 requests per minute at peak. Divide by 15 to get 12 buckets if traffic is evenly distributed. Use a stable assignment so each tenant’s related requests keep the same key. Measure traffic and cached tokens per key at peak, since a hash can distribute tenant IDs evenly while a busy tenant still overloads one bucket.
import hashlib
def prompt_cache_key(tenant_id: str, buckets: int) -> str:
# Illustrative: stable assignment for an earlier model.
n = int(hashlib.sha256(tenant_id.encode()).hexdigest(), 16)
return f"support:{n % buckets}"
key = prompt_cache_key("tenant-123", buckets=12)
If one tenant causes overflow, test a finer stable grouping for that tenant, such as a conversation or workload that has its own reusable prefix. Changing assignments can temporarily reduce reuse as the new groups warm up. The cookbook also warns that overly narrow keys can spread traffic so thin that each group sees fewer repeats.
Why requests with the same key still miss
- Routing misses under load. When a machine is saturated, requests can overflow elsewhere even with identical keys.
- Expiry. On earlier models,
in_memoryentries typically last 5 to 10 minutes of inactivity and up to one hour. The24hpolicy, where supported, typically retains entries for around 30 minutes and can retain them for up to 24 hours. - Prefix divergence. The key helps route requests. Reuse still depends on matching the rendered content through an eligible boundary.
What the key does on GPT-5.6 and later
Assign a distinct key such as support:customer_123 when you want to separate cache reuse and accounting by customer, user, or workspace. The guide’s multi-turn agent example uses agent_123_v1:user_456 across a user’s sessions and forks with the same agent. Separate keys also help prevent cache-hit probing, where someone submits candidate prompts and watches for hits to infer what another user previously cached.
| Model regime | Role of prompt_cache_key | What drives hits |
|---|---|---|
| Models before GPT-5.6 | Optimize cache routing; reuse one stable key per shared prefix | Prefix match plus key plus machine locality |
| GPT-5.6 and later | Optional grouping for separate cache reuse and accounting | Automatic routing plus breakpoint placement |
As of November 30, 2026, open Codex issue #30425, filed June 28, 2026, which does not name the model, reports intermittent zero cached tokens despite a stable key and repeated prefixes. In Codex issue #63587, opened and closed November 24, 2026, a GPT-6.2 Sol user reports a same-socket continuation with zero cached tokens despite sending previous_response_id, x-codex-turn-state, and the same key. The next request recorded 46,848 cached tokens, nearly all of the preceding request’s 46,968 input tokens. The report leaves the cause unresolved.
As of November 30, 2026, open Codex issue #35300, filed July 25, 2026, reports 0% cache hits in a GPT-5.6 replay with a fixed key and a changing final user message. Adding an explicit prompt_cache_breakpoint at the end of the stable startup prefix raised the reporter’s result to 98.6%. The same report observed about 98% hits on append-only turns within one session. Test an explicit breakpoint if independent requests share a startup prefix and diverge at the first user turn. For write charges and breakpoint mechanics, see OpenAI prompt caching changes in GPT-5.6.
When migrating an existing integration, keep your current key values to preserve per-customer accounting. Test whether the default implicit breakpoint at the latest eligible message fits your request pattern. If variable content moves that boundary, put an explicit breakpoint at the end of the stable content and measure billed reads and writes on otherwise comparable requests.
Choosing a key granularity
On models where the key still steers routing, granularity is the whole decision. The cookbook’s observed patterns map cleanly onto three choices:
| Granularity | Best for | Watch out for |
|---|---|---|
| Per conversation or session | Many parallel, unrelated threads per user | Key count grows fast; cold caches per session |
| Per user or tenant | Related conversations over the same context, such as one codebase | Busy tenants can exceed the per-key traffic target |
| Bucketed groups | High-volume shared prefixes | Needs a stable hash-mod mapping; rebalancing costs misses |
Per-user keys improve reuse across related conversations, like a user working the same codebase all day. Per-conversation keys scale better when each user runs many unrelated threads in parallel. For a large shared prefix under heavy traffic, group several users per key by hashing the user ID into a fixed number of buckets sized to the ~15 rpm target.
Whatever you choose, do not put secrets or personal data in the key. It is a routing label that travels with the request.
The same idea at other providers
OpenAI is not the only provider that exposes a routing hint, and the shapes are worth comparing if you run a multi-provider stack or a gateway.
xAI Grok is the most directive: its best-practices doc says to always set prompt_cache_key or the x-grok-conv-id header, which routes requests to the same server to maximize hits. A UUID or your own session ID is the suggested value. The same doc warns that cache entries can be evicted at any time due to server load or restarts, and that a different key cannot reliably force a miss either, since matching starts at the beginning of the prompt.
Mistral exposes prompt_cache_key as a hint that increases the chance of a hit without promising one, and tells you to use a stable application-level identifier such as a conversation, session, or workflow ID. Two mechanics differ from OpenAI’s: cache blocks contain 64 tokens, so cached_tokens comes back as a multiple of 64 and prompts under 64 tokens cannot hit, and Mistral warns you not to include secrets or sensitive user data in the key.
OpenRouter can route subsequent requests to the same provider endpoint, tracked per account, model, and conversation. Stickiness requires a provider whose cache reads cost less than regular input. Pass a session ID of at most 256 characters in the session_id body field or the x-session-id header. OpenRouter can start sticky routing after the first successful request with that ID, even before a cache hit. Without a session ID, OpenRouter waits for a cache hit, and a supplied prompt_cache_key serves as the fallback sticky routing key. A manual provider.order takes priority, and an unavailable provider can trigger fallback. Sticky sessions expire after 60 minutes of inactivity, with each successful request resetting the timer.
| Provider | Field or header | Mechanism | Documented limits |
|---|---|---|---|
| OpenAI, pre-GPT-5.6 | prompt_cache_key | Combined with initial-token hash to help route to the same machine | About 15 requests per minute in total across all prefixes using each key |
| OpenAI, GPT-5.6+ | prompt_cache_key | Separates cache reuse and accounting | Optional, with automatic routing |
| xAI | prompt_cache_key or x-grok-conv-id | Routes to the same server | Eviction any time under load or restarts |
| Mistral | prompt_cache_key | Raises hit chance | 64-token blocks; no secrets in the key |
| OpenRouter | session_id, x-session-id, or prompt_cache_key fallback | Sticky provider routing per model and conversation | 60-minute inactivity expiry, 256-character session ID limit |
For the gateway layer more broadly, including how breakpoints and markers translate across providers, see prompt caching through LLM gateways.
What to do next
- Check your model first. On supported models before GPT-5.6, use a stable key for related requests that share a prefix. On GPT-5.6 and later, check the breakpoint and use a key when you need separate cache reuse and accounting.
- Size keys on earlier models. Aim for about 15 requests per minute in total across all prefixes using each key. Partition busier groups with a stable, deterministic mapping and verify the distribution at peak.
- Verify with usage fields. Read
usage.input_tokens_details.cached_tokensin Responses orusage.prompt_tokens_details.cached_tokensin Chat Completions. For repeated zeros, check minimum prefix length, the rendered prefix and eligible boundary, and retention before investigating routing. - Keep the hashed region stable. The hash covers the initial tokens including tool definitions. Stable tools, stable system content, dynamic content last.
- Price the outcome. Cached-input rates differ by model and regime, and GPT-5.6 and later bill cache writes. Compare current rates on the AI Provider Pricing Index.
- Measure before and after a key change. See what prompt caching is for the mechanics and how to measure your hit rate for the comparison.
Sources
- Prompt caching (OpenAI, accessed 2026-11-30)
- Prompt Caching 201 (OpenAI Cookbook, archived, accessed 2026-11-30)
- Prompt caching with Azure OpenAI (Microsoft, accessed 2026-11-30)
- Intermittent zero prompt-cache hits despite stable prompt_cache_key and repeated/same-prefix Codex requests (OpenAI Codex issue tracker, accessed 2026-11-30)
- Responses WebSocket: same-socket continuation with previous_response_id + x-codex-turn-state intermittently returns cached_tokens=0 (OpenAI Codex issue tracker, accessed 2026-11-30)
- GPT-5.6 prompt caching: Codex cannot emit
prompt_cache_breakpoint, preventing reuse of stable startup prefixes (OpenAI Codex issue tracker, accessed 2026-11-30) - Prompt caching best practices and FAQ (xAI, accessed 2026-11-30)
- Prompt caching (Mistral AI, accessed 2026-11-30)
- Prompt caching (OpenRouter, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
OpenAI prompt_cache_key: How Cache Routing Actually Works. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/openai-prompt-cache-key-routing/
Sources
- Prompt caching
- Prompt Caching 201
- Prompt caching with Azure OpenAI
- Intermittent zero promptcache hits despite stable promptcachekey and repeated/sameprefix Codex requests
- Responses WebSocket: samesocket continuation with previousresponseid + xcodexturnstate intermittently returns cachedtokens=0
- GPT5.6 prompt caching: Codex cannot emit promptcachebreakpoint, preventing reuse of stable startup prefixes
- Prompt caching best practices and FAQ
- Prompt caching
- Prompt caching