A semantic cache keyed solely by prompt embedding similarity will serve one tenant’s private answer to another tenant—unless the cache key binds caller identity and permission scope, and Valkey ACLs enforce the same boundary.

TL;DR

  • Problem: Semantic caches using Valkey (valkey-search) match incoming prompts by vector cosine similarity; without tenant and role metadata in the key and FT.SEARCH pre-filter, semantically similar queries cross tenant and permission boundaries, and poisoned responses persist for future users.
  • Answer: Key every entry with tenant_id, perm_hash, auth_epoch, and model_id; pre-filter FT.SEARCH on @tenant_id and @perm_hash before KNN ranking; enforce Valkey ACL key-pattern rules (~sc:<tenant>:*) over mandatory TLS; and skip caching for Tier-3 untrusted inputs.
  • Watch out: AWS ElastiCache for Valkey cannot bind RBAC User Groups unless in-transit TLS encryption is enabled, and in Valkey 8.x, key prefixes share a global keyspace—so ACLs must be paired with strict FT.SEARCH pre-filtering.

Semantic caches leak across tenants unless keyed by identity and ACL

Situation

To cut LLM inference latency and token spend, platform teams place a semantic cache in front of their data agents and RAG pipelines using Valkey 8.0/8.1 with the valkey-search module (or Redis-compatible vector search). Instead of exact string matching, the cache embeds the user’s prompt, runs an Approximate Nearest Neighbor (HNSW) search, and returns the cached response whenever cosine similarity crosses a threshold such as 0.95.

That design works safely only when every user sees the exact same public knowledge base. The moment a semantic cache sits in front of multi-tenant databases (Post 4) or permission-filtered RAG indexes (Post 2), the cache becomes a shared-state authorization bypass—classified under OWASP LLM02:2025 (Sensitive Information Disclosure) and LLM08:2025 (Vector and Embedding Weaknesses).

If Tenant A’s VP of Finance asks “Show Q3 revenue summary” and Tenant B’s intern asks “What was Q3 revenue?”, a prompt-only semantic cache scores 0.96 similarity and serves Tenant A’s financial figures to Tenant B without ever hitting PostgreSQL RLS or OpenSearch DLS. Worse, if an attacker triggers a poisoned or hallucinated answer once, the cache replays that poisoned output to every subsequent user whose prompt lands in the same embedding neighborhood.

The Problem

Semantic caches introduce four failure modes that exact-match key-value caches rarely trigger.

Semantic cache lookups cross three identity boundaries

  1. Embedding similarity erases authorization boundaries (TB-1 to TB-2). Vector distance measures phrasing similarity, not who asked the question or which RLS/DLS roles they held. Even within a single tenant, an admin asking “List open security incidents” and a contractor asking “Show current incidents” produce nearly identical embeddings; without a perm_hash in the filter, the contractor receives the admin’s cached output.
  2. Valkey 8.x key prefixes share one global keyspace and vector index (TB-2). In Valkey 8.0 and 8.1, ACL SETUSER ... ~tenantA:* restricts key-level commands (GET, HSET) to keys matching tenantA:* (per-database ACL selectors db=N only arrived later in the Valkey 9.1+ lineage). If a shared valkey-search index spans multiple tenants’ hashes, the query path must also inject a mandatory TAG pre-filter (@tenant_id:{tenantA}) before the HNSW KNN step—never trusting application code to filter results after FT.SEARCH returns.
  3. Stale caches outlive role revocation and document deletion (TB-3). If an employee is removed from the finance-admins group or a confidential document is deleted from PostgreSQL, cached answers derived from that access remain valid in Valkey until their TTL expires—creating a silent privilege-revocation lag.
  4. Managed Valkey authentication differs across clouds. On AWS ElastiCache for Valkey, RBAC User Groups cannot be attached to a cluster unless in-transit TLS encryption (--transit-encryption-enabled) is turned on. On Google Cloud Memorystore for Valkey, IAM authentication (--authorization-mode=iam-auth) uses short-lived OAuth2 tokens via Private Service Connect (requiring TCP 6379 and cluster-bus ports 11000–13047), rather than static ACL SETUSER passwords.

How do you get the latency savings of a Valkey semantic cache without leaking answers across tenants, surviving role revocation, or caching poisoned responses?

Options Considered: ElastiCache vs. Memorystore vs. Self-Managed

Compare how Valkey’s three main deployment models handle RBAC, TLS, IAM, and vector search.

ElastiCache, Memorystore, and self-managed Valkey differ on ACLs

How the Options Compare

DimensionAWS ElastiCache for ValkeyGoogle Cloud Memorystore for ValkeySelf-Managed Valkey 8.0 / 8.1
Authentication & RBACRBAC User Groups (create-user, ~prefix:*, command rules) + IAM authIAM Auth (--authorization-mode=iam-auth, roles/memorystore.dbConnectionUser, OAuth2 AUTH)Native ACL SETUSER with key patterns (~sc:tenant:*) and command categories (+@search)
TLS prerequisiteMandatory for RBAC User Groups (--transit-encryption-mode required)Enforced alongside Private Service Connect (PSC) endpointsSelf-managed TLS certs (tls-port 6379, port 0)
Encryption at restAWS KMS (default or Customer Managed Key)Google-managed or CMEKOS/disk encryption (LUKS / EBS / PD)
Vector search (valkey-search)Managed Valkey vector search support (check engine version availability)Managed Memorystore vector search / Valkey 8.xFull control over valkey-search C++ module (FT.CREATE, FT.SEARCH)
Network isolationVPC private subnets + Security GroupsNative Private Service Connect (gcp-memorystore service class; ports 6379, 11000–13047)Private VPC subnets + Security Groups / NetworkPolicies

Across all three environments, never run a shared semantic cache with default user nopass or ~* wildcard key access. Separate read-only cache lookup credentials from cache-writer credentials, and bind every connection to TLS. On AWS ElastiCache for Valkey, this also means provisioning Customer Managed Keys (CMKs) in AWS KMS for at-rest encryption and explicitly passing --transit-encryption-mode required when creating the replication group, because ElastiCache silently prevents RBAC User Groups from binding to non-TLS clusters. On Google Cloud Memorystore for Valkey, ensure your VPC firewall rules open both TCP 6379 for initial client connections and the dynamic cluster-bus range 11000–13047 for Private Service Connect slot redirects, while granting workloads roles/memorystore.dbConnectionUser so they authenticate with short-lived OAuth2 tokens rather than static secrets.

For teams running self-managed Valkey 8.0 or 8.1 with the valkey-search C++ module, remember that valkey-search indexes Valkey Hashes or Valkey-JSON documents locally per shard. Because key-prefix ACLs (~sc:tenantA:*) only govern direct key operations in Valkey 8.x, the cache gateway must be the sole component constructing FT.SEARCH queries—never accepting raw filter strings from the LLM or client—so every HNSW lookup is deterministically constrained by @tenant_id, @perm_hash, and @auth_epoch before vector similarity scoring runs.

Identity-Scoped Key Design and Valkey ACL Architecture

The target architecture binds identity and authorization state into both the cache key/schema and the Valkey ACL layer.

Identity-scoped keys and Valkey ACLs isolate semantic caches

1. Cache Key and Hash Schema Design

Every cached entry in Valkey Hash storage uses a deterministic key structure that encodes the tenant boundary, permission scope, authorization epoch, and model version:

sc:{tenant_id}:{perm_hash}:{auth_epoch}:{model_id}:{entry_uuid}

  • tenant_id: Derived strictly from the verified OIDC token—never from the prompt. If a tool call supplies a tenant parameter, the gateway ignores it and overwrites it with the authenticated token claim.
  • perm_hash: SHA-256 hash of the caller’s sorted effective roles/groups (e.g., sha256("finance-ro,us-west")). Two users in the same tenant with different permissions never share cache entries, preventing privilege escalation via vector similarity.
  • auth_epoch: A monotonic integer stored per tenant (e.g., epoch:tenantA = 42). When an employee is offboarded or a sensitive document’s ACL changes, incrementing auth_epoch invalidates all prior entries for that tenant in O(1) without running expensive KEYS or SCAN sweeps that stall Valkey’s event loop.
  • model_id: Prevents stale answers when upgrading system prompts or foundation models.

2. Valkey ACL Rules (Read vs. Write Separation + Keyspace Isolation)

Configure distinct Valkey ACL users for cache lookup versus cache population, disabling dangerous administrative commands (FLUSHALL, KEYS, CONFIG, SCRIPT):

# Valkey 8.x ACL rules: tenant-scoped reader and writer (disable default user)
# Passwords are stored as SHA-256 hashes (#<hash>); never put a plaintext secret in a rules file.
ACL SETUSER default off

# Tenant-scoped reader: search + hash read on sc:tenantA:* only
ACL SETUSER sc_reader_tenantA on #<sha256-of-reader-secret> \
  ~sc:tenantA:* \
  +@search +hget +hmget +hgetall -@write -@dangerous

# Cache writer: can write sc:tenantA:* with TTL, cannot flush or scan other tenants
ACL SETUSER sc_writer_tenantA on #<sha256-of-writer-secret> \
  ~sc:tenantA:* \
  +hset +expire +del -@dangerous -keys -flushall -flushdb

On AWS ElastiCache for Valkey, pass the exact same access string (~sc:tenantA:* -@all +@search +hget +hmget +hgetall) to aws elasticache create-user --engine valkey, attach it to a User Group, and enforce --transit-encryption-mode required.

3. Mandatory FT.SEARCH Pre-Filter + Leakage Test

When querying valkey-search, always combine the TAG filter for tenant_id, perm_hash, and auth_epoch before the KNN vector clause so HNSW evaluates only authorized candidates:

FT.SEARCH idx_semantic_cache
  "(@tenant_id:{tenantA} @perm_hash:{a1b2c3} @auth_epoch:[42 42])=>[KNN 1 @prompt_vec $vec AS score]"
  PARAMS 2 vec "\x01\x02..."
  RETURN 3 response_text score trust_tier
  DIALECT 2

To verify isolation continuously in CI/CD (Post 8), include an automated leakage test:

  1. Seed a response under tenant_id = tenantA, perm_hash = admin_hash, auth_epoch = 42 for the prompt “Summarize Q3 confidential revenue”, containing the canary CANARY_TENANT_A_REV.
  2. Query the semantic cache with the near-identical prompt “What was Q3 confidential revenue?” under: (a) tenantB, (b) tenantA with intern_hash, and (c) tenantA with admin_hash after bumping auth_epoch to 43.
  3. Assert Cache MISS and 0 occurrences of CANARY_TENANT_A_REV across all three probes.

Attacker and Defender Threat Matrix

Threat VectorTrust Boundary CrossedAttacker Objective (OWASP / ATLAS)Defender Control (Deterministic)Verification Signal
Cross-tenant similarity hitTB-1 → TB-2 (Prompt → Cache)Retrieve Tenant A’s private answer via similar phrasing (OWASP LLM02)Bind @tenant_id in FT.SEARCH pre-filter + Valkey ACL ~sc:tenant:*Leakage test under tenantB returns Cache MISS (0 results)
Intra-tenant privilege escalationTB-1 (Role → Cache)Intern hits Admin’s cached answer for the same topicInclude perm_hash (sorted OIDC roles) in key & FT.SEARCH TAG filterQuery with intern_hash misses admin_hash entry
Stale hit after user offboardingTB-3 (TTL → Revoked User)Demoted user continues reading cached sensitive answersIncrement auth_epoch on role change + cap TTL (EX 900)Bumping auth_epoch to 43 invalidates epoch 42 entries immediately
Persistent cache poisoningTB-3 (Untrusted → Cache)Poison one answer (via Tier-3 doc) so all future users get hijackedNever cache responses from Tier-3 untrusted inputs or error pathsTier-3 session runs with cache_write = false
Wildcard KEYS * / FLUSHALL abuseTB-2 (Client → Cluster)Dump all tenants’ keys or wipe cache availability (Impact)Omit -@dangerous, -keys, -flushall in Valkey ACLsKEYS * and FLUSHALL return NOPERM error
Unencrypted ElastiCache RBAC bypassTB-2 (Network → Cluster)Sniff credentials or bypass RBAC when TLS is offEnforce --transit-encryption-mode required on ElastiCacheNon-TLS connection on port 6379 is rejected

How It Rolls Out

A deterministic four-step lookup and writeback flow ensures the cache accelerates clean, authorized queries without ever serving stale or cross-tenant data.

Pre-filter hybrid search and bump ACL epochs on role changes

Runtime Lookup and Writeback Flow

  1. 01 Hash Scope: The cache gateway extracts tenant_id and role/group claims from the caller’s verified OIDC token, computes perm_hash, and reads the tenant’s current auth_epoch.
  2. 02 Hybrid Filter: The gateway embeds the prompt and executes FT.SEARCH with mandatory TAG/NUMERIC pre-filters (@tenant_id, @perm_hash, @auth_epoch) before KNN similarity matching (score >= 0.95).
  3. 03 ACL Boundary: The Valkey client authenticates as sc_reader_<tenant> (or per-tenant/per-service RBAC user over TLS / IAM AUTH), ensuring Valkey’s own ACL engine blocks access to any key outside ~sc:<tenant>:*.
  4. 04 Safe Writeback: On a cache miss, the agent executes the full governed pipeline. The gateway writes the result back via sc_writer_<tenant> with a short TTL (EX 900) only if the session touched Tier-1 verified data and produced no policy warnings—never caching Tier-3 untrusted ticket summaries.

Phased Rollout and Rollback Gates

  1. Phase 1 — Enforce TLS, Private Connectivity, and Disable default: Enable --transit-encryption-mode required on ElastiCache or PSC + --authorization-mode=iam-auth on Memorystore, and disable the default Valkey user (ACL SETUSER default off). Gate: Unauthenticated or non-TLS connections are rejected. Rollback: Re-enable preferred TLS mode temporarily only during client migration.
  2. Phase 2 — Deploy Identity-Scoped Schema and Epoch Keys: Update the semantic cache index schema to include tenant_id, perm_hash, auth_epoch, and model_id as indexed TAG/NUMERIC fields. Flush legacy un-scoped cache entries. Gate: 100% of cached entries carry non-null tenant_id and perm_hash. Rollback: Bypass cache (fall back to direct LLM calls) if schema migration fails; never fall back to un-scoped keys.
  3. Phase 3 — Enforce Valkey ACLs and Write Exclusion for Tier-3: Provision sc_reader_* / sc_writer_* ACLs and disable cache writes for any session reading Tier-3 untrusted inputs. Gate: Automated cross-tenant and auth_epoch leakage tests pass with 0 leaks. Rollback: Disable semantic cache reads via feature flag while keeping direct governed execution active.

In Practice

I have not benchmarked every valkey-search cluster size under maximum QPS personally, so the controls above are grounded in official Valkey, AWS, Google Cloud, and OWASP documentation:

  • Valkey ACLs and valkey-search (Pattern A — Official Docs): Per the Valkey ACL documentation and Valkey Search documentation, ACL SETUSER restricts keys by prefix pattern (~prefix:*) and commands by category (+@search, -@dangerous), while valkey-search supports hybrid FT.SEARCH queries combining TAG/NUMERIC filters with HNSW vector similarity. Do not assume key-prefix enforcement on search commands: the valkey-search release notes record a fix for a case where commands were allowed even though the user lacked permission on one of the index prefixes, so pin the version and keep a negative test that proves a tenant-A user cannot retrieve tenant-B entries through FT.SEARCH.
  • AWS ElastiCache for Valkey RBAC prerequisite (Pattern A — AWS Docs): Per AWS ElastiCache RBAC documentation, RBAC User Groups require in-transit encryption (TLS) to be enabled on the replication group.
  • Google Cloud Memorystore for Valkey (Pattern A — Google Cloud Docs): Per Memorystore for Valkey IAM & PSC documentation, instances connect via Private Service Connect (gcp-memorystore, TCP 6379 and 11000–13047) and authenticate via short-lived OAuth2 tokens (roles/memorystore.dbConnectionUser).
  • Disclosure risk (Pattern A — OWASP): OWASP LLM02:2025 (Sensitive Information Disclosure) identifies shared caches and cross-user context reuse as primary vectors for leaking confidential responses.

Where It Breaks

Semantic caches fail via shared keys, stale ACLs, and poisoning

ConditionBreaks HowDetectMitigate
Too-low cosine similarity threshold (e.g., 0.80)Semantically distinct queries (“Delete user X” vs “Describe user X”) collide and return wrong cached responsesHigh false-hit rate or user complaints of mismatched answersSet strict similarity threshold (>= 0.95–0.97) and cache only read-only informational queries
Role-explosion across thousands of usersUnique perm_hash per user drives cache hit rate near 0%Cache hit ratio drops below 5% in metricsScope perm_hash by tenant + role tier (not individual user_id) for shared team docs; skip cache for user-private queries
Multi-tenant valkey-search index without pre-filterApplication forgets @tenant_id in FT.SEARCH, returning Tenant A’s vector match to Tenant BLeakage test fails on cross-tenant probeEnforce FT.SEARCH query construction inside a single trusted gateway wrapper; use dedicated Valkey clusters for regulated tenants
Long TTL (EX 86400) on dynamic database answersAgent serves yesterday’s stock/ticket state from cache even after DB updatesCached response diverges from source-of-record queryKeep semantic cache TTL short (EX 300–900) and do not cache real-time transactional queries
Memorystore cluster-bus ports blockedClient connects to 6379 but fails cluster-slot redirects (MOVED)Connection timeouts during Valkey cluster topology refreshAllow TCP 6379 and 11000–13047 in VPC firewall rules for Memorystore PSC

Key Takeaways

  • Never key a semantic cache by prompt embedding alone: Cosine similarity ignores tenant boundaries, RBAC roles, and data sensitivity.
  • Bind tenant_id, perm_hash, auth_epoch, and model_id: Pre-filter FT.SEARCH on those tags before HNSW KNN ranking so unauthorized entries are never candidates.
  • Enforce Valkey ACLs over mandatory TLS: Separate sc_reader and sc_writer users, scope keys with ~sc:<tenant>:*, disable default and -@dangerous, and enable TLS on ElastiCache so RBAC User Groups work.
  • Use auth_epoch + short TTLs for instant revocation: Incrementing a per-tenant epoch invalidates stale cached answers in O(1) when permissions change.
  • Never cache Tier-3 untrusted sessions: Keep poisoned documents and error responses out of the semantic cache so one bad input cannot hijack future users.

What to Do Next

  • Problem: Multi-tenant semantic caches in Valkey leak confidential answers across users and replay poisoned outputs when keyed solely by embedding similarity.
  • Solution: Add tenant_id, perm_hash, and auth_epoch to every cache key and FT.SEARCH pre-filter, enforce Valkey key-pattern ACLs over TLS, and exclude Tier-3 untrusted sessions from cache writes.
  • Proof: Run the three-part leakage test (cross-tenant, cross-role, and post-epoch-bump) with a CANARY_* response and verify 0 cross-boundary hits.
  • Action: Inspect your Valkey or Redis semantic cache keys this week—if they lack tenant_id and perm_hash in both the key prefix and vector pre-filter, disable shared caching for multi-tenant endpoints until scoped.