ByteCosts
prompt-caching-through-llm-gateways.mdx

AI Coding Agents

Prompt caching through LLM gateways

Prompt caching through LLM gateways depends on the request the upstream provider receives, the endpoint that serves it, and the usage the gateway gets back. Verify that your gateway preserves the stable prefix, translates cache markers to the right boundaries, and reports actual reads and writes on completed requests before judging savings.

Trace the breakpoint across the gateway

As of November 30, 2026, the gateway behavior below depends on the upstream model and API. Draw the path for one deployment before interpreting a cache miss. Identify the API shape your client sends, the gateway adapter, the actual model and provider endpoint, and the format that returns usage. A single model alias can hide several of those choices. Record them alongside the cache data so you can tell whether results changed after a routing or adapter change.

Request pathWhat happens to the markerWhat to verify
OpenRouter to Bedrock InvokeModelOpenRouter translates top-level cache_control to a trailing breakpoint because InvokeModel does not accept the top-level field directly.Determine whether the trailing boundary actually ends on stable content.
OpenRouter between Anthropic-style and OpenAI-style markersOpenRouter translates block-level cache_control and prompt_cache_breakpoint in both directions. The translation drops TTL settings. A translated marker sent to Anthropic or Google uses the default five-minute cache_control.Verify the effective lifetime on the destination. OpenRouter’s aggregate cache_write_tokens includes both 30-minute and 12-hour writes on supporting OpenAI routes. Check the upstream lifetime breakdown where available.
OpenRouter to GeminiAcross normal message content, OpenRouter uses only the last cache_control breakpoint.Confirm the final marker ends where you want reuse to stop.
LiteLLM to supported Bedrock Converse modelsLiteLLM translates block-level cache_control to Bedrock’s native cachePoint format.Check the upstream checkpoint and the returned read and write counts.
LiteLLM to GeminiMarked content goes through cachedContents, and the Gemini request references it with cachedContent.Confirm that you intended explicit caching and account for storage.
LiteLLM to a provider without support for that markerLiteLLM documents ignoring the marker where unsupported.Determine whether the destination offers its own implicit caching or expects different controls.
Claude Code through a local proxyBehavior depends on the proxy’s treatment of block-form content and cache_control.Compare inbound and outbound bodies and check upstream usage.

To test a translation, name the block you intend to cache through, such as the last block of a fixed repository guide. Locate it in the outbound body after the gateway’s normalization. Pay particular attention to any change between block-form content and a plain string. The words can survive that conversion while the marker attached to a block disappears. Check which turn data appears before the actual breakpoint too. A successful request can still write a prefix that contains a different user question each time.

LiteLLM documents a separate Bedrock Converse control, supports_bedrock_converse_cache_point, in versions that include its cited fix. The deployment’s setting takes priority over the cost map. Its docs say OpenAI-family models on Bedrock do not receive Converse cachePoint blocks. Check the adapter decision for the deployment you run before interpreting the absence of that field. A prompt may be eligible for a model’s native implicit caching even when the gateway drops an incompatible annotation.

Separate provider affinity from prefix reuse

OpenRouter’s sticky routing sends subsequent requests to the same provider endpoint when the destination’s cache-read price is below ordinary input pricing. Its default conversation identity hashes the first system or developer message and the first non-system message. For an agent that changes either opening message, a stable session_id gives the router a consistent conversation key. Send it as a top-level request field or the x-session-id header. The body value wins if both are present. OpenRouter documents a 256-character maximum. If neither session_id nor x-session-id is set, OpenRouter uses prompt_cache_key as the sticky routing key when the request supplies it.

With session_id, a successful request can establish affinity before a cache hit is observed. Without it, OpenRouter says a detected cache hit activates affinity. Sticky sessions expire after 60 minutes of inactivity, and successful requests reset that timer. A manually specified provider.order takes priority over sticky routing, and an unavailable provider can trigger fallback. Record the actual route after errors and retries so a later miss can be compared with the endpoint that served the earlier request.

Treat the routing timer and the provider cache lifetime as separate clocks. A session can stay pinned to the same provider while the cached entry expires. The same session identifier also cannot make changed prefix content match. Check the effective route first and the actual read count second. If you change your routing configuration, repeat the same fixed-prefix test before drawing a conclusion from production averages.

For flagged Gemini requests across normal messages, a common portability trap is a second breakpoint placed after a changing block. OpenRouter selects the final breakpoint for that path. The normalized first system or developer message can become a single cached systemInstruction. OpenRouter cannot keep a changing tail in that same message uncached. Move changing content into a later user message. Inspect what the gateway sends, especially when porting an Anthropic request that intentionally uses multiple explicit breakpoints.

Identify storage charges and fresh writes

LiteLLM’s Gemini adapter can change the billing regime without changing the public endpoint your application calls. Gemini 2.5 and later support implicit caching. For Gemini routes that support explicit caching, LiteLLM says adding cache_control, including through cache_control_injection_points, moves the marked prefix into an explicit cache object. Implicit caching no longer applies to that portion. Google charges storage for explicit cache objects. Compare implicit and explicit configurations using the same prefix and suffix sequence. Record how much content each explicit object holds, how long it is stored, and how much later traffic actually reads it. A workload with sporadic reuse can look attractive in token counters while incurring storage charges between calls. For the two modes, see Gemini implicit versus explicit caching.

For an illustrative estimate, assume you store a 100,000-token text prefix for one hour on Gemini 3.5 Flash. The committed rates are $1.50 per million ordinary input tokens, $0.15 per million cache-read tokens, and $1 per million stored tokens per hour. Multiply each rate by 0.10 million tokens. For one hour, storage costs an estimated $0.10. Each full read costs $0.015 versus $0.15 for ordinary input, a difference of $0.135. Under those assumptions, one full read that implicit caching would have missed covers the storage cost. If implicit caching already serves every read, explicit caching adds storage cost with no additional read savings. Compare the cost over the full lifetime of each object, including objects that go unread.

Bedrock distinguishes best-effort implicit reuse from explicit checkpoints on supported model and API combinations. For an explicit test, check the selected model’s minimum for the full prefix before the checkpoint. Bedrock can serve a successful inference even when that prefix is too short to cache. For an eligible explicit checkpoint, a request writes a new entry if a different server handles it, including a server in another Region, or if you send it before the identical request has started its response. Cross-region inference can increase writes during high demand. Include the inference profile in your test records and check whether the extra write rate appears after enabling cross-region routing. Converse reports cache reads and writes in cacheReadInputTokens and cacheWriteInputTokens. Its inputTokens counts ordinary input when caching is enabled.

On OpenRouter, let streams finish during initial verification. OpenRouter says a canceled stream usually loses the discount because it stops the upstream request before the provider returns final usage. Without those counts, it bills prompt tokens at the uncached rate. An early cancellation tells you little about whether the prefix itself was reusable. Compare completed and canceled streams in separate groups and inspect the reported cache_discount where available. OpenRouter describes positive savings on reads and a potentially negative discount when a write costs extra. Use the first-party data as a reference for rates and check the actual gateway’s reported cost for the route. AI provider pricing index

Run a direct and proxied comparison

Use a stable document or repository guide long enough to qualify on the specific model and API. Choose a new test prefix and send a request directly to the provider. Keep the selected cache boundary stable on the next request and change a user question after it. Run the follow-up within the provider’s cache lifetime after the first response completes. You want to see a write followed by a read on an explicit path. For best-effort implicit paths, repeat the pair and measure the read share across completed requests.

Run the same sequence through the gateway with a fresh, equivalently sized prefix so the direct call cannot prewarm your gateway test. If you run a local proxy, save the provider-bound request in a controlled test environment. For a managed gateway without outbound captures, use whatever request, route, and usage records it exposes. Compare the first and second responses on each path. If the direct calls show reuse and the gateway calls do not, start by checking model selection, replacement or omission of the breakpoint, and whether the gateway’s usage matches the provider’s reporting format.

Claude Code documents a useful distinction for this test. A gateway that responds with a 400 naming cache_control can trigger a retry with the marker moved from a mid-conversation system block onto the last conversation message. Claude Code keeps the marker on the last conversation message until it exits. The block bills uncached, while the conversation stays cached. A gateway that silently strips the markers and returns success causes the entire conversation history to bill as uncached input each turn. If you use Claude Code’s one-hour TTL through an ANTHROPIC_BASE_URL gateway, forward the anthropic-beta header unchanged. Part of the one-hour request travels in that header. Check the retries as well as the final response. A normal-looking session can hide either behavior unless you look at the billable usage. Claude Code prompt cache settings

If the provider shows reads but the client-facing response lacks the expected fields, treat that as a reporting problem to investigate on its own. Compare the native counters with the normalized ones for the same completed response. On OpenRouter Chat Completions, for example, check usage.prompt_tokens_details.cached_tokens and usage.prompt_tokens_details.cache_write_tokens. Measuring both sides keeps an adapter’s missing counter from looking like a drop in provider reuse.

Use this checklist before enabling the route

  • Record the exact destination model and API, and verify the cache controls it supports. If an alias can fall back, test the fallback as a distinct route.
  • Inspect the outbound request where your gateway exposes it. Verify that marked blocks survive normalization or translate into native fields at the intended boundaries.
  • Run a cold request and a follow-up within the provider’s lifetime with the same eligible prefix. Keep the first run sequential and allow streams to finish so the write and read evidence is available.
  • On OpenRouter, check session identity and provider order separately. On Bedrock, examine repeat writes when traffic uses cross-region inference. On LiteLLM with Gemini, compare the cost of explicit storage with observed read savings.
  • Repeat the test with a routine change after the intended breakpoint. If reuse disappears, retrieve the provider-bound request pair when available and find the first prefix difference.
  • Track read volume, write volume, and billed input across a representative workload before comparing routes. If usage is absent, record it as unknown. Keep canceled streams and fallback traffic visible in your prompt cache metrics.

Sources

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.

Prompt caching through LLM gateways. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/prompt-caching-through-llm-gateways/

Sources