Skip to content

Chat answer cache

Last updated: 2026-11-21T09:54:10-03:00 (UTC-3)

A chat question that was already answered can come back from the cache, without calling the provider. The comparison is exact or, with an embeddings alias, by meaning of the user’s last message: “what is the capital of France?” and “tell me the capital of France” get the same answer. Flag: semantic_cache.

Isolation is strict: only the final question is compared by meaning; the rest of the conversation must be identical. And the cache is separated per key (or per team).

features:
chat_completions: true
embeddings: true
semantic_cache: true
models:
- id: gpt
targets: [{provider: openai, model: gpt-4o-mini}]
semantic_cache:
enabled: true
ttl: 1h # 1s to 24h
embedding_model: nomic # without it, the cache is exact only
threshold: 0.9 # required with embedding_model; no default
scope: key # key (default) or team
max_input_chars: 2000 # longer questions only match exactly
- id: nomic
capabilities: [embeddings]
targets: [{provider: llama, model: nomic}]

semantic_cache.enabled turns the alias’s cache policy on or off without removing it. The TTL is required whenever the policy block is present; 1h is the console’s creation preset, not a gateway default. With an embeddings alias, the similarity threshold must be finite and between 0.5 and 1; its editor preset is not a backend default. Scope defaults to key, and omitted or zero max_input_chars selects 2000 (maximum 8000). These constraints are shared with the existing backend and console consumers; see parameter definitions.

The same fields are in the API (PUT /api/v1/admin/models/{id}) and in the model editor in the console. In Providers, the “Chat answer cache” panel shows the backend, the policies and the live entries, and deletes an alias’s entries.

  1. The last message must be from the user and contain only text. A conversation that ends in a tool result, or a question with an image, proceeds without the cache.

  2. The bucket is an HMAC of:

    • the scope (key, or team with scope: team);
    • the alias and the configuration of the alias and of the embeddings model;
    • the connection of every provider those two aliases name (protocol, base URL, API version, fixed headers and auth type, never the credential), so repointing a provider never serves what the previous endpoint answered;
    • the alias’s output guardrails;
    • every parameter (except stream) and every previous message.

    Changing any of them leads to a different bucket.

  3. Within the bucket, the same question matches without an embedding.

  4. With embedding_model, the question is embedded as the calling key itself, through the normal /v1/embeddings route: quota, ledger and logs see the call. The most similar entry with cosine similarity at or above threshold wins, among the 500 newest in the bucket.

  5. If the key cannot call the embeddings alias, or if the embedding fails, the lookup is exact only and the chat proceeds normally.

Input guardrails, quota and usage recording run before the lookup. A blocked prompt never receives an answer from the cache.

Header Value
X-Gateway-Cache hit or miss (absent when the policy does not apply)
X-Gateway-Cache-Kind exact or semantic
X-Gateway-Cache-Similarity similarity of the semantic hit, to 4 decimal places
X-Gateway-Provider provider that generated the stored answer
  • id: a hit gets a new id and created.
  • Stream: with stream: true, the answer comes back as SSE chunks, with usage when stream_options.include_usage asks for it, and ends in [DONE].
  • Usage: the recorded usage has no new tokens, and valuation uses the reason cache_hit.

Only 200 responses with a non-empty choices, up to 256 KiB, read to the end, are stored. With an output guardrail, the already-masked response is stored, the same one the client received.

A streamed response is stored too. The gateway reassembles the chat.completion from the chunks the client received: text, reasoning_content, tool calls with concatenated arguments, finish_reason and usage. It is only stored if the stream ends in [DONE], with every choice closed and no field it cannot reassemble (refusal, audio, logprobs). Aliases with an output guardrail do not store streams: the stream does not go through the mask, and the entry could later be served as JSON without it.

Request Effect
Cache-Control: no-cache does not look up, but stores the new answer
Cache-Control: no-store looks up, but does not store
X-Gateway-Cache: bypass neither looks up nor stores
body "cache": {"no-cache": true} or {"no-store": true} the field is removed before the provider
  • With PostgreSQL:
    • entries live in gateway_semantic_cache and apply to every replica;
    • the vector is REAL[] and the dot product is computed in SQL;
    • the answer is encrypted with AES-GCM, with a key derived from admin.session_key_env and the bucket as associated data;
    • the database stores neither the question nor the answer in readable form;
    • replicas with different secrets cannot open each other’s entries and treat that as a miss;
    • an answer is written after the response, off the request path, with at most 16 writes in flight per process. When all 16 are busy (a slow database), the answer is not stored and the write is counted as dropped; on shutdown the process waits up to 6 seconds for the writes in flight;
    • each write trims the bucket to its newest 500 entries and removes up to 100 expired ones, skipping rows another replica is already deleting, so concurrent writers never wait on or deadlock with each other.
  • With Redis (distributed_semantic_cache): see Shared across replicas on Redis below. PostgreSQL then carries no chat cache reads or writes.

Operations:

  • GET /api/v1/admin/semantic-cache (providers:read) and DELETE /api/v1/admin/semantic-cache?model= (providers:manage).
  • Metric gateway_semantic_cache_total{model,result}, with result = exact_hit, semantic_hit, miss, bypass, store, dropped, error or, on Redis only, skipped (lookup not attempted while the breaker below is open).
  • ?model= takes any name a configured model serves. Answers are stored under the served name: the model, the canonical model of an alias_of name, or the concrete name a wildcard alias resolved (openai/gpt-4o through openai/*). Purging openai/gpt-4o removes that name’s answers; purging openai/* (what the console sends) removes every name under that prefix, including names a more specific alias under the same prefix served. A name no configured model serves answers 404 model_not_found: it would purge nothing. To remove the answers of a model you deleted from the configuration, purge without ?model=.

The exact chat cache is this cache without embedding_model: an identical conversation gets the stored answer. The operator flag exact_chat_cache (off by default, requires semantic_cache) applies stricter rules to every chat cache policy, exact or semantic, instead of adding a second cache:

features:
semantic_cache: true
exact_chat_cache: true
chat_cache_cross_tenant: false # share past the team; off by default
models:
- id: gpt
semantic_cache:
enabled: true
ttl: 1h # the longest an answer is kept; clients can only shorten it
scope: team # key (default) or team
# share: organization # or all; only with chat_cache_cross_tenant
  • The key begins with the organization and team. With scope: key it is organization, team and key; with scope: team, organization and team. Answers never cross teams unless the policy sets share and the operator flag chat_cache_cross_tenant is on: share: organization serves every team of the caller’s organization, share: all every organization. A key without an organization (organizations off, or a team in none) is not one tenant: share: organization keeps it within its scope. Without the flag share is saved but ignored. A shared bucket also shares its trimming (the newest 500 entries) and tells one tenant, through X-Gateway-Cache: hit, that another asked the same thing: share only between tenants that trust each other.
  • The key covers the whole normalized request: every parameter that reaches the provider (model configuration, tools, tool_choice, response_format, temperature, seed, max_tokens and the rest), every earlier message, and the last message’s fields besides its text (name, for example). Object keys are sorted and insignificant whitespace removed at every level, so two requests that differ only in key order or spacing share an entry; numbers keep their exact text. A value with a repeated member name, or with a surrogate escape, is keyed by its exact bytes instead, since a provider may read either duplicate. Without an embedding model the last message’s content itself is in the key, so text parts never match one string joined by newlines. Only stream and stream_options are left out, so a streamed and a JSON request share an entry. The provider connections, output guardrails and forwarded client headers stay in the key as before. Turning the flag on starts a new key space: entries stored before it are not read (they expire with their TTL).
  • Per-request lifetime, capped by the admin: X-Gateway-Cache-TTL: 30 (seconds, up to 86400, or a Go duration such as 2m) or the body field "cache": {"ttl": 30} stores the answer for that long, never longer than the alias ttl. An unreadable value is ignored and the alias ttl applies. Cache-Control: no-cache / no-store, X-Gateway-Cache: bypass and cache.no-cache / cache.no-store work as described in client control.
  • Streams are replayed, not refused: a streamed answer is stored when the stream ends cleanly and every part can be reassembled, as described in response; a hit on a stream: true request is replayed as chunks ending in [DONE]. Streams on an alias with an output guardrail are not stored.
  • A hit costs nothing and is visible: the usage event has the cache kind (cache_kind, the cache_kind analytics dimension, the request journey), no tokens, and a known valuation of zero with reason cache_hit (without the flag a hit is unknown/cache_hit). It still counts toward RPM, since admission runs before the lookup, and the gateway logs chat_cache_hit with the request ID, alias, kind, provider and whether it was a stream (never the question or the answer).

The share field is in YAML, the model API (semantic_cache.share) and the console model editor (Cache sharing past the team). Both flags are operator controls.

PostgreSQL already shares the cache between replicas that use the same database and admin.session_key_env. When you run Redis for the exact cache, you can keep the chat cache there instead, so the database carries no cache traffic and every replica on the same Redis namespace shares hits. Flag distributed_semantic_cache (runtime, operator control, off by default). It requires semantic_cache and a Redis cache_backend; memory and Memcached are refused at load and on every flag or backend change.

features:
semantic_cache: true
distributed_semantic_cache: true
cache_backend:
backend: redis
namespace: gateway_production
url_env: GATEWAY_CACHE_URL # rediss://user:password@host:6380/0
key_env: GATEWAY_CACHE_KEY # base64 of 32 random bytes, the same on every replica
timeout: 250ms
tls: {enabled: true}

Nothing else changes: the alias policy (semantic_cache on the model, TTL, threshold, scope, max_input_chars), client controls, headers, valuation and guardrail rules are the same as with PostgreSQL. The connection, TLS, ACL and console management are those of the cache backend; a console change of backend moves the chat cache with it. distributed_exact_cache is independent: either can be on without the other.

How it is stored. Redis has no similarity search without a module (the stock redis:7 image answers unknown command 'FT._LIST'), so the gateway keeps its own small index per bucket:

Key Content TTL
<namespace>:sc:e:<hmac> one answer: AES-GCM sealed body (up to 256 KiB), provider, expiry and the question’s float32 vector the alias TTL
<namespace>:sc:i:<hmac> per bucket and vector size, a list with one sealed record per question: hash, expiry and an int8 copy of the vector with its rounding-error norm extended to the longest TTL in it
<namespace>:sc:epoch, <namespace>:sc:alias:<hmac> random generations; a purge replaces one none
  • Every name is an HMAC and every value is sealed with a key derived from cache_backend.key_env and the key’s own name (associated data included), so Redis sees neither questions, answers, aliases nor teams, and a value copied under another name does not open. Replicas with a different key_env compute different buckets and names: a miss, never an error.
  • A lookup is at most four bounded round trips: the two generations, the exact answer, then (after the embedding) the bucket list and one pipelined read of up to 8 candidates. The int8 copy only bounds each candidate’s similarity from above; the candidates are re-scored against their float32 vectors and an answer is served only when that exact score reaches threshold, as in PostgreSQL. The int8 copy is four times smaller than float32: measured on local Redis 7.4, a full bucket of 500 questions of 1,536 dimensions is a 0.79 MB read (1.1 ms) instead of 3.1 MB (1.9 ms).
  • A store writes the answer and appends its record with one RPUSH/LTRIM script, so concurrent replicas writing to a busy bucket never conflict. The list keeps the newest 500 records, or fewer when their vectors would make one read exceed 1 MiB (about 325 for 3,072 dimensions, 124 for 8,192). An older question leaves the list but still matches exactly until its TTL. Vectors of another size (an embeddings alias that falls back to a provider with other dimensions) go to their own list, so each list keeps its own bound.
  • Expiry is checked against the sealed timestamp as well as the Redis TTL, so a server that ignores TTLs never serves an expired answer.

When Redis fails. The request never fails because of the cache. The first operation of a lookup decides: if Redis does not answer within cache_backend.timeout, the request goes on as a miss (X-Gateway-Cache: miss), spends no embedding and stores nothing. The failure counts as result="error" and logs semantic_cache_backend_unavailable (error class only, never the endpoint) at most once per 30 seconds with the number suppressed. For the next 2 seconds the process skips Redis altogether (counted as skipped); then one request probes it again, so a black-holed server costs at most one timeout per 2 seconds. Only lookups open this breaker: a failed background write, a cancelled client request and one key the gateway cannot read (a reply past the frame bounds, a key of another type) are counted and logged but leave the cache on for every other bucket. A boot with the flag on checks the connection, read, write and list primitives on keys of its own and refuses to start if they fail, like distributed_exact_cache. Turning the flag on at runtime does not run that check: failures show up as misses and error counts.

Status and purge. GET /api/v1/admin/semantic-cache reports backend: redis, entries_known: false and entries: -1 per alias: there is no reliable inventory without scanning the server. A purge replaces the alias generation (or the global one with no ?model=); every replica stops reading the old answers on its next lookup and they expire with their TTL; the response says purged: -1. A purge also reaches the backend the flag does not select, best effort, so switching the flag later does not bring back answers you purged; if that second purge fails the response says inactive_purge: failed (the answers there expire with their TTL). On Redis the generation belongs to the declared models[] entry, so purging one concrete name of a wildcard alias also invalidates the other names that wildcard served (PostgreSQL removes only that name); purging openai/* rotates that wildcard and every declared entry under the prefix, matching the PostgreSQL prefix delete. A Redis failure part way through answers 503; repeat the purge.

Capacity is the server’s. The gateway bounds each value (an answer of up to 256 KiB plus its vector, a bucket list of up to 1 MiB) and each read, but not the number of buckets: every combination of scope, history and parameters is its own bucket and lives up to the alias TTL (24 hours at most). Set maxmemory with volatile-lru (or allkeys-lru) on the Redis server: every cache key has a TTL except the generations, and an evicted generation only turns its answers into misses. With noeviction, a full server also stops the exact cache’s writes. These keys are outside the exact cache’s slot budget (max_entries, max_bytes), which still bounds only the exact cache.

Trust. Values are authenticated, so a client of the same Redis without the key cannot plant or alter an answer; tampering only produces misses. Redis remains trusted infrastructure, as for the exact cache: someone who can write to it can delete entries, fill it, or put back an old generation to make a purged answer reachable again until it expires. Use TLS, an ACL limited to the namespace prefix (commands GET, GETRANGE, SET, RPUSH, LTRIM, LRANGE, PTTL, PEXPIRE, EVAL/EVALSHA) and a private network.

Differences from PostgreSQL, all on the safe side. When more than 8 candidates bound above the best exact score, the best of the 8 read is served (still at or above threshold, maybe not the highest). Buckets of very large vectors compare fewer than 500 questions. Counts are unknown. The answer is served with the same headers; X-Gateway-Cache-Similarity is the exact float32 score.

Upgrade. Turning the flag on starts with an empty shared cache; PostgreSQL entries are not copied and stay there until they expire. Turning it off goes back to PostgreSQL; Redis entries expire with their TTL.

Absolute similarity depends on the embeddings model. Measured with nomic-embed-text v1.5 (llama.cpp):

Pair Similarity
“What is the capital of France?” ~ “what’s the capital city of France?” 0.973
“How do I reverse a list in Python?” ~ “How can I reverse a Python list?” 0.978
“What is the capital of France?” ~ “Tell me the capital of France” 0.956
“Is it safe to take ibuprofen with alcohol?” ~ “… paracetamol …” 0.831
“Convert 10 USD to EUR” ~ “Convert 100 USD to EUR” 0.823
“What is the weather in Paris today?” ~ “… London …” 0.798
“What is the capital of France?” ~ “… Germany?” 0.767
“Qual é a capital da França?” ~ “What is the capital of France?” 0.746

With this model, 0.9 separates paraphrases from pairs that change the meaning: a different medicine, a different amount, a different city. Even so, a high similarity does not prove the answer fits. For questions whose meaning depends on a number or a name, use the exact cache (without embedding_model). When you change the embeddings model, measure again with the similarity header.

  • On aliases with an output guardrail, only non-streaming responses populate the cache.
  • Chat Completions only. Responses, Messages and native Gemini proceed without the cache.
  • Each miss with embedding_model costs one extra embedding, which counts toward the key’s RPM and quota.

Every route below needs a console session or an admin Bearer token, the role’s permission and, for writes, the X-CSRF-Token header; the full contract is in the API reference.

Route What it does
DELETE /api/v1/admin/semantic-cache Deletes every chat cache entry, or one alias’s with ?model=

If the answer alias or embedding alias declares target conditions, semantic answer caching is bypassed. This preserves the routing boundary instead of claiming unproved cross-condition hits. Existing unconditional profiles remain unchanged; auto-router example-vector memoization has its own bounded private context namespace.

m7gtw[email protected]