Skip to main content

Caching on the gateway

The gateway can cache model responses, so identical requests are answered from the cache without calling the provider. Cache hits return in milliseconds, cost nothing, and are still logged with the calling key. Caching is configured once, in the Admin UI or in spanway_settings, and then applies to chat completions, text completions, embeddings, transcriptions and the other supported call types. Response caching is part of the free gateway. Provider side prompt caching, which lowers the price of long prompts, is a different feature described on prompt caching.

A real-world scenario​

A product FAQ bot gets the same twenty questions hundreds of times a day. The admin turns on a Redis response cache with a ten minute lifetime. The first "How do I reset my password" of the morning goes to the provider, and the next few hundred are served from Redis in a few milliseconds at no cost. The Cache Analytics tab shows a 60 percent hit ratio for the bot's key, and when the FAQ changes the admin flushes the cache so nobody gets a stale answer.

Step by step​

In the Admin UI​

  1. Open /ui/caching as a proxy admin and pick the Cache Settings tab.
  2. Choose Node (Single Instance) under Redis Type, fill in Host, Port and Password or a single Redis URL, and open Advanced Settings to set Namespace and TTL (seconds).
  3. Click Test Connection and wait for Cache connection test successful!, then click Save Changes. The gateway starts caching at once, no restart needed.
  4. Pick the Cache Health tab and click Run Health Check to see the cache type, the ping result and the test write.
  5. Send a request twice and pick the Cache Analytics tab. Cache Hits and Cache Hit Ratio move, and the Cache Hits vs API Requests chart shows the hit per call type.

With curl​

The same setup in config.yaml.

spanway_settings:
cache: true
cache_params:
type: redis
host: os.environ/REDIS_HOST
port: os.environ/REDIS_PORT
password: os.environ/REDIS_PASSWORD
ttl: 600

Send the same request twice and compare the headers.

curl -i -X POST http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "claude-haiku-5-5", "messages": [{"role": "user", "content": "How do I reset my password?"}]}'

Control the cache for one request, remove one entry, or empty the cache.

curl -X POST http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "claude-haiku-5-5", "messages": [{"role": "user", "content": "Hello"}], "cache": {"ttl": 300}}'

curl -X POST http://localhost:4000/cache/delete \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"keys": ["5f2a...c1", "8bd0...9e"]}'

curl -X POST http://localhost:4000/cache/flushall -H "Authorization: Bearer $SPANWAY_MASTER_KEY"

Each gateway worker also keeps a short-lived copy of recent answers in its own memory, so a repeat request does not have to reach Redis. A delete or flush clears that copy on the worker that handled the call and tells every other worker to clear theirs, so a removed answer is not served again. The message to other workers travels over the shared coordination Redis. Without one, other workers keep serving their copy until it expires.

With the OpenAI SDK, send the cache object through extra_body.

import os
from openai import OpenAI

client = OpenAI(base_url="http://localhost:4000", api_key=os.environ["SPANWAY_API_KEY"])
client.chat.completions.create(
model="claude-haiku-5-5",
messages=[{"role": "user", "content": "Summarize our refund policy"}],
extra_body={"cache": {"no-cache": True}},
)

Expected result​

The first response carries x-spanway-cache-key with the key of the new entry and comes from the provider. The second response has the same x-spanway-cache-key, returns in milliseconds, and its spend log row is marked as a cache hit with zero cost. POST /cache/delete answers {"status": "success"} and POST /cache/flushall answers {"status": "success", "deleted_entries": 1284} with the number of cached responses it removed, and the next identical request goes to the provider again. Each worker also keeps a short-lived in-memory copy of entries it served, so a worker that served an entry moments before the delete can keep answering from that copy until the entry's ttl lapses. Use a short ttl when entries must disappear at once. The flush removes cached responses and the cached key lookups stored on that Redis, which are read again from the database on the next request. Rate limit and spend counters, pod locks and other data on the same Redis are kept, and entries saved under a per-request namespace stay until deleted by key. Both routes are for proxy admins only and each call writes an audit row. The Usage page shows cache hit rates and the spend saved, and the Cache Analytics tab breaks them down by key, model and call type.

Settings​

cache_params keyDefaultMeaning
typelocalBackend, such as local, redis, redis-semantic, s3, gcs, azure-blob, disk, qdrant-semantic or valkey-semantic. local keeps entries in each worker's memory, so replicas do not share them. See cache backends.
modedefault_ondefault_on caches every request. default_off caches only requests that send "cache": {"use-cache": true}, which is the safe choice when most answers must stay fresh.
ttlunset (no expiry on Redis)Seconds an entry lives. Without it a Redis entry stays until it is deleted or Redis evicts it, so set a ttl when answers can go stale.
namespaceunsetPrefix added to every cache key, which separates environments sharing one Redis.
supported_call_typescompletions, chat, embeddings, transcriptions, text completions, rerank, Responses and Anthropic Messages calls, sync and asyncWhich call types are cached, for example ["acompletion", "aembedding"].
max_messages4Requests with more messages, or more Responses API input items, than this are never looked up or stored, so long agent conversations never serve or create an entry. Set null to cache any length.
default_in_memory_ttlunsetSeconds entries live in the local backend. When set it replaces ttl there.
default_in_redis_ttlunsetSeconds entries live in the Redis backends (redis, redis-semantic, valkey-semantic). When set it replaces ttl there.
similarity_threshold0.8 in the Admin UIRequired similarity for semantic backends, between 0 and 1. Higher is stricter. See cache backends.

The same keys can be saved from the Cache Settings tab of the Response Cache page, and the settings reference lists them with the REDIS_* environment variables.

Cache keys are built from the model group and the request parameters that affect the output, so two requests hit the same entry only when the model, messages and generation parameters match. To share entries between model groups, see caching across model groups.

Who shares an entry​

An exact-match entry is shared by every caller of the model group. The cache key does not include the key, team or organization, so when two teams send the same prompt with the same parameters, the second team gets the first team's stored answer. That is the point of a cache for shared prompts, but it matters when an answer can depend on who asked or carry one team's data. To keep entries apart, send a per-request "namespace" for each team, send "no-store": true for answers that must never be reused, or use mode: default_off so only requests that opt in are cached. Semantic caches are kept apart per key, team and organization by default, see cache backends. A request under a zero data retention policy is never cached.

Turn the cache off​

Turning the cache off is useful when cached answers have gone stale or wrong, or while you move the cache to another Redis. Afterwards every request goes to the model again, so answers are fresh but slower and cost more. Responses already stored in Redis stay there until their ttl runs out, so turning the cache back on later can still answer from them unless you flush first.

  1. In the Admin UI, open Response Cache, go to the Cache Settings tab, select Turn Cache Off and confirm with Turn Off. With the API, send DELETE /cache/settings with a proxy admin key:

    curl -X DELETE http://localhost:4000/cache/settings \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY"
  2. The answer is {"message": "Cache settings removed and response caching turned off", "status": "success"}. The saved settings are gone, the instance that answered stops caching at once, and the other instances stop on their next settings refresh.

  3. If the config file also sets a response cache (spanway_settings.cache and cache_params), remove it there too, because that cache comes back at the next restart.

Saving the Cache Settings tab again, or POST /cache/settings, turns the cache back on. Each turn off writes a deleted audit row on Spanway_CacheConfig with object_id cache_config and the removed settings, credentials redacted. The coordination Redis that the replicas share is not touched. To keep the cache but stop normal traffic from using it, save it with Mode set to default_off instead, so only requests that send "cache": {"use-cache": true} are cached.

Per-request cache controls​

ControlEffect
"no-cache": trueSkip the cache lookup and always call the provider. The new response is still stored.
"no-store": trueDo not store this response in the cache.
"ttl": 300Store this response for the given number of seconds.
"s-maxage": 60Only accept a cached response that is at most this many seconds old.
"namespace": "team-a"Read and write under a separate namespace.
"use-cache": trueOpt in to caching when the cache runs in default_off mode.

A request under a zero data retention policy skips the response cache, so its response is never stored there and it is never answered from an earlier one. Admins can limit which controls a key may use with allowed_cache_controls on the key, for example ["no-cache"]. A request with a control the key is not allowed to use is rejected with 403. An empty or unset list allows every control.

Managing the cache​

MethodPathSummary
GET/cache/settingsRead the response cache settings
POST/cache/settingsSave the response cache settings
DELETE/cache/settingsTurn the saved response cache off
POST/cache/settings/testTest a response cache connection
GET/cache/pingCheck the response cache connection
POST/cache/deleteDelete cached responses by key
GET/cache/redis/infoRead Redis server information
POST/cache/flushallEmpty the Redis response cache

Cache settings saved from the Admin UI or with POST /cache/settings are stored encrypted in the database and applied without a restart. Testing a Redis connection walks through the test and save routes.

Errors​

What you seeWhyFix
503 Cache not initialized from /cache/pingNo cache is configured.Save cache settings on the Cache Settings tab, or set cache: true with cache_params in the config file.
400 Cache type local does not support deleting a key, ... does not support flushing or ... does not support redis info/cache/delete, /cache/flushall and /cache/redis/info work on Redis only.Switch to a Redis backend, or restart the gateway to clear a local cache.
503 Cache not initialized. spanway.cache is None from /cache/delete, /cache/flushall or /cache/redis/infoNo response cache is configured.Set one up on the Cache Settings tab.
500 Cache Delete Failed(...) or 503 Service Unhealthy (...)Redis refused the delete, or could not be reached for the flush or Redis info.Check the connection on the Cache Health tab.
401 Only proxy admin can be used ... or 403 user not allowed to access this route, role= proxy_admin_viewerThe cache routes are for proxy admins, and Admin Viewers may only read.Use a proxy admin key.
404 No cache settings are saved, so there is nothing to turn off. from DELETE /cache/settingsNothing was saved from the Admin UI or POST /cache/settings, so there is no saved cache to turn off. A cache from the config file is turned off in the config file.Remove cache from the config file and restart, or ignore the message if the cache is already off.
422 at body.keys from /cache/deleteThe body has no keys list, or it is empty.Send at least one key.
Requests are never cache hitsThe requests differ in a parameter, caching runs in default_off mode, or the conversation has more than max_messages (default 4) messages.Compare the two bodies, send "cache": {"use-cache": true}, or raise max_messages.
403 Not allowed to set <control> as a cache control. Contact admin to change permissions.The key's allowed_cache_controls does not include that control.Add the control to the key, or remove it from the request.
Stale answers after a content changeEntries live for ttl seconds.Call /cache/flushall, or /cache/delete with the x-spanway-cache-key of the stale entries.
Connection test failed on the Cache Settings tabThe gateway cannot reach Redis with those values.See testing a Redis connection.

Logs​

LevelLineMeaning and action
INFOCache settings initialized from databaseA replica loaded the saved cache settings. Normal.
INFOSaved cache settings were removed, response cache turned offAn admin turned the cache off, or a replica noticed that the saved settings were removed. Normal.
WARNINGCLIENT LIST command failed (likely restricted on managed Redis): ...A managed Redis refuses the client list. Normal on managed services.
WARNINGFailed to write cache-settings audit log: ...A save worked but its audit row was not written. Check the database.
ERRORCache health check failed/cache/ping could not reach the cache. Check the connection.

Testing a Redis connection lists the lines of the test and save routes.