Mental model
Tiered LLM caching reduces inference latency and token spend by routing requests through deterministic L1 exact-key caches and KV prefix memory before attempting probabilistic L2 semantic vector lookups. Because embedding similarity cannot reliably separate negated intents or changed numeric thresholds, safe L2 reuse requires strict cosine gates, tenant/role key salting, and corpus epoch invalidation.
Theory
Production AI systems serve a heavy-tailed query stream where repeated policy lookups, shared tool schemas, and minor phrasing variations drive redundant GPU compute. A safe caching architecture partitions reuse across three distinct mechanisms with strictly different correctness guarantees:
- L1 Exact Hash Cache: Canonicalizes whitespace/casing and computes a deterministic SHA-256 digest over
(normalized_query, model_id, prompt_version, tenant_id, acl_role_hash, corpus_epoch). Backed by Redis with RESP3 client-side caching (CLIENT TRACKING), exact hits resolve in under2mswith zero semantic ambiguity. - L2 Semantic Vector Cache: Embeds the incoming query and runs an HNSW nearest-neighbor lookup in Redis against recently cached
(query_vector, response)records constrained to matching metadata tags (tenant_id,corpus_epoch,acl_tier). A response is reused only if (typically0.96–0.98). - Provider KV / Context Prefix Caching: Caches the prefilled key-value attention tensors of long immutable system instructions, tool schemas, and reference documents (typically
1,024+tokens pinned byte-identically at position0). Unlike L1/L2 response caches, KV prefix caching computes fresh output tokens conditioned on the unique user suffix, avoiding false-hit risks while slashing time-to-first-token (TTFT) and input token billing.
False-Positive Blast Radius & Quantitative Economics
Let be the L1 exact hit rate, the L2 semantic hit rate, the false-positive equivalence probability at cosine threshold , and the expected remediation cost of serving a wrong answer. Effective per-request cost becomes:
Consider an assistant handling 1,000,000 queries/day at \$0.008 per uncached completion ($8,000/day). At h1 = 0.18 (exact FAQ hits costing \$0.00001 each) and h2 = 0.22 (semantic hits at tau = 0.97 costing \$0.0002 for embedding + ANN lookup), gross LLM spend drops by (0.18 + 0.22) × \$8,000 − \$46 to save $3,154/day (39.4%). However, relaxing from 0.97 to 0.90 to chase h2 = 0.35 exposes a severe threshold blast radius: pairs like "cancel my enterprise plan" vs "renew my enterprise plan", or "grace period is 14 days" vs "grace period is 30 days", routinely score 0.91–0.94 cosine similarity. If rises from 0.05% (110 bad hits/day) to 3.5% (12,250 wrong answers/day), even a modest \$0.50 support-escalation cost per bad answer ($6,125/day) wipes out the entire compute savings.
Tenant Salting and Epoch Invalidation
Multi-tenant leaks occur when an L2 cache matches a shared question ("What is our Q4 revenue target?") across different tenant_id or acl_role boundaries. Every L1 key hash and L2 vector metadata pre-filter must salt on (tenant_id, acl_scope_hash, model_id, prompt_version).
To purge stale completions instantaneously after a knowledge-base edit or policy change without scanning millions of Redis keys (KEYS * or SCAN), store a lightweight integer corpus_epoch per domain in Redis (and subscribe via RESP3 client-side tracking). Bumping corpus_epoch from 42 to 43 invalidates all prior L1 and L2 entries in atomic time while old keys expire quietly via TTL.
Trade-offs
Caching choices trade hit rate against precision guarantees, security isolation, and memory overhead.
| Cache Tier | Hit Trigger | False-Hit Risk | Security Scope Key | Typical Savings & Latency |
|---|---|---|---|---|
| L1 Exact + RESP3 Tracking | Byte-identical normalized key | Zero | Mandatory (tenant, acl_hash, epoch) | 100x+ speedup (< 2ms), 10–25% hit rate |
| L2 Semantic Vector (Redis HNSW) | cosine >= 0.97 + tag pre-filter | Moderate–High (negations/numbers) | Public / role-bucketed non-PII scopes | 15–40x speedup (5–15ms), 15–30% extra hits |
| KV / Context Prefix Cache | Byte-identical prefix tokens | Zero (fresh decoding on suffix) | Prefix content digest + provider isolation | 2–4x TTFT reduction, 50–90% cached input discount |
Volatile workflows—live order balances, tool-mutating actions, or personalized financial advice—must bypass L2 semantic caching completely (cache_policy = "bypass" or L1-only with 5s TTL) because embedding distance never captures mutable real-time state.
Failure modes and misconceptions
Sharing an L2 semantic vector space without mandatory tenant and ACL pre-filtering. Returning an HR or compliance completion generated for Tenant A to a semantically similar query from Tenant B constitutes an immediate cross-tenant data breach.
Using cosine thresholds below 0.95 on queries containing numbers, dates, or negation. Dense bi-encoders place "exclude VAT" and "include VAT" or "limit 100" and "limit 500" within 0.91–0.94 cosine similarity, producing confident, wrong cached replies.
Polluting KV prefix caches with per-request timestamps or unordered tool schemas. Injecting Current time: 13:04:22 or randomly sorted JSON keys at token index 0 shifts every downstream attention position and forces 0% prefix cache hits.
Reporting blended cached+uncached P50 latency as uncached inference capacity. High cache hit rates mask downstream GPU saturation; when a corpus_epoch bump triggers a cold cache stampede, uncached traffic can overwhelm inference workers unless single-flight request coalescing (lock/dedup) protects origin LLM calls.
Decision scenario
A SaaS customer-support copilot serves 400K daily queries across 1,200 enterprise accounts (55% public product FAQ questions, 45% private account/billing queries). Public FAQs repeat heavily with slight phrasing variation, whereas account queries reference user IDs and live invoice states. Enable deterministic KV prefix caching across all traffic by pinning static system instructions and tool JSON schemas first (1,800 tokens), enable L1 exact hash caching (TTL = 10 min) salted by (tenant_id, acl_role, corpus_epoch) on deterministic lookups, and restrict L2 Redis HNSW semantic caching (cosine >= 0.975) strictly to the unauthenticated/public FAQ route with an automated regex bypass whenever numbers, dates, or account IDs appear in the query.
Learning outcomes
- Architect a three-tier LLM cache combining L1 exact hashes with RESP3 tracking, L2 semantic HNSW lookups, and KV prefix caching.
- Quantify the economic trade-off between L2 cache hit rate and false-positive blast radius on negated or numerical queries.
- Enforce tenant/ACL key salting and
corpus_epochinvalidation to prevent cross-tenant leaks and stale policy answers.
Implementation example
This Python tiered cache checks an L1 exact SHA-256 key salted with tenant scope and corpus_epoch, bypasses L2 semantic lookup on numeric/volatile queries, and enforces a strict 0.975 cosine gate before reusing a cached completion.
pythonimport hashlib, json, reNUMERIC_OR_NEGATION_RE = re.compile(r"\b(\d+|not|never|except|cancel|renew|without)\b", re.I)class TieredLlmCache:def __init__(self, redis_client, embed_fn, sim_threshold: float = 0.975, ttl_sec: int = 3600):self.redis = redis_clientself.embed = embed_fnself.sim_threshold = sim_thresholdself.ttl_sec = ttl_secdef _scope_key(self, query: str, tenant_id: str, acl_role: str, model_id: str, epoch: int) -> str:norm = " ".join(query.strip().lower().split())payload = json.dumps([norm, tenant_id, acl_role, model_id, epoch], separators=(",", ":"))return f"llm:l1:{tenant_id}:e{epoch}:{hashlib.sha256(payload.encode()).hexdigest()}"def lookup(self, query: str, tenant_id: str, acl_role: str, model_id: str, domain: str) -> str | None:epoch = int(self.redis.get(f"llm:epoch:{domain}") or 1)l1_key = self._scope_key(query, tenant_id, acl_role, model_id, epoch)if exact := self.redis.get(l1_key):return exact.decode("utf-8")if NUMERIC_OR_NEGATION_RE.search(query):return None # Bypass L2 semantic reuse when numbers or negations flip intentq_vec = self.embed(query)match = self.redis.vector_search(vec=q_vec,filters={"tenant_id": tenant_id, "acl_role": acl_role, "epoch": epoch},top_k=1,)if match and match[0]["cosine_sim"] >= self.sim_threshold:return match[0]["completion"]return None
Why must L1 and L2 LLM cache keys salt on tenant_id, acl_role, and corpus_epoch, and why do numbers and negation words justify bypassing L2 semantic reuse?