Skip to main content
Version: Dev

Response Caching

Response caching lets AISIX reuse an earlier non-streaming Chat Completions response when a later request has the same cache key. It is gateway-side response caching, not provider prompt caching or the control-plane configuration snapshot cache. For provider-side caching on Anthropic models, see Anthropic Prompt Caching. To also reuse responses for similar prompts, add Semantic Caching on top of a policy.

Start with a model-scoped in-memory policy and verify a miss followed by a hit. Add Redis only when gateway instances need to share entries, then tune the matching and sharing scopes for your traffic.

How Response Caching Works​

AISIX caches exact non-streaming Chat Completions responses. Streaming responses and other proxy API families do not use this response-cache path. A response that carries generated images, from any upstream, is not stored because of its size.

Cache policies can apply to all eligible requests, one model alias, or one caller API key. Each policy stores responses in the gateway's in-process memory cache or in Redis when Redis is configured at startup.

Before AISIX can cache a response, the gateway must have the selected backend available and the request must match an enabled cache policy.

Cache Key Matching​

AISIX creates the cache key from the normalized Chat Completions request that affects the upstream response. Two requests share a cache entry only when the model alias, message roles and normalized content, sampling settings, response length, and extra OpenAI-compatible request options match.

JSON object key order does not affect cache matching, including in nested objects. Array order does affect matching, so two requests with the same tool definitions in a different order use different cache entries.

When present, temperature and top_p are compared at 0.001 precision rather than by exact floating-point equality. Two explicit values in the same thousandth-wide bucket therefore use the same cache key when every other field matches. An omitted field remains distinct from an explicit value.

For a multi-target model, the cache key uses the alias the caller requested, not the target model that served the miss. The request ID and request headers are not part of the cache key.

Whether the caller API key partitions the cache is controlled by the policy's scope field. With the default scope: api_key, entries are private to the API key that stored them; scope: env shares entries across every caller in the environment. See Choose the Sharing Scope.

Choose a Cache Backend​

Each cache policy chooses where matching responses are stored:

BackendBehavior
MemoryDefault. Uses the in-process cache on the gateway instance that handled the miss.
RedisUses the shared Redis cache configured at gateway startup.

Use memory for single-instance deployments or when node-local cache entries are acceptable. Use Redis when several gateway instances should share cached responses for the same policy. AISIX supports a single Redis endpoint, Redis Cluster, and Redis Sentinel.

Prerequisites​

Before starting, prepare the following:

  • A working model alias and caller API key that can send non-streaming Chat Completions requests.
  • curl.
  • For AISIX Enterprise or AISIX Cloud, prepare an environment with an attached gateway. For AISIX Enterprise, follow the AISIX Enterprise getting-started guide; to request AISIX Cloud access, contact API7.
  • For Dashboard workflows, sign in with permission to manage cache policies.
  • For Admin API workflows, install jq and obtain a write-scoped token from an identity allowed to manage cache policies. The identity must also be able to read any model or caller API key referenced by a selector.
  • For AISIX OSS, prepare a gateway that loads a complete declarative resources.yaml file.

Configure an In-Memory Cache Policy​

The following example creates a model-scoped policy with the default in-process memory backend. Choose either the control-plane or AISIX OSS configuration path, then use the shared verification procedure. If another enabled cache policy already matches the example requests, disable or delete it before continuing.

Export the gateway connection and resource values used by both paths:

# AISIX_PROXY has no trailing slash or endpoint path such as /v1.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export AISIX_API_KEY="YOUR_CALLER_API_KEY"
export AISIX_MODEL="gpt-4o-mini"
export CACHE_PROMPT="cache-check-$(date +%s)"

Create the policy in the environment serving the model.

  1. Open the environment and select Cache policies, then New cache policy.
  2. Set Name to default-chat-cache and keep In-memory (per-DP) as the backend.
  3. Set TTL (seconds) to 3600. In Applies to, enter model:gpt-4o-mini.
  4. Keep Per API key as the sharing scope so each caller has private cache entries.
In-memory cache policy form with a one-hour TTL and model selector
  1. Select Create cache policy. Check the saved backend, TTL, sharing scope, and selector.
Saved default-chat-cache policy with its backend, TTL, scope, and model selector

Continue with Verify Cache Miss and Hit Behavior to confirm that the gateway applies the policy.

Verify Cache Miss and Hit Behavior​

The steps below read the x-aisix-cache response header, which the gateway sends only when its startup configuration sets proxy.expose_debug_headers to true. Enable it on the gateway you test with, or read the same verdict from the cache_status field of each request's access-log line, found by its x-aisix-request-id.

Define a helper that sends the same request body on each call:

send_cache_request() {
curl -sSi -X POST "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer ${AISIX_API_KEY}" \
-H "Content-Type: application/json" \
--data-binary @- <<EOF
{
"model": "${AISIX_MODEL}",
"messages": [{"role": "user", "content": "${CACHE_PROMPT}"}]
}
EOF
}

Send the request once:

send_cache_request

The first matching request should include this response header:

x-aisix-cache: miss

The miss means AISIX called the upstream provider and wrote the response into the cache. Repeat the request without changing the model or body:

send_cache_request

The repeated request should include:

x-aisix-cache: hit

The hit means AISIX served the stored response without calling the upstream provider. In AISIX Enterprise and AISIX Cloud, the usage event records the replayed token counts and cache-savings counters with a cost of 0. The hit therefore costs nothing and adds no spend to budgets.

Change the prompt to confirm that the request body participates in the cache key:

CACHE_PROMPT="${CACHE_PROMPT}-different" send_cache_request

The changed request should return x-aisix-cache: miss.

Share Cache Entries with Redis​

Redis lets several gateway instances share entries. Make sure Redis is running and reachable from every participating gateway, then add its connection details to config.yaml:

config.yaml
cache:
redis:
mode: single
url: redis://127.0.0.1:6379/

Start or restart each gateway after adding the Redis configuration. Configuring a policy with backend: redis does not establish the Redis connection. If a matching policy selects Redis but cache.redis is absent, AISIX disables caching for those requests instead of silently falling back to memory.

After Redis is available, replace the in-memory policy with a Redis-backed policy through the same management path you used above.

The backend is fixed when a policy is created. Replace the existing policy to switch storage.

  1. Open Cache policies and select Delete on default-chat-cache. Review the confirmation.
Confirmation before deleting the in-memory cache policy
  1. Select Delete.
  2. Select New cache policy and enter shared-chat-cache as the Name.
  3. Choose Redis (shared) and keep the original TTL, selector, and sharing scope.
Redis-backed replacement cache policy with the same TTL and model selector
  1. Select Create cache policy.

Verify Redis Cache Behavior​

Set a fresh prompt, then run send_cache_request twice. The first request should report a miss and the second should report a hit:

export CACHE_PROMPT="redis-cache-check-$(date +%s)"

send_cache_request
send_cache_request

Verify Cache Sharing Across Gateway Instances​

To confirm that Redis is shared, send the first request to one gateway instance and the identical request to another. Both instances must load the same cache policy and connect to the same Redis deployment.

export AISIX_PROXY_A="https://gateway-a.example.com"
export AISIX_PROXY_B="https://gateway-b.example.com"
export CACHE_PROMPT="shared-cache-check-$(date +%s)"

AISIX_PROXY="$AISIX_PROXY_A" send_cache_request
AISIX_PROXY="$AISIX_PROXY_B" send_cache_request

The request through gateway A should report a miss. The request through gateway B should report a hit. With the memory backend, the second gateway would have its own empty cache and report another miss.

When the Redis Cache Backend Fails​

A failed cache lookup or store does not fail the model request. A failed lookup proceeds to the upstream provider. A failed store returns the provider response without caching it. Both are treated as cache misses.

Startup and Recovery​

If Redis is unreachable at startup, connection attempts can delay all gateway listeners. After the bounded attempts finish, the listeners start and Redis-backed policies report cache misses. A background task keeps trying to attach Redis and enables the backend when it becomes available.

The gateway logs the backend, configured endpoint values, reason, and connection error. It repeats the warning every five minutes while Redis remains unavailable. Rejected credentials, NOAUTH or DENIED, and an unavailable database follow the same recovery path with reason=refused instead of reason=unreachable.

Redis endpoint values can expose credentials

The warning includes the configured endpoint values verbatim: url in single mode, nodes in cluster mode, and sentinels in sentinel mode. Credentials embedded in those values are logged too. Use the separate username and password fields for data-node credentials. Sentinel credentials remain in the sentinel URLs, so restrict access to gateway logs.

Startup stops for local errors that cannot recover in the background:

  • An invalid Redis URL or a hostname that resolves to no address.
  • TLS material that AISIX cannot read or parse, or a client certificate without its key or a key without its certificate.
  • A missing mode-specific field or timeout_secs: 0.

Configure Redis credentials and databases according to the selected mode:

  • cache.redis.username and cache.redis.password apply in every mode. Set them together because either explicit field replaces both credentials embedded in url.
  • cache.redis.database applies in single and sentinel modes. Redis Cluster always uses DB 0.

Runtime Failure Handling​

The first failure for each cache layer during an outage is logged at WARN. Later failures for that layer are logged at DEBUG until recovery.

Monitor aisix_redis_failures_total and use its operation label to identify the affected cache layer:

Cache layeroperation values
Exact response cachingcache_get, cache_put
Semantic cachingsemantic_acquire, semantic_lookup, semantic_store, semantic_index

A cache-status verdict alone cannot distinguish a degraded backend from a cold cache.

cache.redis.timeout_secs bounds each Redis round trip and connection attempt. It defaults to 5 seconds, has a minimum of 1, and rejects 0 at startup.

A timeout or connectivity failure opens the cache subsystem's short circuit for 30 seconds. During that window, cache operations return immediately and requests proceed to the upstream without paying the timeout again.

A server-reported Redis error fails the current cache operation but does not open the short circuit.

After 30 seconds, a background task probes Redis with PING. Success closes the short circuit; failure starts another 30-second interval. Application requests continue bypassing Redis until the probe succeeds.

The exact-match cache and the vector search behind Semantic Caching share one short circuit, because they are two connections to the same cache.redis block. The rate limiter keeps its own, so a Redis outage opens each independently. For the rate limiter's side of the same mechanism, see Choose Rate-Limit Counter Storage.

Mixed-Version Compatibility​

A stored response keeps every choice and its logprobs. A gateway at 1.7.0 or earlier cannot read a shared entry that contains more than one choice or logprobs; it treats that entry as a cache error. The mixed-version fleet continues sharing other entries normally.

Tune Policy Scope​

After verifying the basic cache behavior, tune the policy scope for the traffic you want to cache.

The applies_to field controls which requests match a cache policy:

ValueScope
allEvery eligible non-streaming Chat Completions request.
model:<alias>Requests that use the caller-visible model alias.
api_key:<id>Requests authenticated with the caller API key resource ID.

For AISIX Enterprise or AISIX Cloud, use the caller API key ID returned by the Admin API. In resources.yaml, use the id of the caller API key entry; a caller API key display_name does not match in this field.

Start with a narrow policy, such as a model-scoped or caller-key-scoped policy. Use a global policy only when every eligible Chat Completions request should participate in response caching.

Open Cache policies and select Edit on the policy. The editor identifies the fixed name and backend and lets you change Applies to and TTL (seconds).

Cache policy editor with an editable selector and TTL and a fixed backend

Set the selector and TTL for the traffic you want to cache, then select Save changes.

In AISIX Enterprise and AISIX Cloud, a selector for an exact alias is bound to that model's resource ID. Renaming the model preserves the policy binding and updates the selector shown by the control plane.

Deleting that model leaves the policy listed and enabled, but it no longer matches traffic. Creating a new model with the same name does not restore the binding. Edit and save the policy to bind it to the replacement, even if the selector text is unchanged.

A concrete name served only by a wildcard alias has no corresponding exact model resource. Its selector continues to match by name.

The selector determines which requests the policy covers. The separate sharing scope determines whether those requests may reuse entries across callers.

Avoid overlapping enabled policies for the same requests. When more than one policy matches, AISIX uses the first matching policy to choose the backend and TTL, so overlapping policies can make cache behavior harder to reason about.

Use only the supported matcher forms. The gateway treats an unrecognized prefix as all, which can make a mistyped policy broader than intended regardless of which management path created it.

Choose the Sharing Scope​

The policy's scope field selects the sharing boundary for cached entries:

ScopeBehavior
api_keyDefault. Entries are private to the caller API key that stored them. One caller's responses are never replayed to another caller.
envEvery caller API key in the environment shares the entries. Identical eligible requests reuse one entry across callers.

Keep the default api_key scope for general traffic: responses often embed caller-specific context, and per-key partitioning prevents one caller's answer from leaking to another. Choose env for shared-knowledge traffic — FAQ bots, documentation Q&A — where cross-caller reuse is the point and the hit rate benefits from a shared pool.

The scope also applies to a semantic layer. With scope: env, a caller can receive an entry stored for another caller's similar — not just identical — request. Review this wider sharing boundary before enabling it.

Scope is mutable, so switch the policy you already created rather than adding a second, overlapping one.

Update the existing policy rather than creating an overlapping one.

  1. Open Cache policies and select Edit on the policy.
  2. Set Sharing scope to Environment-wide. Review the warning about sharing responses across callers.
Environment-wide sharing selected in the cache policy editor
  1. Select Save changes.

Bypass the Cache Per Request​

A caller can control cache use for one request through standard Cache-Control directives:

DirectiveBehavior
Cache-Control: no-cacheSkips the cache lookup. The fresh upstream response still refreshes the stored entry.
Cache-Control: no-storePerforms the normal lookup. If it misses, the fresh upstream response is not written to the cache.

Force a fresh upstream response while allowing it to replace the stored entry:

curl -sSi -X POST "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer ${AISIX_API_KEY}" \
-H "Cache-Control: no-cache" \
-H "Content-Type: application/json" \
--data-binary @- <<EOF
{
"model": "${AISIX_MODEL}",
"messages": [{"role": "user", "content": "${CACHE_PROMPT}"}]
}
EOF

The cache verdict reflects the directive:

  • A no-cache request reports bypass, in the x-aisix-cache header when debug headers are enabled and in the access log's cache_status either way.
  • A no-store request can still report hit and serve an existing entry. If it misses, it reports miss and leaves no new entry behind.

Use no-cache to force-refresh a stale answer. Use no-store when a fresh response must not be stored. To require an upstream response and prevent that response from being stored, send Cache-Control: no-cache, no-store.

Purge Cached Entries​

Purging invalidates every entry stored under a policy — on every gateway instance and, for a policy with a semantic layer, in both matching layers — without deleting or disabling the policy.

  1. Open Cache policies and select Purge entries on the policy. Review the confirmation, which explains that the policy remains configured.
Purge confirmation explaining that cached entries are invalidated while the policy remains
  1. Select Purge. The policy can cache later responses.

Purge when cached answers have gone stale ahead of their TTL — after a system-prompt change, a provider-side model update, or a corrected upstream document.

Next Steps​

You have configured response caching and verified cache miss and hit behavior. Next:

  • Add Semantic Caching to also serve cached responses for similar — not identical — prompts.
  • Enable Anthropic Prompt Caching when you want provider-side discounts for repeated prompt prefixes instead of reusing whole responses.
  • Continue with Guardrails to add request and response checks before and after provider calls.