Skip to content

Exact cache: memory, Redis/Valkey and Memcached

Last updated: 2026-11-21T13:24:01-03:00 (UTC-3)

The same exact cache profile can use local RAM, Redis compatible with the commands in this contract, or Memcached. A local endpoint and a hosted service use the same adapter: there is no dependency on Kubernetes or on a cloud product. These are not an authorization cache, a ledger or primary storage. A Redis backend can also hold the chat answer cache with distributed_semantic_cache; that profile has its own key layout and bounds, summarized in Chat answer cache on the same Redis. The restrictions on embeddings/moderations, per-request opt-in, uncounted usage and authentication before the lookup remain mandatory.

The YAML shipped with the application uses cache_backend.backend: memory and distributed_exact_cache: false. Compose, Helm, Kustomize and NPX reuse this schema; none of them installs Redis or Memcached as a mandatory dependency. The exact_cache flag enabled in the example does not store responses on its own: an eligible alias policy and cache permission on the request are also required.

To replace memory, the operator selects backend: redis or backend: memcached, provides the connection and the Secret references, and enables the remote profile. The same backend can connect to a standalone process, a self-managed container or a compatible hosted endpoint. There is no hosting field, no automatic vendor detection and no cloud service provisioning. Choosing the backend does not change PostgreSQL, the ledger, authentication or permissions. Deployment modes separate the application from the dependencies the operator provides.

The YAML remains the baseline. With cache_backend_management, the global admin can also change the backend from the console (Settings & sources → Response cache backend) or with PUT /api/v1/admin/cache-backend, without a rollout: the replica that receives the change tests connection, read, write and CAS before saving; a failure returns 422 and nothing is saved. For the redis backend the request carries the connection URL as url (write-only; omit it to keep the stored one; the console field is Connection URL). It is encrypted with the control plane key and never comes back in the response: the response has endpoint (only scheme, host and port) and url_configured. Until 0.0.1-rc.2 these fields were redis_url, redis_endpoint and redis_url_configured; a request with redis_url is now refused naming url (upgrading from 0.0.1-rc.2). The content key is generated on the server. Each replica applies the override on its next sync cycle and, if its own test fails, keeps the previous connection and shows the error. DELETE goes back to the YAML. Mutual TLS (client certificate) remains YAML-only. The distributed_exact_cache flag is a runtime flag, requires exact_cache and an effective remote backend, and grants no scopes or plan entitlements. Viewers and operators see only the safe summary. Latent configuration is validated too.

With boot_settings_view, Settings & sources → Response cache backend shows a safe read-only policy summary. Global readers do not need infrastructure:manage and do not load the private connection editor. The same summary appears as infrastructure.cache_settings in GET /api/v1/admin/config; privileged backend responses also include it as optional settings. Turning off this visibility flag removes both extensions, without changing cache behavior. Existing exact_cache, distributed_exact_cache, alias policy and client opt-in still control use; metadata grants no access.

The summary contains two layers:

  • Configured policy is the desired YAML or console block.
  • Installed manager policy is the manager currently owned by this replica. It can differ while synchronization runs or when applying a new target fails. Its state is constructed, pending_retry, invalid or unavailable. These states do not certify service health. enabled means current flags permit the viable installed manager, not that every request is cacheable.
Existing parameter Default Supported value Memory applicability
cache_backend.timeout 250ms 10ms–2s Remote operations only
cache_backend.max_entries 256 1–256 Per-process entry ceiling
cache_backend.max_bytes 33554432 2048–33554432 bytes Per-process accounting budget
cache_backend.max_response_bytes 65536 256–65536 bytes Maximum candidate response body
cache_backend.max_concurrency 16 1–64 Remote operations only

The five scalar limits and the backend selector share parameter definitions with the existing Go validators, safe projections and console controls. Namespace, address, credential and TLS relationships retain their private typed profile schema; safe descriptors never contain their configured values. The exact and semantic alias policies use their own required TTL and conditional constraints.

An integer 0 selects the existing default. An omitted or empty timeout selects 250ms. Memory retains the two remote-only configuration values for inspection, marked applicable: false; its installed timeout and concurrency have null value/source. This does not add a network timeout or concurrency gate to memory.

Every row reports its default, source and change boundary. Omitted YAML values use default; an explicit YAML default or integer zero remains yaml. A versioned console override replaces the whole block, so its five normalized policies use console, including omitted/default values. restart_required: true describes a future YAML/default edit; false describes the existing runtime console override. Reverting an override is a runtime operation even though its resulting rows describe the YAML rollout boundary. Unknown factories or invalid fields report unavailable values rather than inferred provenance.

The summary contains no namespace, endpoint, host, credential, environment variable, certificate reference or raw failure detail. Reading it does not resolve secrets, compute a secret fingerprint, connect to an adapter or probe service health. Desired and installed layers can span an asynchronous refresh; their presence is not an atomic-match guarantee.

The existing privileged editor exposes Max entries, Max bytes and Max response bytes for both memory and remote backends. These use the same versioned API, CSRF check, validation, audit and reversion as the existing timeout and remote concurrency controls. A memory save sends these three common fields and omits stale remote connection, trust and key-rotation data.

Memory may accept a response limit larger than its accounting budget: an item that does not fit is bypassed, not stored beyond the budget. A remote profile must hold at least one bounded slot. Shared slot capacity is min(max_entries, max_bytes / (max_response_bytes + 1024)); the installed entry ceiling is policy rather than observed occupancy or guaranteed slot capacity. The existing cache status panel reports capacity separately.

An observed management 401 or 403 clears private endpoint/credential drafts and invalidates late replies. After access is restored, Reload connection access explicitly reloads the editor. An authorized 409 conflict or 422 connection failure keeps the draft for correction; neither response means a successful save. Read-only global metadata remains separate from management permission.

Omitting cache_backend selects memory; backend: memory makes that choice explicit. Limits can be lowered:

features:
exact_cache: true
cache_backend:
backend: memory
max_entries: 256
max_bytes: 33554432
max_response_bytes: 65536

Capacity is a per-process LRU, with no network or credential. Restarting drops the entries. The limits are conservative accounting of entries, not a promise about the Go runtime’s maximum heap.

Shared hits require equivalent gateway configuration snapshots as well as the same backend and namespace. A different declared listener or another configuration change produces a different cache identity; host-port mappings outside the gateway configuration do not change its declared listener. Wait for each replica to apply a managed backend override before checking sharing. Starting a replica (a rollout, a scale-up, a replaced node) keeps the shared entries: its boot check creates the namespace’s generation marker only when there is none and never replaces one, so its first lookup joins the generation the running replicas serve under. Before this fix, a boot with control-plane overrides in the database (a rate policy, a model edit) discarded every replica’s entries. Replicas whose configurations differ still invalidate each other’s entries, as above.

Migrating from memory to Redis/Memcached starts with an empty cache and does not copy old responses. When you switch from one remote backend to another, entries are not transferred automatically: apply the purge/rollout procedure below, preserving the authorization and usage persisted in PostgreSQL.

features:
exact_cache: true
distributed_exact_cache: true
cache_backend:
backend: redis
namespace: gateway_production
url_env: GATEWAY_CACHE_URL
key_env: GATEWAY_CACHE_KEY
timeout: 250ms
max_concurrency: 16
max_entries: 256
max_bytes: 33554432
max_response_bytes: 65536
tls:
enabled: true
ca_file: /run/secrets/cache-ca.pem
# server_name: cache.internal.example
# cert_file: /run/secrets/cache-client.pem
# key_file: /run/secrets/cache-client-key.pem

GATEWAY_CACHE_URL holds the URL rediss://user:password@host:6380/0; never put the plaintext value in values files, Git or logged commands. URL-escape the credentials. Host and port are explicit; query and fragment are rejected. rediss also enables TLS without tls.enabled. The system CA is used when ca_file is omitted. No option disables certificate or hostname verification. A client certificate/key pair enables mTLS. Files must be regular files limited to 1 MiB, with support for Kubernetes Secret symlinks; a FIFO or device does not block the read. On Windows they must also be protected from untrusted accounts (mounted files on Windows).

The Go Redis client has a pool and dials limited by max_concurrency (the chat answer cache has a second pool on the same connection settings, with its own frame bounds, opened only when it is used; both share the same max_concurrency admission of operations), a per-operation deadline and a single dial attempt, with no command retry. A Redis restarted empty (a Pod deleted and recreated without persistence) costs no bypass, over TCP or TLS: the next lookup is a miss that recreates the generation marker, then the entries refill. Before reusing an idle plain-TCP connection the pool checks that the server has not closed it; a TLS connection cannot be checked that way, so the generation read, its SET NX and the entry read (the idempotent commands) run once more on a newly dialed connection when an open connection fails with EOF, a reset, a broken pipe or a closed connection. A Redis reply, a dial or TLS handshake failure and a timeout are never retried, and CAS and entry writes never are; only a retry that also fails counts in gateway_cache_backend_errors_total. An answer stored right after a restart can still meet a stale pooled connection: it is not kept (gateway_exact_cache_stores_total{result="failed"}), and the lookup is unaffected. The profile uses bounded GETRANGE, SET, SET NX and CAS through GET/EVAL/EVALSHA; the ACL identity needs these permissions only on the chosen prefix. Handshake commands such as HELLO/CLIENT/PING must be accepted by the service. An insufficient ACL fails the boot check. This adapter connects to a standalone Redis endpoint or a compatible proxy: it does not advertise Redis Cluster discovery, Sentinel, IAM tokens or automatic credential refresh. Valkey requires qualifying the chosen service with the same tests; protocol compatibility does not certify a hosted offering.

features:
exact_cache: true
distributed_exact_cache: true
cache_backend:
backend: memcached
namespace: gateway_production
addresses:
- cache-1.internal.example:11211
- cache-2.internal.example:11211
key_env: GATEWAY_CACHE_KEY
timeout: 250ms
max_concurrency: 16
max_entries: 256
max_bytes: 33554432
max_response_bytes: 65536
tls:
enabled: true
ca_file: /run/secrets/cache-ca.pem
# server_name: cache.internal.example
# cert_file: /run/secrets/cache-client.pem
# key_file: /run/secrets/cache-client-key.pem

Accepts 1–8 static TCP addresses. Replicas use the same list in the same order; changing the list requires a rollout and a purge after it stabilizes. The mature gomemcache client runs GET/SET/ADD/CAS/VERSION. Each operation keeps its own limited connections, closed on completion or cancellation; no abandoned request goroutine is left waiting on a server. Admission limits concurrent operations; a check of all servers can open up to addresses × max_concurrency connections. TLS/mTLS support direct servers or a trusted TLS terminator. SASL/binary, UDP and autodiscovery of hosted clusters are not implemented. Do not configure a service that requires those protocols as if it were compatible.

For isolated development, allow_insecure: true explicitly allows TCP without TLS on any remote backend. This option does not disable verification when TLS is enabled. Restrict the service to a private network/loopback. Production must use TLS and a network policy.

Keys of the cache_backend block:

Field Meaning Profile/limit
cache_backend.backend Implementation memory (default), redis, memcached
cache_backend.namespace Prefix exclusive to the environment/application Required for remote, 1–48 alphanumeric/_/- characters, starting with a letter; no PII
cache_backend.key_env Shared HMAC/encryption secret Required for remote, base64 of exactly 32 random bytes
cache_backend.url_env Reference to the URL with authentication Redis only
cache_backend.addresses TCP servers Memcached only, 1–8
cache_backend.timeout Budget for one backend operation Default 250 ms, 10 ms–2 s
cache_backend.max_concurrency Local admission of remote operations Default 16, 1–64
cache_backend.max_entries Ceiling on entries/slots Default 256, 1–256
cache_backend.max_bytes Ceiling on accounted bytes Default 32 MiB, 2 KiB–32 MiB; remote must fit one slot
cache_backend.max_response_bytes Cacheable JSON body Default 64 KiB, 256 B–64 KiB
cache_backend.allow_insecure TCP without TLS, explicitly authorized by the operator Default false
cache_backend.tls.enabled TLS with verification Remote; rediss also enables it
cache_backend.tls.ca_file CAs in addition to the system trust store Regular PEM up to 1 MiB
cache_backend.tls.server_name Name verified in the certificate No skip_verify
cache_backend.tls.cert_file / cache_backend.tls.key_file mTLS client identity Both required when configured

Fields from another adapter are not silently accepted. Invalid configuration, a missing Secret, invalid TLS or an inability to read/write/CAS fail at boot, before the listener. The boot check uses only a synthetic probe with a one-second TTL and the shared marker, without purging existing responses. Creating the Server does no networking. A later cache failure causes a bypass to the provider, within the deadline, without changing authorization, quota or financial usage decisions.

Isolation, storage and purge across replicas

Section titled “Isolation, storage and purge across replicas”

Replicas share the namespace and the Secret. The Secret derives different keys for HMAC and AES-256-GCM; no payload, token or authentication header appears in entry names or in status metadata. Contents are authenticated/encrypted before being sent to the cache. TLS is still required: encrypting values does not authenticate the transport, commands or server, and does not eliminate improper access to the service.

The HMAC covers configuration, the effective upstream credential, identity/team/key and the credential the client presented, alias, operation, query and the exact payload bytes. Live authorization still happens before the lookup on every request. A revoked key does not use an existing response, and a failure in the identity database is still a 503. Without the flag/opt-in, nothing is cached.

A shared random generation is created with ADD/SET NX and replaced with CAS. A change in configuration identity or a purge changes the generation; restoring a previous configuration does not restore an old generation. Evicting the marker creates another random generation. The lookup checks the generation again after reading/decrypting the entry. A stale callback after a purge can, at worst, occupy a slot that turns into a miss, but it does not return content from an old generation. A request already admitted can complete before the purge; retroactive revocation of bytes already sent is not promised.

Remote backends use fixed slots, with no index or global lock, and without promising a distributed LRU. Effective capacity is min(max_entries, floor(max_bytes / (max_response_bytes + 1024))). The 1 KiB reserve covers the encrypted envelope and bounded metadata. Each digest picks a slot; a collision replaces the slot and causes a miss for the previous occupant. The envelope validates digest/generation/TTL/protocol, and the gateway validates the body again. There are at most that many slots plus one marker and one probe per namespace for the exact cache; the chat answer cache’s keys, when enabled, are separate and bounded by the server’s own maxmemory. Multiple namespaces add up their capacities.

The accounting does not include Redis/Memcached internal structures, sockets, in-flight responses or the Go heap. Configure maximum memory and an eviction policy on the server as well; Redis/Memcached are trusted infrastructure, and a connection guard limits headers to 4 KiB and rejects VALUE/RESP bulk sizes above the limit before handing them to the client decoders. Payloads are streamed to the decoder in chunks; CRLF bytes or header-like bytes inside the body stay intact. RESP3 handshake aggregates accept up to 64 elements, 16 levels and 512 frames per response. The cumulative wire budget is max_response_bytes + 5120 per Redis response or per connection of a Memcached operation, with up to 32 VALUE frames in the latter; this bounds lists/nesting in hostile responses without interpreting the opaque body bytes. Normal/nested HELLO responses and bodies containing CRLF have reverse controls. GETRANGE limits the value a legitimate Redis returns even if another client wrote larger content. This eliminates allocation dictated by a giant value header; it does not certify every possible behavior of a malicious server. The deadline limits network waits. Each value the gateway writes is limited to max_response_bytes + 1024; set the service’s item size and memory limits for this profile. The alias TTL remains 1 s–5 min. An internal timestamp prevents serving expired content even when the Memcached TTL rounds up. Evictions and downtime are misses, never sources of truth.

GET /api/v1/admin/cache returns scope: shared, the backend, effective capacity, usage_known:false, entries:-1 and accounted_bytes:-1: there is no reliable global inventory. The UI shows occupancy as unknown. Counters and process_instance_id remain observations of the replica that answered, not distributed analytics. available represents a bounded check at that moment. DELETE confirms success only after updating the shared generation; a failure returns 503. It does not use FLUSHALL/flush_all and does not affect another namespace. RBAC, same-origin and CSRF are the same as in the local profile.

A gateway restart keeps the remote cache if the Secret/configuration/generation remain compatible. Rotating the Secret requires a coordinated rollout and a new namespace/purge according to the runbook; old, now unreachable entries expire within five minutes. The cache must not be backed up as a primary system. Persistence, physical retention and disk encryption are the hosted service’s responsibility; AES-GCM does not promise immediate zeroization. Stopping processes must drain requests before closing cache clients.

With distributed_semantic_cache (requires semantic_cache and backend: redis; Memcached is refused), the chat answer cache lives under <namespace>:sc: on this connection instead of PostgreSQL. Why Redis only: a lookup by meaning needs an atomic append-and-trim of the bucket list, a pipelined read of several candidates and bounded range reads of values up to 1 MiB; the Memcached adapter opens a connection per operation and has none of these, so it was not qualified. Its replies are framed against 1 MiB plus 1 KiB and up to 508 list elements, instead of max_response_bytes; each answer is at most 256 KiB plus its vector. The content key, TLS, ACL, timeout and admission are this backend’s; the ACL also needs RPUSH, LTRIM, LRANGE, PTTL and PEXPIRE on the prefix. Boot and console swaps check those primitives on probe keys of their own when the flag is on. Size maxmemory with an LRU policy for it: the number of chat buckets is not bounded by max_entries/max_bytes.

  1. Provision a compatible service, TLS and ACL/private network; determine memory and maximum item size. Generate a random base64 32-byte Secret outside YAML/Git. Mount CA/mTLS through a Secret when needed.
  2. Use an exclusive namespace and the same connection/Secret/list on all replicas. Configure flags and alias policy in the versioned YAML/base. Roll out atomically using the chosen deployment mode.
  3. Verify a healthy boot and the status without exposing the connection. Send two identical, authorized synthetic requests with X-Gateway-Cache: allow, aimed at different replicas: the first is a miss, the second a hit. Do not use administrator keys for inference.
  4. Purge through the authorized UI/API and repeat: it must go back to a miss on any replica. Test cache unavailability and revoked authorization separately: the first passes through, the second must deny before the provider.
  5. To roll back, turn off exact_cache, publish a backend: memory configuration with no remote connection and without distributed_exact_cache, and roll out. With a console override, DELETE /api/v1/admin/cache-backend goes back to the YAML without a rollout. Do not change boot flags without a rollout. Authentication, the database and the ledger remain independent of the cache. Wait for the maximum TTL before removing old infrastructure/Secrets; never deliberately reintroduce an old Secret/namespace with unexpired data.

Clients: github.com/redis/go-redis/v9 and github.com/bradfitz/gomemcache, at the versions pinned in go.mod.

Test with the real gateway, local Redis 7 and an embeddings alias with caching:

  • Repeated requests go miss → hit; a different request is a miss. That was two calls to the upstream instead of three.
  • The hit survives a gateway restart, because the content is in Redis and not in the process.
  • With Redis paused, the request waits for the timeout (250 ms), goes on to the upstream with no cache header and responds 200.

Real Redis 7.4 and Memcached 1.6 passed with two gateway replicas and a TLS/mTLS tunnel, including a private CA, a wrong hostname and a client without a certificate. This validates the protocol; managed services (Memorystore, ElastiCache) have not been qualified.

Official references: Go Redis client, SET/NX/TTL, EVAL, Memcached guide and CAS, Memcached TLS, gomemcache client.

The optional adapters were exercised against the digest-pinned Redis 7.4.11 and Memcached 1.6.45 fixtures, including TLS/mTLS tunnels, bounded protocol frames, encrypted slots, generations, purge, concurrency and failure/recovery. Separate native-gateway checks used two replicas and real PostgreSQL to verify memory/remote selection, denied access and keeping the installed adapter after a failed replacement. These are local protocol profiles, not managed-cloud certification. Memory remains the default; selecting another service never provisions it or moves authorization/ledger state into the cache.

Expiry tests first require a successful write and a positive hit. A Go virtual clock proves the logical cutoff; real services separately report a finite TTL and receive a checked explicit expiry command. This avoids timing-based pass conditions and does not claim a natural five-minute wait. The tests detect both a failed write and a removed logical-expiry guard. See Redis expiry and Memcached expiry/meta TTL.

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
POST /api/v1/admin/cache/ping Checks the shared cache now, with a timed result for each step

m7gtwcontact@m7gtw.com