Skip to main content

Prompt caching

Prompt caching is a provider feature that stores the processed prefix of a prompt so that later requests reusing it are cheaper and faster. It is different from the gateway's response cache, which returns a stored answer without calling the model. Spanway exposes prompt caching across providers in one way, reports cached tokens in usage, prices them correctly, and can route follow-up requests to the deployment that holds the cache.

Scenario​

A legal assistant sends the same forty page policy document with every question. Without caching, every call pays for the whole document. The team marks the document as a cache breakpoint, so the provider processes it once and later questions read it from the cache at a fraction of the price. On the Usage page the team watches the share of cached prompt tokens go up and the cost per question go down.

Steps​

  1. Check that the model supports prompt caching. In the Admin UI open the Model Hub (/ui/model-hub-table), click the model and look for the Prompt Caching badge under Capabilities. It comes from supports_prompt_caching in the price map.

  2. Mark the cacheable prefix. Anthropic style cache_control on a content part tells the provider where the cacheable prefix ends. The gateway maps it to each provider's mechanism, and providers with automatic caching, such as OpenAI, ignore it.

    curl -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{
    "model": "claude-sonnet-5-5",
    "messages": [
    {"role": "system", "content": [{"type": "text", "text": "<long policy document>", "cache_control": {"type": "ephemeral"}}]},
    {"role": "user", "content": "Does the policy cover refunds?"}
    ]
    }'
  3. Send the request twice. The first response reports cache_creation_input_tokens, the second reports prompt_tokens_details.cached_tokens.

  4. Watch the savings. Open Usage (/ui/usage) and compare cached and uncached prompt tokens per key or team, or open Logs (/ui/logs) and read the token details of the two requests.

Expected result​

The response usage of the second call includes prompt_tokens_details.cached_tokens close to the size of the document, and x-spanway-response-cost is lower than on the first call. Cost is calculated with the model's cache_read_input_token_cost and cache_creation_input_token_cost from the price map.

Keeping caches warm across deployments​

A provider cache lives with one provider account. When a model group spreads traffic across several accounts or regions, a follow-up request may land on a deployment without the cache. Add the prompt_caching pre-call check to prefer the deployment that served the previous request with the same prompt prefix.

router_settings:
optional_pre_call_checks: ["prompt_caching"]

In the Admin UI the same setting is under Router Settings (/ui/router-settings).

Injecting cache control on the gateway​

A deployment can add cache breakpoints automatically for clients that do not send them, so that every request from a chat application benefits. In the Admin UI open Models + Endpoints, click the model, click Edit Settings, turn on Cache Control Injection Points, pick the Location and Role (or a message Index) and save. The same form holds Cache Read Cost (per 1M tokens) and Cache Write Cost (per 1M tokens) when the price map has no cache prices for the model.

model_list:
- model_name: claude-sonnet-5-5
spanway_params:
model: anthropic/claude-sonnet-5-5
api_key: os.environ/ANTHROPIC_API_KEY
cache_control_injection_points:
- location: message
role: system
Injection point fieldValuesWhat it does
locationmessage or tool_configmessage marks a message as cacheable. tool_config marks the tool definitions, on AWS Bedrock only.
rolesystem, user or assistantMarks every message of that role.
indexa number, negative counts from the endMarks one message instead, for example -1 for the latest one. An index outside the conversation is skipped with a warning.
controlfor example {"type": "ephemeral", "ttl": "1h"}The cache control to add. Unset adds {"type": "ephemeral"} with the provider's 5 minute lifetime, and "ttl": "1h" keeps the cache for an hour at twice the write price.
cache_control_injection_points:
- location: message
index: -1
control: {type: ephemeral, ttl: 1h}

A request can carry at most four breakpoints. When the client already marked its own, the gateway adds only what is left of that limit.

Gateway-wide switches​

Instead of configuring each deployment, a proxy admin can turn caching on for every Claude deployment at once. These are the switches on the Prompt Caching tab of the Cost Optimization page, and they can be changed there at runtime.

SettingDefaultWhat it does
spanway_settings.enable_anthropic_prompt_caching, or SPANWAY_ENABLE_ANTHROPIC_PROMPT_CACHING=trueoffOn, the gateway marks the system prompt and the latest turn as cacheable for Claude on Anthropic, Bedrock, Vertex AI and Azure AI, so a long prompt that repeats is billed at the cached rate. Callers that share provider credentials share the cache.
spanway_settings.anthropic_prompt_caching_ttl, or SPANWAY_ANTHROPIC_PROMPT_CACHING_TTLunset (5 minutes)5m or 1h. 1h keeps the cache through long pauses, and each cache write then costs twice as much.
spanway_settings.openai_system_messages_firstoffOn, system and developer messages move to the front of OpenAI and Azure OpenAI chat requests so OpenAI's automatic cache matches more often.
spanway_settings:
enable_anthropic_prompt_caching: true
anthropic_prompt_caching_ttl: 1h

See the settings reference for what each setting does when on and when off. The Prompt Caching tab of Router Settings (/ui/router-settings) holds the same three switches.

The price map's prompt_cache_min_tokens says how long a prompt must be before a provider caches it. When a model has none, the prompt_caching pre-call check and Vertex AI context caching assume 1,024 tokens, which the MINIMUM_PROMPT_CACHE_TOKEN_COUNT environment variable changes.

Turning caching on for one key​

A key can turn automatic caching on for its own requests while the gateway-wide switch stays off, for example for one agent that resends a long system prompt. In the Admin UI open Virtual Keys, create or edit a key and turn on Enable Prompt Caching. Over the API, send enable_prompt_caching with the key.

curl -X POST http://localhost:4000/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "support-agent", "enable_prompt_caching": true}'

Expected result: the new key's requests to Claude on Anthropic, AWS Bedrock, Vertex AI and Azure AI get cache breakpoints, and its responses report cache_creation_input_tokens on the first call. The key switch can only turn caching on. When the gateway-wide switch is on, a key with enable_prompt_caching: false is still cached, because the gateway-wide switch covers every key.

Errors​

What you seeWhat it meansFix
No cached_tokens in the second responseThe prefix is below the provider's minimum cacheable size, or more than the provider's cache lifetime passed between calls, or the second call landed on another deployment.Cache a longer prefix, call again within the lifetime, and add the prompt_caching pre-call check.
400 from the provider on cache_controlThe provider rejected the breakpoint, for example too many breakpoints in one request.Keep to the provider's breakpoint limit, usually four.
Cost does not dropThe model has no cache prices in the price map.Add cache_read_input_token_cost and cache_creation_input_token_cost to the deployment with custom pricing.

The GET /cost_optimization/prompt_caching/requests route answers 403 Only proxy admin roles can view prompt caching requests for other keys, see cost optimization errors.

Logs​

The Logs page shows each request's cached and cache creation tokens in its token details. A request the gateway marked shows gateway_injected: true on the Prompt Caching tab of the Cost Optimization page and in GET /cost_optimization/prompt_caching/requests, with what caching saved on it.

LevelLineMeaning and action
WARNINGAnthropicCacheControlHook: Reached the provider limit of 4 cache breakpoints. Skipping further injection.The request already had the most breakpoints a provider accepts, so the gateway added no more. Normal for clients that mark their own.
WARNINGAnthropicCacheControlHook: Provided index <n> is out of bounds for message list of length <m>. ...An injection point's index points past the conversation, so that point was skipped. Fix the index, or use -1 for the latest message.