11B.3 Caching Strategies
Every LLM call costs money and takes seconds, and most production traffic repeats: the same FAQ, the same document summary, the same system prompt in front of a thousand different questions. Caching is the engineering of not paying twice for the same work — but "the same work" means something different at every layer of an LLM system. A provider can reuse the computed prefix of a prompt (prompt caching); your application can reuse a whole answer for an identical request (exact-match response caching); it can reuse an answer for a similar question (semantic caching); it can reuse embeddings, retrieval results, tool outputs and even in-flight requests. Each layer has its own key, its own TTL, its own failure modes, and its own economics — and getting the key wrong is how a cache turns from a cost saver into a correctness bug. This lesson is the complete map of the caching stack: what each layer saves, how to design keys that are safe, how to tune a semantic cache without shipping wrong answers, how to survive a cache stampede, and when caching quietly loses money.
What you'll learn
- The full caching stack for LLM applications — provider prompt caching, exact-match and semantic response caches, embedding/retrieval/rerank/tool-result caches, self-hosted prefix caching, edge and client caches — and what each layer actually saves
- How to design cache keys that are correct: normalisation, model and prompt versions, generation parameters, tool/state hashes, and the permission scope that must be inside the key, never a post-filter
- Exact-match response caching end to end: backends (memory, SQLite,
diskcache, Redis), TTLs, per-tenant keys, streaming replay, and a production-shapedExactCachewith single-flight - Semantic caching done safely: how it works, every implementation worth knowing as of November 2026 (GPTCache, RedisVL, LiteLLM, Portkey, Cloudflare AI Gateway, Helicone), threshold tuning on a labelled set, and the cross-user leakage risks
- The specialist caches you should link to rather than rebuild: embeddings (06.2), retrieval results (07.2, 07.6, 07.11), tool and API results, self-hosted prefix caching (11C.6), CDN/edge and client-side caches
- Cache economics: the hit-rate × saving − overhead formula, a worked calculator, latency savings, and the cases where caching costs more than it saves
- The failure gallery: staleness, frozen non-deterministic answers, PII in cached values, cache poisoning, thundering herds, negative caching, cache penetration (guaranteed misses), and invalidation strategies
- Request coalescing and response caching in gateways (LiteLLM, Portkey, Cloudflare AI Gateway, Helicone), and when the gateway should own the cache instead of your app
What you don't need
- API keys or any provider account.
llm_service/cache.pyis pure standard library and every demo runs offline; provider and gateway features are taught from their official documentation, dated "as of November 2026". - How provider prompt caching works mechanically. Lesson 03.7, Parts 6–11 owns the per-provider APIs, breakpoints, TTLs, prices and the hit-rate analyser; 02.7, Part 7 owns the KV-cache mechanics. This lesson owns the strategy on top.
- Redis itself. The code uses plain dicts; the Redis/SQLite/diskcache backends are compared, and swapping the store is a five-line change.
- Module 12's security depth. Cache poisoning and PII handling get production rules here; the full threat model is Module 12.
Setup
This lesson's code needs Python 3.11+ and nothing else — llm_service/cache.py uses only the standard library, so every sample runs with python3 cache.py, no uv add, no .env, no keys. If you are building the module's running service, the shared project conventions (the injectable client, the cost tracker, the trace kit) come from 03.11, 03.7 and 11A.1; the cache module drops into that package unchanged. For the optional Redis backend mentioned in 3.4, pip install redis is the only dependency, and it is not required to follow the lesson.
What you must be able to do after this lesson#
- Name the seven cache layers and what each one saves
- Build a correct exact-match cache key with model, prompt version, parameters and permission scope
- Choose a semantic-cache threshold using labelled pairs, and say when semantic caching is forbidden
- Compute the break-even hit rate with hit rate times saving minus overhead
- Prevent a cache stampede with single-flight request coalescing
- Choose an invalidation strategy and avoid PII and poisoned entries in cached values
- Decide between a gateway cache and an application cache
Why this matters for an AI engineer#
Caching is the highest-leverage cost control you have that isn't "use a smaller model". But the word covers at least seven different mechanisms, and the mistakes are asymmetric: a missed cache costs money, while a wrong cache hit costs correctness, trust and sometimes a privacy breach. You'll hear all of these in design reviews and incident post-mortems:
| You'll hear... | You'll understand it after... |
|---|---|
| "Turn on prompt caching, it's free money." | 2.7 When prompt caching loses money |
| "Just cache the response for 24 hours." | 3.5 TTLs and invalidation |
| "The cache key is the user prompt." | 3.2 Key design |
| "Tenant B got tenant A's answer from the cache!" | 3.6 Per-tenant and ACL-scoped keys |
| "Use a semantic cache, hit rate doubles." | 4.5 Suitability by use case |
| "Fifty users asked the same question at once." | 7.6 Cache stampede and 8.1 Coalescing |
| "We cache errors too, right?" | 7.7 Negative caching: don't |
| "Should the gateway or the app own the cache?" | 8.3 App-level vs gateway-level |
| "Our hit rate is 80% but costs went up." | 6.1 The formula — writes and overhead can exceed savings |
| "Cache the embeddings, the retrieval results, the tool calls..." | Part 5: The specialist caches |
| "Prompt caching vs response caching — which one?" | Part 1: The caching stack |
Part 1: The caching stack#
1.1 Seven layers, seven different things#
"Cache" in an LLM system is not one mechanism but a stack of them, each sitting at a different point in the request path and each saving something different. The confusion starts because people use one word for all of them.
flowchart TD
subgraph client ["Client"]
C1["Browser / mobile app"]
end
subgraph edge ["Edge & gateway"]
E1["CDN / edge cache<br/>static AI-generated assets"]
E2["Gateway response cache<br/>exact match: LiteLLM, Portkey,<br/>Cloudflare AI Gateway, Helicone"]
end
subgraph app ["Your service: llm_service"]
A1["Exact-match response cache<br/>scope + model + prompt + params"]
A2["Semantic cache<br/>embedding similarity + scope"]
A3["Specialist caches<br/>retrieval, rerank, tool/API results"]
A4["Request coalescer<br/>single-flight on cold keys"]
end
subgraph upstream ["Upstream"]
P1["Provider prompt cache<br/>KV-prefix reuse (03.7)"]
P2["LLM API / self-hosted server<br/>vLLM APC, SGLang RadixAttention (11C.6)"]
end
C1 --> E1 --> E2 --> A1 --> A2 --> A3 --> A4
A4 --> P1 --> P2
A4 -.->|"open-weight traffic"| P2Reading the diagram top to bottom, a request passes through up to seven cache decisions:
| # | Layer | What is cached | Hit condition | What a hit saves |
|---|---|---|---|---|
| 1 | Client-side | Rendered answer, generated images/audio in the browser | Same user, same screen, TTL or revalidation | Everything — no request at all |
| 2 | CDN / edge | Static AI-generated assets (images, PDFs, audio) keyed by URL | Same URL, cache headers allow it | The whole generation + egress |
| 3 | Gateway response cache | Whole request → whole response, exact match | Byte-identical request body (+ namespace/metadata) | The entire provider call |
| 4 | App exact-match cache | Normalised request → stored response, scoped | Semantically identical inputs (normalised) | The entire provider call, with your TTL and scope rules |
| 5 | App semantic cache | Similar question → stored answer | Embedding cosine ≥ threshold, same scope | The entire provider call, at the price of occasional wrong answers |
| 6 | Specialist caches | Embeddings, retrieval hits, rerank scores, tool/API results | Deterministic key (text hash, query+filters, endpoint+args) | The sub-call's cost and latency inside the request |
| 7 | Provider prompt cache / self-hosted prefix cache | KV cache of an identical prompt prefix | Byte-identical prefix ≥ provider minimum | Most of the input cost and prefill latency — output is still generated |
The ordering matters. Layers 1–5 avoid the provider call entirely; layer 6 makes the surviving calls cheaper; layer 7 makes every call cheaper without changing what you cache at the application level. They compose: a cached answer never reaches the provider's prompt cache, and a prompt-cache hit still pays for output tokens.
1.2 What each layer is for, honestly#
Not every layer belongs in every system. The honest defaults:
- Provider prompt caching is nearly free to enable and should be on wherever the traffic shape supports it — but it only discounts input tokens on repeated prefixes. 03.7 covers the mechanics; Part 2 covers when it loses money.
- Exact-match response caching is the workhorse for FAQ bots, classification, extraction and any deterministic-ish workload. It is the safest app-level cache because a hit means "literally the same request".
- Semantic caching is powerful and dangerous: it trades correctness for hit rate, and it is only appropriate for single-shot, low-stakes, high-repetition traffic. 07.11, §4.3 reached the same conclusion inside RAG; this lesson generalises it.
- Specialist caches are usually obvious wins — embeddings and retrieval results are deterministic functions of their inputs, so caching them is safe once the key is right.
- Edge/CDN and client caches matter when you serve AI-generated assets, not when you call models.
1.3 The two questions every cache design answers#
Before any mechanism, every cache answers two questions, and getting them wrong causes every incident in Part 7:
- What is the key? Everything that can change the answer must be inside it — model, prompt version, generation parameters, the permission scope, and any state the answer depends on (retrieved documents, user profile, current date). Miss one and you serve stale or wrong-scoped answers.
- How long does it live? TTL bounds staleness; version fields in the key bound it more precisely. "Forever" is almost never right for LLM outputs, because the world, the index and the prompt all move.
Everything in this lesson is an elaboration of those two questions per layer.
What this means for you as an engineer: the layers compose rather than compete — a cached answer never reaches the provider's prompt cache, and a prompt-cache hit still pays for output tokens — so each is an independent cost/latency decision, not one switch. A miss costs money while a wrong hit costs correctness, and every layer reduces to the same two questions: what is the key, and how long does it live? Part 2 starts with the layer you may already be paying for without realising it: the provider's prompt cache.
Part 2: Provider prompt caching — strategy, not mechanics#
2.1 Where the boundary falls#
Provider prompt caching is the provider reusing the KV cache of an identical prompt prefix across requests. The mechanics — breakpoints, minimums, lifetimes, prices, per-provider usage fields — are owned by 03.7, Parts 6–9, and the KV-cache intuition by 02.7, Part 7. What this lesson owns is the strategy: how to structure prompts so caching actually hits, how to choose lifetimes, how to warm caches, how caching interacts with multi-turn and agent loops, and when it loses money.
For the why behind the strategy (why only an exact prefix matches, hash chains, per-machine caches, routing) see 11B.4, Parts 1 to 3, and for a table of every provider's rules 11B.4, 4.6b.
2.2 Stable-prefix design: the one rule that decides your hit rate#
Prompt caching reuses only an identical prefix, so your hit rate is decided at prompt-assembly time (02.7, 7.2). The layout rule is stable prefix first, volatile suffix last, canonical ordering inside the prefix. 04.6, Part 10 teaches the layout, 11B.4, 2.4 shows why it works, 11B.4, Part 7 is the checklist, and 03.7, 10.4 has a request builder that enforces it. The strategy additions:
- Audit what actually varies per request. The classic cache-killers: a timestamp or request ID in the system prompt, a per-user name injected early, tool definitions from an unordered set, unstable JSON key order, retrieved documents ordered by a per-query score. Each one silently turns every request into a cache write. Relevance ordering belongs in the volatile tail (04.6, 10.2).
- Per-user stable facts are a middle tier. A user's profile is stable within a session but differs across users. High-volume single-user sessions (a long agent run) benefit from caching it; many single-shot users sharing a system prompt don't, because per-user prefixes fragment the cache. Decide per feature.
2.3 TTL and lifetime choice#
Lifetimes and write prices differ by provider (Anthropic 5 minutes or 1 hour, OpenAI 30 minutes or 12 hours on newer models, Gemini explicit caches with a storage charge). 03.7, 6.3 and 11B.4, Part 5 own the arithmetic; the strategy is:
- Match the lifetime to the traffic gap, not the maximum. Interactive chat with seconds between turns wants the short lifetime; a nightly batch over the same documents wants the long one. A 1-hour Anthropic write only pays from the third use inside the hour (11B.4, 5.1).
- Design for the gap, not the average. Reads refresh an Anthropic entry for free, so steady traffic keeps it alive and the lifetime only matters across quiet periods (11B.4, 5.4 compares a keep-warm ping with the 1-hour write).
- Gemini explicit caches suit large stable corpora queried sporadically (a 200K-token manual read by 14 questions over a shift), where storage is small next to re-writing the prefix (11B.4, 5.3). For chat-shaped traffic, implicit caching is the right tool.
- Don't cache what won't repeat. One-off prompts and unique-per-user documents pay the write premium for zero reads (2.7).
2.4 Warm-up and pre-warming#
A cold cache means the first request after a deploy, a quiet period or a prefix change pays full price and full latency, and a burst of concurrent first requests can each pay a write. 03.7, 6.6 and 11B.4, 6.5 own the mechanics of pre-warming. The strategy: warm on deploy (one request per model and major prefix variant) and before predictable bursts such as morning traffic or post-incident recovery. Provider caches are per account, so one warm-up covers every tenant, unlike your app-level caches. And say in the runbook that p99 latency includes cold misses unless you keep the cache warm.
2.5 Breakpoints across multi-turn and agent loops#
Multi-turn conversations and agent loops are where prompt caching earns its keep, and where it silently breaks.
- Append-only is the cache-friendly shape. Each turn's request should be the previous request plus the new exchange. 04.7, Part 9 owns the table of history operations that break the cache; the headline is that trimming the oldest turn breaks the cache from the start of history, while summarising in occasional large batches amortises the break.
- Let the breakpoint follow the conversation. On Anthropic, automatic caching (03.7, 6.1) moves the breakpoint forward as history grows. Use explicit block-level breakpoints when the shared prefix is not the whole history (system prompt plus tools, a different tail every request).
- Agent loops re-send everything each step, so the shared prefix is huge and stable. New tool results are fine (new suffix); editing an earlier result, reordering tool definitions or injecting per-step facts into the system prompt invalidates it (11B.4, 2.5). Keep thinking and effort settings fixed within a session too.
- Cross-request prefix sharing beats per-conversation caching. The biggest wins are across chats that share the system prompt, tool definitions and reference docs (04.6, 10.1).
2.6 Measuring hit rate and savings in production#
The full treatment is in 03.7, Part 10: the five metrics (request hit rate, token hit ratio, write ratio, net saving, prefix churn) and a hit-rate analyser you can run. The per-provider formulas are in 11B.4, 8.1. What this lesson adds is the production loop:
- Emit the metrics per feature and put them on the dashboard 11A.2 owns. A feature with a stable prefix should show a high token hit ratio; near zero means the prefix is churning.
- Alert on prefix churn, not just hit rate. A deploy that puts a timestamp or version string into the system prompt does not drop the hit rate immediately (old entries still hit until they expire) but new writes are never read. Prefix churn catches it within minutes.
- The counterfactual is the number that matters. Net saving is cost-without-caching minus actual cost, after write premiums (Part 6 here generalises it to every layer). Per-feature numbers justify, or kill, the write premium on marginal prefixes: FAQ bots with stable prefixes typically save 60 to 90 percent of input cost, chat with per-user context saves little.
2.7 When prompt caching loses money#
Caching is not free even when it works. The full treatment is in 11B.4, Part 5: the break-even formula and the eight loss cases (5.2). 03.7, 11.3 lists the cases where you should not cache at all. In short: prefixes that are written and never re-read, churning "stable" prefixes (a timestamp or per-request ordering turns every request into a write), a long lifetime bought for traffic that would have refreshed a short one, Gemini explicit-cache storage kept for few queries, prompts below the provider minimum (nothing is cached), and cold paths where a miss is slower than not trying.
2.8 Provider-side tenancy: shared per account, not per user#
Everything above treats the provider cache as a mechanism to optimise. Its entries are also shared: every request your account sends, for every end user, draws on the same cache, and the isolation boundary is your provider account structure, not your users. 03.7, 9.4 tabulates it (per organization on OpenAI, per workspace on Anthropic's Claude API, per project on Gemini, per account on OpenRouter) and 6.7 has the Anthropic detail. Three consequences:
- A hit requires a byte-identical prefix, so casual leakage needs sensitive data inside the shared prefix, which is exactly what 2.2's audit pushes out. Keep user data out of the stable prefix and the shared cache is safe by construction.
- Cache-hit probing is documented research, not folklore. A hit returns faster than a miss, so an attacker timing responses can infer whether another tenant recently sent a given prefix (the attack that motivated
cache_salton self-hosted serving, 11B.4, 4.6; Module 12 owns the threat model). Mitigations: a per-tenantprompt_cache_keyon OpenAI GPT-5.6 and later (03.7, 7.2; a routing hint only on earlier models), or separate Anthropic workspaces at the cost of shared hits on your common prefix (03.7, 6.7). - The knobs are hints, not boundaries.
prompt_cache_keyand similar session or routing fields steer accounting; they are not a hard isolation boundary the way separate workspaces or a self-hosted salt are. If your threat model needs a guarantee, isolate at the account or workspace layer and accept the lower hit rate.
What this means for you as an engineer: prompt caching is a prompt-layout feature, not a flag. The work is auditing what varies per request, pushing it to the tail, canonicalising the stable part, matching lifetimes to traffic gaps, warming before bursts, and measuring net saving per feature. Do that and it is the cheapest latency and cost win in the stack; skip it and you're paying write premiums for misses.
Part 3: Exact-match response caching#
3.1 When an answer may be frozen#
An exact-match response cache stores the whole provider response and replays it when the same request arrives again. It is the app-level equivalent of an HTTP cache for LLM calls — and like HTTP caching, it is only correct when the answer is a pure function of the request.
The workloads where it shines:
- FAQ and support bots — "what's the refund policy?" asked identically a thousand times a day.
- Classification and extraction — ticket routing, entity extraction, content moderation: same input shape, deterministic-ish output, high volume.
- Document Q&A over a stable corpus — the same question about the same manual version.
- Generated assets with stable inputs — a product description template filled with the same SKU data.
- Retry/dedup safety — the same request fired twice by a client bug or a retry storm is served once.
The workloads where it fails:
- Conversational, personalised or stateful traffic — the "same" question means something different in different sessions; the answer depends on history, user profile, retrieved documents and current state that aren't in a naive key.
- Answers that should reflect now — "what's the weather", "any updates on my order", anything whose truth changes faster than your TTL.
- High-entropy creative output — poem, story, brainstorm: identical prompts should give different answers; freezing one is a product bug, not a cache win.
3.2 Key design: the full anatomy#
The cache key is the contract. Everything that can change the answer must be inside it; anything inside it that doesn't change the answer costs you hit rate. The anatomy, from most to least important:
| Component | Why it's in the key | Example |
|---|---|---|
| Permission scope | A hit must never cross an ACL/tenant boundary | tenant-a, user-123, role:admin — hash it, never store raw |
| Model + provider | Different models = different answers; a model swap must invalidate | openai/gpt-6-luna, anthropic/claude-haiku-5-5 |
| Prompt/template version | A prompt edit changes answers; version in key = free invalidation | prompt-v14, extractor@sha256:… (04.10 owns versioning) |
| Generation params | temperature, max_tokens, seed, top_p, reasoning effort — all change output | {"max_tokens": 200, "seed": 42} |
| Tool/state hash | Answers that depend on retrieved docs, user state, current data | index_version, doc_ids hash, state_version |
| The normalised request | The actual messages/prompt, canonicalised | sorted JSON, normalised text |
The scope goes inside the key hash — never as a post-filter. A post-filter ("fetch the entry, then check if the scope matches") still reveals that an entry exists and invites timing/leakage bugs; a scope inside the hash means tenant B's lookup simply misses because the key is different (07.11, §4.3 made the same rule for RAG). The request_key function in llm_service/cache.py (8.4) implements exactly this anatomy — provider keeps same-named models on different providers from colliding, and deps is where index_version, tool versions and state hashes go.
3.3 Normalisation: what counts as "the same request"#
Exact match is only as exact as your normaliser. The layers, from safest to most aggressive:
| Level | What it does | Risk |
|---|---|---|
| Byte-exact | Hash the raw request body | Misses on trivial differences (whitespace, key order); safest, lowest hit rate |
| Canonical JSON | Parse body, sort_keys, normalise whitespace in strings |
Misses on punctuation/case; still very safe |
| Text-normalised | Lowercase, fold accents to ASCII (café→cafe), keep [a-z0-9] runs, collapse whitespace |
"Same" question in different cases or accent forms hits; small risk of merging genuinely different inputs |
| Semantic | Embed and match by similarity | This is Part 4, a different cache with different risks |
For LLM requests, text-normalised is the sweet spot for chat-shaped input: it absorbs the differences that don't change intent (case, trailing punctuation, extra spaces) while staying conservative. Do not normalise away meaning — don't stem, don't remove stopwords, don't reorder messages. Two requests that differ only in normalisation-insignificant ways get the same answer; anything more aggressive belongs in the semantic layer where the threshold is explicit.
3.4 Backends: memory, SQLite, diskcache, Redis#
The cache is a key→value store with TTL and size bounds. The backend choice is an operations decision, not a correctness one — the key design is identical.
| Backend | Good for | Watch out for | Version (Nov 2026) |
|---|---|---|---|
| In-process dict | Single-process dev, tests, small services | Lost on restart; not shared across workers/replicas; memory bound | stdlib |
SQLite (sqlite3) |
Single-node services, moderate scale, persistence | One writer at a time; fine to millions of rows; file on disk | stdlib |
diskcache |
Persistent local cache with eviction policies (LRU/LFU), Django-compatible API, stampede-safe memoize_stampede |
Still single-node; disk I/O | diskcache 5.6.3 |
| Redis / Valkey | Multi-worker, multi-replica, shared across services; TTL and eviction native | Another service to run; memory cost; network hop (~1ms vs ~µs) | server-side |
| The gateway's cache | Zero app code; LiteLLM/Portkey/Cloudflare/Helicone response caches (8.2) | Less control over key/scope/TTL; see 8.3 | per gateway |
The ExactCache in cache.py takes any mapping with get/set/delete; swapping the in-memory dict for Redis is a thin adapter (redis.get/set with ex=ttl). 3.7's CachingEmbedder uses SQLite for the same reason — show the interface, swap the store.
3.5 TTLs and invalidation#
TTL bounds staleness; the key's version fields bound it precisely. The strategies, roughly in order of preference:
- Versioned keys (best). Put
prompt_version,model,index_versionin the key. A deploy or reindex changes the key space; old entries are never hit and can be garbage-collected by age. No explicit invalidation needed — the version is the invalidation. - TTL (necessary). Even with versioned keys, TTL bounds memory and catches changes you didn't version (a data source that updates without a version bump, a policy that changed). Choose TTL ≈ "how stale can this answer be before it's wrong" — minutes for fast-moving data, hours/days for stable FAQs, never "forever" for anything touching the real world.
- Event-driven invalidation (for high-value entries). When a document is deleted or edited, kill every cached answer that depended on it — 07.11's
invalidate_docpattern: the entry carries thedoc_idsit cited, and a delete event drops those keys. For erasure requests, this is also the privacy path (7.4). - Explicit flush (last resort).
FLUSHDB/cache.clear()on deploy — blunt, loses everything, but simple. Prefer versioned keys so you rarely need it.
3.6 Per-tenant and ACL-scoped keys#
The single most dangerous cache bug is serving one user's answer to another. The rules:
- Scope is inside the key.
request_key(scope=...)hashes the permission boundary into the key; tenant B's identical question produces a different key and misses. Never fetch-then-check. - Scope is the authorization boundary, not the user ID. Two users with the same permissions can share entries (better hit rate); two users with different permissions must not. Use role/tenant/group-derived scope strings, hashed.
- Cached values can contain scoped data. An answer generated for tenant A may quote tenant A's documents — storing it under a shared key leaks it. The scope-in-key rule prevents the lookup leak; also ensure the stored value doesn't embed cross-scope data (it can't, if the request that produced it was scoped).
- Test it. 07.11's demo shows alice and bob getting different keys for the same question — replicate that test for your cache.
3.7 Streaming responses: replay vs bypass#
LLM responses often stream (SSE). A cached streaming response can be replayed — but the mechanics differ:
- Replay the stored event stream. Store the sequence of stream events (or the final assembled text plus timing metadata) and re-emit it with the same SSE framing. The client sees a normal stream; latency is ~0. 03.3 owns the streaming protocol; the cache stores the events, not the raw socket bytes.
- Or bypass streaming on hits. Simpler: on a cache hit, return the complete response as one non-streaming reply (or a single SSE event). The client already handles both; the "stream" was instantaneous anyway. Decide per endpoint — interactive UIs that show token-by-token progress may prefer replay; API consumers prefer the simple path.
- Never cache partial streams. A stream that errored or was truncated mid-way must not be stored — only complete, successful responses. The
devcache.pyrule from 03.10 applies: only200/complete responses are cached; errors are never cached (7.7).
3.8 The llm_service/cache.py exact-cache code#
The full file is in 8.4; the exact-cache pieces:
# llm_service/cache.py — excerpts (the complete file is at the end of Part 8)
@dataclass
class _Entry:
value: Any
expires_at: float
class ExactCache:
"""Request -> response cache with TTL, size bound and single-flight.
``None`` is never a hit — a stored ``None`` is indistinguishable from a
miss, so treat ``None`` as "no answer" upstream and don't cache it.
"""
def __init__(self, ttl_seconds=3600.0, max_entries=10_000, store=None):
self.ttl = ttl_seconds
self.max_entries = max_entries
self._store = store if store is not None else {}
self.stats = CacheStats()
self._inflight: dict[str, asyncio.Task[Any]] = {}
async def get_or_compute(self, key, compute):
hit = self.get(key)
if hit is not None:
self.stats.hits += 1
return hit
task = self._inflight.get(key)
if task is not None:
self.stats.coalesced += 1
self.stats.hits += 1
return await asyncio.shield(task) # one waiter leaving must not cancel the rest
self.stats.misses += 1
task = asyncio.ensure_future(self._compute_and_store(key, compute))
self._inflight[key] = task
task.add_done_callback(lambda t, k=key: self._finish(k, t))
return await asyncio.shield(task)
def _finish(self, key, task):
self._inflight.pop(key, None)
if not task.cancelled():
task.exception() # mark retrieved: no "never retrieved" warning if every waiter left
async def _compute_and_store(self, key, compute):
try:
value = await compute()
except BaseException:
self.stats.errors += 1
raise # never cache failures
self.put(key, value)
return valueThree properties matter: single-flight (the _inflight dict — 20 concurrent identical misses cost one compute, shown in the 8.4 demo), never-cache-errors (the except re-raises without storing), and TTL + size bound (expiry on read, oldest-evict on write).
What this means for you as an engineer: exact-match caching is the safest app-level cache because a hit means "literally the same request". The entire correctness burden is the key: scope inside the hash, versions inside the key, normalisation before hashing, and TTL for the drift you can't version. Get the key right and it's a pure win; get it wrong and it's a correctness incident.
Part 4: Semantic caching#
4.1 How it works#
A semantic cache relaxes exact match: instead of hashing the request, it embeds the query into a vector, finds the nearest stored query by cosine similarity, and serves the stored answer when similarity clears a threshold. "How do I get a refund?" and "what's your refund policy?" are different bytes but nearby vectors — a semantic cache hits where an exact cache misses.
The mechanism has three cost centres an exact cache doesn't:
- An embedding call per lookup — you pay to embed the incoming query before you can decide hit/miss (unless you cache query embeddings too, 06.2, 5.5). This is usually cheap relative to a generation call but not free.
- A vector search per lookup — nearest-neighbour over stored queries; milliseconds with an index, brute-force fine for thousands of entries.
- Wrong-answer risk — the threshold trades hit rate against false hits. A false hit serves an answer to a different question, which is worse than a miss.
4.2 The implementations, verified as of November 2026#
| Implementation | What it is | Licence / status | Watch out for |
|---|---|---|---|
GPTCache (PyPI gptcache 0.1.44) |
The best-known open-source semantic cache: pluggable embedder, vector store, similarity evaluator, eviction | MIT; repo still commits (Sep 2026) but README says "we no longer add support for new API or models" — use the get/set API |
No new provider adapters; several open security issues incl. unsafe-YAML RCE reports (#687, #676) — pin and audit; similarity threshold ~0.8 in examples is a starting point, not truth |
RedisVL SemanticCache (redisvl 0.30.0) |
Redis-native semantic cache: SemanticCache(name, distance_threshold, ttl, vectorizer); store()/check(); filterable_fields for scoped lookup; LangCacheSemanticCache hosted option |
MIT, Redis Inc. | distance_threshold is Redis COSINE distance [0–2], lower is stricter (default 0.1) — opposite convention to similarity thresholds; needs Redis with vector search (Redis Stack, or Redis 8+/Redis Cloud) |
| redis-py guide | Redis's own docs walk through a hash-per-entry semantic cache: embedding + metadata in a Redis Hash, FT.SEARCH KNN + TAG pre-filter in one round trip |
Documentation pattern | You build the threshold logic yourself — full control, more code |
| LiteLLM proxy | Gateway-level: cache_params.type = redis-semantic, valkey-semantic, qdrant-semantic; similarity_threshold (0.8 in docs); embeds the whole messages array |
LiteLLM proxy feature | Explicit warning: designed for single-shot prompts; replays stale answers on multi-turn/agentic traffic. Requests over max_messages (default 4) are neither looked up nor stored. Hit carries x-litellm-semantic-similarity header |
| Portkey | Gateway config cache: {mode: "semantic"}; cosine similarity; superset of simple cache (exact match first) |
Portkey AI gateway; semantic mode on select Enterprise plans | Works only on requests <8,191 tokens and ≤4 messages; x-portkey-cache-namespace scopes it |
| Cloudflare AI Gateway | Response caching at the edge; cache_ttl, cf-aig-cache-key, cf-aig-skip-cache |
Cloudflare | Identical requests only — no semantic mode yet ("we plan on adding semantic search"); text and image responses |
| Helicone | Edge response cache on Cloudflare Workers KV; Helicone-Cache-Enabled, Helicone-Cache-Seed, bucketed multi-response cache |
Helicone | Cache key = seed + URL + body + auth/cache headers + bucket index; exact-match semantics, not semantic (the helicone/ai-gateway README documents Redis/S3 backends — a different surface) |
The pattern across all of them: embed → vector-search → threshold → serve. The differences are the store (Redis/Qdrant/SQLite/vector DB), the threshold convention (similarity vs distance), the scope mechanism (filters vs key prefix vs namespace), and who owns the embedding call.
4.3 Threshold tuning on a labelled set#
The only honest way to pick a threshold is to measure it on your data. The method:
- Build a labelled set: pairs of (query, stored_query, should_hit?) — "refund policy?" vs "how do refunds work" = hit; "refund policy?" vs "sick leave policy" = miss. Include the borderline cases that actually occur in your traffic.
- Compute the similarity for each pair at lookup time (your
nearest()returns the raw score). - Sweep the threshold and plot hit rate vs false-hit rate. Pick the point where false hits ≈ 0 (or whatever your risk budget allows) while hit rate is still useful.
- Re-tune when the embedder, the question mix or the cost of a wrong answer changes.
The SemanticCache.nearest() method in cache.py exists precisely for this: it returns (value, similarity) without applying the threshold, so you can log the score distribution and tune offline. In production, log every semantic lookup's top score — the histogram tells you where your threshold sits and whether it's drifting.
4.4 False hits: what a wrong cache hit costs#
A semantic-cache false hit serves an answer to a different question. The cost is asymmetric:
- Exact cache false hit: impossible by construction (same key = same request).
- Semantic cache false hit: the user gets a plausible-sounding answer to the wrong question. For an FAQ bot that's a wrong policy; for a medical-style FAQ it's a wrong dosage; for a coding assistant it's a wrong API. The blast radius depends on what the cached answers do.
Mitigations, in order of effectiveness:
- High threshold + labelled-set tuning — the baseline.
- Narrow the cacheable surface — only cache answers that are generic (FAQs, definitions, stable policies), never personalised, transactional or high-stakes answers. Scope the cacheable intent classes explicitly.
- Store provenance and re-verify on borderline hits — for similarities in a "grey zone" (say 0.75–0.85), don't serve blindly: re-run a cheap validator or escalate to the LLM. Two-tier threshold.
- Never semantic-cache across scope boundaries — the scope check runs before similarity, so a hit can never leak across tenants (4.6 and 4.7).
- Eval-gate the threshold — before enabling in production, run your eval set with the cache on and measure answer-correctness with cache hits vs without: deterministic/exact-match graders in 10A.3, CI eval-gates in 10A.8 (Module 10A owns evals). A threshold that drops correctness below your SLO isn't worth the hit rate.
4.5 Suitability by use case#
| Use case | Semantic cache? | Why |
|---|---|---|
| FAQ bot, single-shot | ✅ Yes, tuned | High repetition, low stakes per hit, paraphrases common |
| Classification/routing | ⚠️ Maybe | Only if classes are few and embeddings separate them; else exact-match on normalised input |
| Conversational RAG | ❌ No | "What about contractors?" is semantically close to a cached full-time answer but contextually different — the threshold can't see session state (07.11, 4.3.2) |
| Personalised assistant | ❌ No | Answers depend on user state not in the query |
| Agentic/tool-calling traffic | ❌ No | LiteLLM's explicit warning: replays stale answers on multi-turn/agentic traffic; each turn's context differs |
| High-stakes (medical, legal, financial advice) | ❌ No or very high threshold | A wrong hit is worse than a miss; the cost of a wrong answer dwarfs the savings |
| Creative/open-ended generation | ❌ No | Identical prompts should vary; freezing is a product bug |
The decision rule: semantic caching is for single-shot, low-stakes, high-repetition traffic where a wrong answer is recoverable. Everything else uses exact-match or no cache.
4.6 Invalidation and versioning#
Semantic caches need the same invalidation discipline as exact caches, plus one extra problem: the embedding space itself.
- Version the embedder and the answer-space together. If you change the embedding model, every stored vector is in a different space — similarities become meaningless. Put the embedder model+version in the cache's key space (or flush on change). 06.2, 5.6 owns this for embedding caches; the same rule applies to the query-side cache.
- Version the answers. A prompt change or index update that alters answers must invalidate stored responses — same
prompt_version/index_versionin the entry metadata, flush or key-partition on change. - TTL bounds drift. Even with versioning, TTL catches unversioned changes (a policy document updated without a version bump).
- Scope-partition the store. Store
scopeon every entry and filter before similarity — a hit can never cross tenants.
4.7 Privacy and cross-user leakage#
Semantic caching has a privacy wrinkle exact caching doesn't: the cache stores queries, which can be sensitive ("what's my account balance?", "is my diagnosis covered?"). Rules:
- Scope before similarity — the lookup filters by scope first, so tenant A's query vectors are never compared against tenant B's entries.
- Hash or encrypt stored queries — the vector is derived from the query; if the raw query is also stored (for debugging), encrypt it or hash it. The vector itself can leak information via inversion attacks on small embedding models — treat stored vectors as sensitive.
- Short TTL on query-side caches — queries drift; a stale semantic cache hides that. Hours–days, not forever (06.2, 5.5).
- Deletion propagates — an erasure request must reach cached queries and cached answers that embed the user's data (05.9, 9.3 owns the propagation pattern; 7.4 covers the cache side).
- Never share a semantic cache across permission scopes — the blast radius of a bug here is cross-tenant answer leakage, the worst kind.
4.8 Evaluating cache correctness#
A semantic cache is a quality component, so it belongs in your eval loop (Module 10A owns evals — 10A.3 for deterministic correctness graders, 10A.8 for CI eval-gates; this is the cache-specific application):
- Measure hit-rate vs correctness jointly. A 90% hit rate with 5% wrong answers is worse than a 50% hit rate with 0% wrong answers. Track both.
- Label the borderline band. Log every lookup's top similarity; manually review the 0.7–0.9 band to find where false hits live, then set the threshold above it.
- A/B the threshold. Run two thresholds on a traffic slice; compare answer-correctness (judge or exact-match on your eval set) and cost. The eval harness decides, not intuition.
- Watch for distribution shift. A new product launch or seasonal query change shifts the embedding distribution; re-tune.
4.9 The SemanticCache code and demo#
The full SemanticCache, HashingEmbedder and cosine are in cache.py (8.4). The key methods:
# llm_service/cache.py — excerpts
class SemanticCache:
"""Question -> answer cache over embedding similarity, scope-filtered."""
def check(self, query: str, scope: str) -> Any | None:
qv = self._query_vector(query)
best, best_sim = None, -1.0
now = time.time()
for e in self._entries:
if e.scope != scope or e.created_at + self.ttl < now:
continue # scope + TTL filter BEFORE similarity
sim = cosine(qv, e.vector)
if sim > best_sim:
best, best_sim = e, sim
if best is None or best_sim < self.threshold:
self.stats.misses += 1
return None
best.hits += 1
self.stats.hits += 1
return best.value
def nearest(self, query: str, scope: str) -> tuple[Any | None, float]:
"""(value, similarity) of the best in-scope entry — for threshold tuning."""
...The demo output (real — pure stdlib, run python3 cache.py):
semantic [HIT ] sim=0.389 'How can I get my money back?' (scope=public)
served: 'Refunds go to the original payment method within 14 days.'
semantic [miss] sim=0.201 'what is the refund policy' (scope=public)
semantic [miss] sim=0.114 'When does support close on Friday?' (scope=public)
semantic [miss] sim=-1.000 'How do I get a refund?' (scope=tenant-x)Read it carefully — it's a lesson in itself:
- "How can I get my money back?" HIT at 0.389 — a true paraphrase of "How do I get a refund?" caught by the (deliberately weak)
HashingEmbedder. With a real embedding model this scores far higher; the toy embedder shows the mechanism, not the quality. - "what is the refund policy" MISSED at 0.201 — arguably the same intent, but the toy embedder can't tell (it shares only the word "refund"). A real embedder would hit. This is the false-negative side of the threshold dial.
- "When does support close on Friday?" MISSED at 0.114 — correctly below threshold; unrelated to refunds.
- "How do I get a refund?" for tenant-x MISSED at -1.000 — the exact same question that would hit for
publicreturns nothing because the scope filter ran first. This is the cross-tenant isolation working.
The HashingEmbedder is a feature-hashing bag-of-words vectoriser — deterministic, stdlib-only, good enough to demonstrate store/threshold/scope/stats. Production swaps in a real embedding model (the same Embedder seam 06.2 owns).
Scope honesty: SemanticCache is demo-grade — the _entries list stands in for a vector index (production uses RedisVL/Qdrant/pgvector), check() has no single-flight so N concurrent misses each pay an embed + scan, expired entries are skipped on every scan but never removed until FIFO eviction, and store() evicts oldest-first ignoring the hits counter. The fixes are a real index, single-flight on the miss path (7.6), and TTL+score-aware eviction — the class docstring in 8.4 says the same.
What this means for you as an engineer: semantic caching buys hit rate at the price of wrong-answer risk. It's appropriate only for single-shot, low-stakes, high-repetition traffic — FAQ bots, not conversations, agents or high-stakes domains. Tune the threshold on a labelled set, scope before similarity, version the embedder and answers together, and eval-gate the hit-rate-vs-correctness trade-off. Used within those bounds it's a real cost saver; used outside them it's a correctness incident waiting to happen.
Part 5: The specialist caches#
Reference
Not every cache stores answers. Several cache the inputs to the expensive call — embeddings, retrieval results, tool outputs — which are deterministic functions of their inputs and therefore safe to cache once the key is right. Most are already owned by earlier lessons; this part maps them and adds only what's missing.
5.1 Embedding caches → 06.2, Part 5#
06.2 owns the CachingEmbedder: a decorator that serves cache hits locally and sends only unique misses — still batched — to the real embedder, keyed on (model, version, dimensions, task_type, preprocessing_hash, text_hash). The caching-strategy notes:
- The key is the spec. Bump the model version or preprocessing and every key changes — stale vectors are never hit, no flush needed. This is the versioned-key pattern applied to embeddings.
- Dedup inside one call is handled: a text repeated in a batch is embedded once.
- Query-embedding caching has a privacy wrinkle document caching doesn't — it stores what users asked. Short TTL, hashed keys, tenant scoping (06.2, 5.5).
- Embedding calls are usually cheap relative to generation — cache them for cost and latency, but don't over-engineer; the embedder call is often <1% of a RAG request's cost.
5.2 Retrieval result caches → 07.2, 07.6, 07.11#
Retrieval is the other expensive sub-call inside a RAG request. The caches:
- Hot-query cache — 07.2, §8.1 owns
CachedRetriever: memoises(query, k, filters)→ hits with TTL; the filters carry the tenant scope so a hit can't cross ACLs. The strategy note: the key must include the index version — a reindex or embedding-model change invalidates every cached hit set, same versioned-key rule. - Per-session retrieval cache — 07.6, §3.4 owns it: conversational follow-ups re-retrieve overlapping context; a per-session store avoids re-hitting the vector DB every turn.
- Rerank caches — reranking is a per-query scoring call over retrieved candidates; cache
(query, candidate_ids, reranker_version)→ scores. Rerankers are deterministic-ish per version, so versioned keys work. Few lessons own this explicitly — it's a small win but free once the key is right. - The RAG response cache — 07.11, §4.3 owns the production version with
doc_idsinvalidation on delete. This lesson generalises the pattern to non-RAG features.
5.3 Tool and API result caches#
Agents call tools that hit external APIs — and many of those calls are idempotent reads that repeat: "get order status", "lookup product", "fetch exchange rate". Caching them is often the biggest agent-cost win:
- Cache only idempotent reads. GET-like operations with no side effects. Never cache writes, payments, sends — a cached "success" for an action that didn't happen is a correctness and safety bug.
- TTL by freshness. The TTL is "how stale can this data be" — exchange rates minutes, product catalogues hours, user profiles session-length. The data's own freshness SLA decides, not the LLM's.
- Key on the full request: endpoint + normalised args + auth scope + API version. Same key-design rules as response caching.
- Version the upstream. If the external API versions its data or you switch providers, the key's version field invalidates.
- Agents make this subtle: a tool result cached for one agent run may be stale for the next; scope tool-result caches per session or per short TTL unless the data is genuinely static. 08A.6 owns tool design (idempotency keys, safe retries); 08A.14 owns agent reliability — the cache sits between them.
5.4 KV-cache / prefix caching in self-hosted serving → 11C.6#
When you self-host, the provider prompt cache becomes your prefix cache: vLLM's automatic prefix caching (enable_prefix_caching=True) and SGLang's RadixAttention reuse KV blocks for shared prefixes, saving prefill time but not decode. 11B.4, 2.2 explains how they hash and match blocks and 11B.4, 4.6 compares the engines; 11C.6 owns the serving side.
- The strategy is identical to provider prompt caching: stable prefix first, volatile suffix last (Part 2).
- Multi-tenant isolation: self-hosted prefix caches must not share KV across tenants with different data policies. vLLM's
cache_saltsalts the first block's hash so only same-salt requests share entries, to blunt timing-based inference of cached content (vLLM prefix-caching design, verified Nov 2026); check your server's docs for the equivalent. - Multi-tenant isolation: self-hosted prefix caches must not share KV across tenants with different data policies — vLLM's
cache_saltsalts the first block's hash so only same-salt requests share entries, explicitly to blunt timing-based inference of cached content (vLLM prefix-caching design, verified Nov 2026); check your server's docs for the equivalent.
5.5 CDN / edge caching for AI-generated assets#
When your app serves AI-generated content (images, audio, PDFs, video), standard HTTP caching applies:
- Cache the asset, not the generation. A generated image at
/assets/img/abc.pngwithCache-Control: public, max-age=…is cached by CDN and browser like any static file — the generation cost is paid once. - Key the URL by content/version. A stable URL per generated asset; a new generation gets a new URL (or a version param) so caches invalidate naturally.
- AI gateways are not CDNs. Cloudflare AI Gateway caches responses to model API calls (8.2), not your served assets — different layer, don't confuse them.
- Private vs public. Personalised generations shouldn't get
publiccache headers; useprivate+ short max-age or no-store.
5.6 Client-side caching#
The browser/app can cache too:
- Service worker / IndexedDB for repeated views of the same generated content.
- HTTP cache headers on your own API responses (
Cache-Control, ETag) — the client revalidates cheaply. - Optimistic UI: show the cached answer instantly, revalidate in background (stale-while-revalidate pattern).
- Never cache sensitive generations client-side without encryption — a shared device is a leak vector.
What this means for you as an engineer: the specialist caches are mostly owned elsewhere — link to them, don't rebuild. The strategy additions are: version every key on the thing that changes the output (model, index, embedder, upstream API), scope tool-result caches per session, and remember that self-hosted prefix caching is the same stable-prefix problem as provider prompt caching. The wins are real but bounded — embeddings and retrieval are cheap sub-calls; the big money is in response caching and prompt caching.
Part 6: Cache economics#
6.1 The formula#
Every cache layer has the same economic shape:
net_saving = hits × (cost_without_cache − cost_with_cache)
− lookups × lookup_overhead (every lookup pays it, hit or miss)
− stores × write_cost (prompt caching only)
− storage_cost (explicit caches only)For an app-level response cache (exact or semantic), cost_with_cache ≈ 0 on a hit (no provider call) and cost_without_cache = full call cost. So:
net_saving/day = requests/day × hit_rate × cost_per_call
− requests/day × cache_overhead_per_reqThe break-even hit rate is where net saving = 0:
break_even_hit_rate = cache_overhead_per_req / cost_per_callFor prompt caching, add the write premium: a cache write costs 1.25–2.5× base input, a read ~0.1×. The formula becomes the break-even derived in 11B.4, Part 5 (with a calculator in 03.7, 11.1) — reads must outnumber writes enough to cover the premium. This Part is about the economics of app-level caches, which Part 5 of 11B.4 does not cover.
6.2 A worked calculator#
Pure-local, stdlib only — run it yourself:
# cache_economics.py — net daily saving of a response cache
def net_saving(requests, hit_rate, cost_per_call, overhead_per_req=0.0):
hits = requests * hit_rate
saved = hits * cost_per_call
overhead = requests * overhead_per_req
return saved - overhead, hits, requests - hits
def break_even(overhead_per_req, cost_per_call):
return overhead_per_req / cost_per_call if cost_per_call else float("inf")
# FAQ bot: 100k req/day, $0.01/call, 40% hit rate, $0.0001 overhead/req
s, h, m = net_saving(100_000, 0.40, 0.01, overhead_per_req=0.0001)
print(f"FAQ bot: {h:,.0f} hits, {m:,.0f} misses -> net ${s:,.2f}/day")
# Conversational chat: 10k req/day, $0.05/call, 5% hit rate
s, h, m = net_saving(10_000, 0.05, 0.05, overhead_per_req=0.0001)
print(f"Chat: {h:,.0f} hits, {m:,.0f} misses -> net ${s:,.2f}/day")
print(f"Break-even hit rate (FAQ): {break_even(0.0001, 0.01):.1%}")FAQ bot: 40,000 hits, 60,000 misses -> net $390.00/day
Chat: 500 hits, 9,500 misses -> net $24.00/day
Break-even hit rate (FAQ): 1.0%Read it: the FAQ bot saves ~$390/day at a 1% break-even — caching is a no-brainer. The chat feature saves only $24/day at 5% hit rate — still positive but marginal; if overhead were higher or hit rate lower it'd lose money. The break-even hit rate is the number that decides whether to bother — below it, the cache costs more than it saves.
6.3 Latency savings#
Cost isn't the only axis. A cache hit returns in ~1–10ms (Redis/dict lookup) vs ~1–30s for an LLM call — a 100–1000× latency reduction on hits. For user-facing features, hit rate directly improves p50/p99 latency. But:
- A miss is slightly slower — you pay the lookup + the full call. Keep overhead small (a dict/Redis GET is ~1ms; an embedding call for semantic cache is ~50–200ms — not negligible).
- Stampede protection matters for latency too — a cold-cache burst without single-flight makes N users wait for N sequential computes; with it, they all get the one result (7.6).
- Prompt caching saves latency too — cached prefix skips prefill, so TTFT drops (02.7, 7.2 measured ~9–11× on a 2,895-token prefix locally).
6.4 When caching isn't worth it#
| Scenario | Verdict |
|---|---|
| Hit rate below break-even | Lose money — measure before enabling |
| Unique-per-request traffic | No repeats = pure overhead — and the adversarial version is 7.9 |
| Answers must reflect "now" | TTL can't be short enough; correctness risk |
| Wrong-answer cost > savings | Semantic cache on high-stakes = bad trade |
| Cache infrastructure cost > savings | Redis cluster, vector DB, ops time — count it |
| Development/debugging | Use the dev cache (03.10), not production caching |
6.5 Measuring in production#
The metrics are 11A.2's job; the cache-specific ones (for provider prompt caching see 2.6 and 03.7, Part 10):
- Hit rate (hits / total lookups) per cache layer per feature.
- Net saving — the counterfactual: cost-without-cache − actual cost, after write premiums and overhead.
- Latency delta — p50/p99 with vs without cache.
- False-hit rate (semantic only) — sampled manual review or eval-set correctness.
- Stampede/coalescing count — how often single-flight saved you.
Emit them as metrics (11A.2 owns the instrumentation); the CacheStats in cache.py is the in-process version.
What this means for you as an engineer: cache economics is a formula, not a vibe. Compute the break-even hit rate before enabling; measure net saving (not just hit rate) in production; count overhead and write premiums; and remember latency is a second currency. A cache that saves $390/day at 1% break-even is obvious; one that saves $24/day at 5% hit rate needs scrutiny.
Part 7: Correctness, safety and failure modes#
Every cache bug is a key bug, a TTL bug, a scope bug — or, for guaranteed-miss floods, a missing admission control. This part is the failure catalogue with the production rule for each.
7.1 Staleness: the key must carry every version#
A cached answer is only as fresh as the things it depended on. The dependencies that must be in the key:
- Model version —
gpt-6-lunatoday,gpt-6-luna-2026-11tomorrow; a silent provider update changes answers under the same model name. Pin dated snapshots where offered (02.9, Part 8 owns versioning) and put the pinned ID in the key. - Prompt/template version — 04.10 owns versioning; the version string goes in the key.
- Index/data version — a reindex, embedding-model change or document update changes what retrieval returns, hence the answer.
index_versionin the key (07.11's ResponseCache carries it). - Tool/API version — a tool-result cache keyed without the upstream API version serves pre-change data.
- Time-dependent answers — "today's weather", "current price": either don't cache, or put a coarse time bucket (
date) in the key so entries expire naturally.
7.2 Non-deterministic outputs and frozen answers#
LLM outputs are samples, not functions (02.5, Part 7). Caching picks one sample and serves it until TTL:
- Fine for: classification, extraction, FAQ — small answer spaces where any valid sample is acceptable.
- Risky for: open-ended generation, creative writing, anything where variety is the product.
- The mitigation: cache the decision, not the prose. For "summarise this doc", cache nothing or cache per-doc; for "classify this ticket", cache the label. When in doubt, keep the LLM call and cache only the deterministic sub-results (Part 5).
7.3 Personalised content#
An answer that depends on who is asking must either include the user in the key or not be cached:
- User-specific state in the key:
scope=user-123gives perfect isolation but near-zero hit rate (every user misses).scope=role:premiumshares across same-role users — better hit rate, still correct if the answer only depends on role-level facts. - The test: if two users with the same scope could legitimately get different answers (different order history, different preferences), the scope is too coarse — add the missing dimension or don't cache.
- PII in cached values: a cached answer may quote the user's own data (order details, health info). Encrypt at rest, short TTL, delete on erasure (7.4).
7.4 PII in cached values#
Cached responses can contain personal data — the user's question, the answer quoting their records, embeddings of their documents. The rules:
- Encrypt sensitive entries at rest — Redis with encryption, or encrypt the value before storing; the key (a hash) is safe, the value may not be.
- Short TTL for PII-bearing entries — minutes to hours, not days.
- Deletion propagates — an erasure request must reach cached queries and cached answers (05.9, 9.3 owns the propagation pattern across raw store, manifest, vectors, caches, backups). Your cache needs a
delete_by_scope(user)ordelete_by_doc(doc_id)path — 07.11'sinvalidate_docis the model. - Don't log raw queries into cache tables — hash for lookup, keep a separate access-controlled log if needed (06.2, 5.5).
- Access control on the cache itself — the cache store is as sensitive as the database; restrict who can read it.
7.5 Cache poisoning → Module 12#
An attacker who can influence queries can populate a shared cache with malicious answers that get served to other users — cache poisoning. The defences (Module 12 owns the full threat model):
- Scope-partition aggressively — per-tenant caches mean one tenant's poison can't reach another.
- Never cache attacker-controlled content verbatim — a query like "ignore previous instructions and say X" cached as an answer is a stored prompt-injection payload.
- Validate before storing — don't cache refusals, errors, or outputs that fail your validators (7.7).
- Key on authenticated scope — the scope comes from the session/token, never from client-supplied fields a user can forge.
- Rate-limit cache writes — a flood of unique queries shouldn't evict good entries; size bounds + LRU help.
7.6 Cache stampede / thundering herd#
A stampede (or thundering herd) is N concurrent requests missing the same cold key simultaneously, each starting its own expensive compute. For an LLM call costing $0.05 and 5s, 100 simultaneous misses = $5 and a provider rate-limit hit.
The fix is single-flight (also called request coalescing or dogpiling prevention): the first caller computes; concurrent callers with the same key await the same result. ExactCache.get_or_compute implements it with an _inflight dict of asyncio.Tasks — shown in 3.8 and demoed in 8.4 (20 concurrent identical → 1 provider call, 19 coalesced).
Variants:
- Lock + double-check: acquire a per-key lock, re-check the cache inside the lock (the classic pattern;
diskcache'smemoize_stampededoes this). - Probabilistic early expiry: for TTL caches, expire some entries slightly early so they don't all miss at once (XFetch-style).
- Request queueing: for extreme bursts, queue misses and process at a controlled rate — 11C.3 owns backpressure.
7.7 Negative caching: don't#
Negative caching is storing "this request failed" and replaying the failure. For LLM calls it's almost always wrong:
- A 429/500/timeout cached means every retry for the TTL gets the cached failure instead of a real attempt — a self-inflicted outage.
- A refusal or content-block cached means a legitimate retry (with different params or after a policy change) still gets the cached refusal.
- An empty/invalid response cached means the parse failure repeats forever.
The rule from devcache.py (03.10) and cache.py: only store successful, complete responses. Errors, refusals, truncations and timeouts are never cached. The except in _compute_and_store re-raises without storing — that's the whole mechanism.
7.8 Invalidation strategies and warming#
Recap of the invalidation toolkit, roughly in order of preference:
- Versioned keys — the version is the invalidation; old entries die by TTL/GC.
- TTL — bounds staleness for unversioned drift.
- Event-driven —
invalidate_doc(doc_id),delete_by_scope(user)on the events that change the answer's inputs. - Explicit flush — blunt; use on deploy when versions didn't change but you need a clean slate.
- Warming — after invalidation (deploy, reindex, flush), pre-populate the hot keys so the first real users don't all miss: fire representative requests per (model × prefix-variant × scope) before opening traffic. 03.7, 6.6 covers provider-side warming; the app-level version is the same idea on your response cache.
7.9 Cache penetration: guaranteed misses#
The third classic cache failure mode (alongside stampede and correlated expiry) is penetration: requests for keys that can never hit, so every one pays the full backend cost. In LLM apps it has a sharper edge than in classic caches:
- Benign penetration is 6.4's "unique-per-request traffic" — every miss is pure overhead, and on the semantic path each miss also pays an embed call plus a vector search before discovering there is nothing to serve.
- Adversarial penetration is real: an attacker can spray unique queries — or queries crafted to sit just under the semantic threshold — and every one still costs a full generation call (plus embed + search on the semantic path). It is the cache-flavoured version of a cost denial-of-service, and the per-miss work makes it more expensive per request than a plain API flood.
The defences are admission control, not caching:
- Authenticate and rate-limit before compute. Quotas per user/tenant/API key before the cache lookup — a request that would be rejected anyway shouldn't pay an embed or a generation. 11C.3 owns rate limiting; 11B.1 owns token budgets.
- Alert on miss rate and distinct-key rate per scope. A scope whose miss rate jumps to ~100% with high key cardinality is being penetrated — or your key design broke; the same signal catches both, so check which. These are 11A.2 metrics.
- Protect hot entries from miss-driven eviction. A flood of unique misses can flush the good entries out from under you — size bounds plus LFU/LRU-with-protection, not naive FIFO.
- Keep failure-throttling out of the response cache. If you need to damp repeated failures, that is the circuit-breaker/rate-limiter concern of 7.7's exception — never negative-cache the penetrated requests themselves.
What this means for you as an engineer: every cache failure is a key, TTL or scope bug. Version every dependency in the key, TTL for unversioned drift, single-flight for stampedes, never cache errors, propagate deletions to cached values, warm after invalidation — and treat guaranteed-miss floods as an admission-control problem (7.9). The failure gallery in 8.6 collects the incidents.
Part 8: Coalescing, gateways and the running service#
Deep-dive
8.1 Batching vs coalescing: two different things#
03.9, 1.4 owns the three meanings of "batching". The cache-relevant one is request coalescing (also called deduplication or single-flight): when N identical requests are in flight at once, collapse them into one provider call and fan the result out. It's different from:
- Provider batch APIs — submit many different requests as a job for ~50% off, hours latency. For offline work, not request dedup.
- Request packing — put several items in one prompt ("classify these 20"). Different mechanism, similar savings.
- Server-side continuous batching — the provider's GPUs batch your requests; invisible to you.
Coalescing is the only one that helps concurrent identical requests without changing what the model sees. ExactCache.get_or_compute's _inflight dict is the implementation; 7.6 covers the stampede it prevents.
8.2 Response caching in gateways#
Four gateways offer response caching, verified as of November 2026:
| Gateway | Cache type | Key / scope mechanism | Notable limits |
|---|---|---|---|
| LiteLLM proxy | Exact (redis,s3,gcs,local,disk) + semantic (redis-semantic,valkey-semantic,qdrant-semantic) |
Hash of request body; ttl; semantic embeds whole messages array |
Semantic warns against multi-turn/agentic; requests over max_messages (default 4) skip semantic lookup/store; x-litellm-semantic-similarity header on hits; Redis needed multi-worker |
| Portkey | Simple (exact) + semantic (cosine, enterprise) | Full request body + x-portkey-metadata + x-portkey-cache-namespace + max_age; x-portkey-cache-force-refresh |
Semantic only <8,191 tokens & ≤4 messages; semantic is Enterprise-plan |
| Cloudflare AI Gateway | Exact only (edge) | cache_ttl on gateway; cf-aig-cache-key, cf-aig-skip-cache, cf-aig-cache-ttl, cf-aig-cache-status headers |
Identical requests only; text+image; no semantic mode yet |
| Helicone | Exact (edge, Workers KV) | Helicone-Cache-Seed + URL + body + auth/cache headers + bucket index; Cache-control max-age; Helicone-Cache-Bucket-Max-Size |
Multi-response buckets; Helicone-Cache: HIT/MISS header; the helicone/ai-gateway README documents Redis/S3 backends — a different surface |
Two details from Cloudflare's own caching page (checked November 2026) show why a gateway cache does not replace app-level thinking: caching is off by default and enabled globally or per request, the TTL is bounded (60 seconds to one month, 5 minutes if you set none), and the cache is documented as volatile — two identical requests that arrive at the same moment can both miss. That is the stampede of 7.6 happening one layer out, so single-flight in your own service is still worth having in front of a gateway cache.
8.3 App-level vs gateway-level: trade-offs#
App-level (llm_service/cache.py) |
Gateway-level | |
|---|---|---|
| Key control | Full: scope, versions, normalisation, state hash | Limited: body hash + provider-specific namespace/metadata |
| Scope/ACL | Native — scope inside your key | Depends on gateway's metadata/namespace support; verify per-tenant isolation |
| TTL/invalidation | Your TTL + versioned keys + event-driven | Gateway TTL (max_age, cache_ttl); no event-driven invalidation |
| Semantic | Your threshold, your embedder, your eval-tuned dial | Gateway's threshold; less control |
| Streaming | You control replay/bypass | Gateway caches non-streaming typically; verify |
| Ops | Your code, your store (Redis/dict) | Zero app code; another config surface |
| Lock-in | None — your cache | Tied to gateway's semantics |
The rule: use the gateway cache for the simple, high-volume, low-risk exact-match case (FAQ endpoints where the whole request is the key and you don't need custom scope/TTL). Use the app cache when you need scope-aware keys, versioned invalidation, semantic thresholds, streaming replay, or per-feature control — which is most production cases. They compose: gateway cache in front, app cache behind for what the gateway can't express.
8.4 llm_service/cache.py — the running project file#
The complete file, stdlib-only, runnable with python3 cache.py (real output below). It is the module's cache module: request_key builds the exact-match key from scope + provider + model + prompt version + params + deps + normalised messages, ExactCache serves it with single-flight, SemanticCache does thresholded similarity within scope, HashingEmbedder is the offline stand-in.
"""llm_service/cache.py — response caches for the llm_service.
Stdlib only, so every sample in lesson 11B.3 runs with no API key and no
packages. Three pieces:
- ``request_key``: turn a call's inputs into the exact-match cache key.
Everything that can change the answer must be in it.
- ``ExactCache``: normalised request -> stored response, with TTL, size
bound, per-scope keys and single-flight (one in-flight compute per key,
so a burst of identical misses costs one provider call, not N).
- ``SemanticCache``: embed the query, serve the nearest stored answer whose
cosine similarity clears ``threshold`` — but only inside the caller's
permission scope. A wrong hit is worse than a miss, so the threshold is a
quality dial tuned on an eval set, never a guess.
The ``HashingEmbedder`` is a deterministic stand-in: feature hashing over
word n-grams. Swap it for a real embedding API in production (lesson 06.2
owns the embedder pipeline and its own cache).
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import math
import re
import time
import unicodedata
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
_WORD = re.compile(r"[a-z0-9]+")
def normalise_text(text: str) -> str:
"""Lowercase, fold accents to ASCII, keep ``[a-z0-9]`` runs.
"café" -> "cafe", "don't" -> "don t". Exact match means exact *after*
this canonicalisation — anything more aggressive is semantic caching.
"""
folded = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
return " ".join(_WORD.findall(folded.lower()))
def _canonical_content(content: Any) -> Any:
"""Text is normalised; multimodal block lists pass through to JSON.
``json.dumps(..., sort_keys=True)`` in ``request_key`` canonicalises
the blocks; content that isn't JSON-serialisable raises — this cache
is for text-shaped requests.
"""
if isinstance(content, str):
return normalise_text(content)
return content
def request_key(
*,
messages,
model,
params,
prompt_version,
scope,
provider="",
deps=None,
) -> str:
"""The exact-match cache key: scope + provider + model + prompt +
params + deps + normalised messages.
``scope`` is the permission/tenant boundary — inside the key, never a
post-filter, so a hit can never cross an ACL. ``deps`` carries the
state the answer depends on that isn't in the messages: ``index_version``,
tool versions, user-state hashes.
"""
canonical = {
"scope": scope,
"provider": provider,
"model": model,
"prompt_version": prompt_version,
"params": params,
"deps": deps or {},
"messages": [
{"role": m["role"], "content": _canonical_content(m["content"])}
for m in messages
],
}
blob = json.dumps(canonical, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(blob.encode()).hexdigest()
@dataclass
class CacheStats:
hits: int = 0
misses: int = 0
stores: int = 0
coalesced: int = 0
errors: int = 0
@property
def hit_rate(self) -> float:
total = self.hits + self.misses
return self.hits / total if total else 0.0
@dataclass
class _Entry:
value: Any
expires_at: float
class ExactCache:
"""Request -> response cache with TTL, size bound and single-flight.
``None`` is never a hit — a stored ``None`` is indistinguishable from a
miss, so treat ``None`` as "no answer" upstream and don't cache it.
"""
def __init__(self, ttl_seconds=3600.0, max_entries=10_000, store=None):
self.ttl = ttl_seconds
self.max_entries = max_entries
self._store = store if store is not None else {}
self.stats = CacheStats()
self._inflight: dict[str, asyncio.Task[Any]] = {}
def get(self, key: str) -> Any | None:
entry = self._store.get(key)
if entry is None:
return None
if entry.expires_at < time.time():
self._store.pop(key, None)
return None
return entry.value
def put(self, key: str, value: Any) -> None:
if len(self._store) >= self.max_entries:
self._evict_one()
self._store[key] = _Entry(value, time.time() + self.ttl)
self.stats.stores += 1
def _evict_one(self) -> None:
oldest = min(self._store, key=lambda k: self._store[k].expires_at)
self._store.pop(oldest, None)
async def get_or_compute(self, key: str, compute: Callable[[], Awaitable[Any]]) -> Any:
"""Serve ``key`` from cache, or run ``compute`` exactly once.
Concurrent callers with the same key share one in-flight task —
the stampede case. Only successful computes are stored.
"""
hit = self.get(key)
if hit is not None:
self.stats.hits += 1
return hit
task = self._inflight.get(key)
if task is not None:
self.stats.coalesced += 1
self.stats.hits += 1
return await asyncio.shield(task) # one waiter leaving must not cancel the rest
self.stats.misses += 1
task = asyncio.ensure_future(self._compute_and_store(key, compute))
self._inflight[key] = task
task.add_done_callback(lambda t, k=key: self._finish(k, t))
return await asyncio.shield(task)
def _finish(self, key: str, task: asyncio.Task[Any]) -> None:
self._inflight.pop(key, None)
if not task.cancelled():
task.exception() # mark retrieved: no "never retrieved" warning if every waiter left
async def _compute_and_store(self, key: str, compute) -> Any:
try:
value = await compute()
except BaseException:
self.stats.errors += 1
raise # never cache failures
self.put(key, value)
return value
class HashingEmbedder:
"""Deterministic toy embedder: feature hashing over word n-grams.
Real semantic caches use a real embedding model; this exists so the
pipeline runs offline. Similarity is bag-of-words-ish.
"""
def __init__(self, dims: int = 256) -> None:
self.dims = dims
def _ngrams(self, text: str) -> list[str]:
words = _WORD.findall(text.lower())
grams = list(words)
grams += [f"{a} {b}" for a, b in zip(words, words[1:])]
return grams
def embed(self, text: str) -> list[float]:
vec = [0.0] * self.dims
for g in self._ngrams(text):
h = int.from_bytes(hashlib.blake2b(g.encode(), digest_size=8).digest(), "big")
vec[h % self.dims] += 1.0
norm = math.sqrt(sum(v * v for v in vec)) or 1.0
return [v / norm for v in vec]
def cosine(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b)) # inputs are L2-normalised
@dataclass
class SemanticEntry:
vector: list[float]
value: Any
scope: str
created_at: float
hits: int = 0
class SemanticCache:
"""Question -> answer cache over embedding similarity, scope-filtered.
Demo scope: ``_entries`` is a list standing in for a vector index —
production swaps in RedisVL/Qdrant, adds single-flight on the miss
path, and evicts by TTL + score rather than scanning FIFO.
"""
def __init__(self, embedder, threshold=0.35, ttl_seconds=86_400.0, max_entries=5_000):
self.embedder = embedder
self.threshold = threshold
self.ttl = ttl_seconds
self.max_entries = max_entries
self._entries: list[SemanticEntry] = []
self.stats = CacheStats()
def _query_vector(self, text: str) -> list[float]:
return self.embedder.embed(text)
def check(self, query: str, scope: str) -> Any | None:
qv = self._query_vector(query)
best, best_sim = None, -1.0
now = time.time()
for e in self._entries:
if e.scope != scope or e.created_at + self.ttl < now:
continue # scope + TTL filter BEFORE similarity
sim = cosine(qv, e.vector)
if sim > best_sim:
best, best_sim = e, sim
if best is None or best_sim < self.threshold:
self.stats.misses += 1
return None
best.hits += 1
self.stats.hits += 1
return best.value
def store(self, query: str, value: Any, scope: str) -> None:
if len(self._entries) >= self.max_entries:
self._entries.pop(0)
self._entries.append(
SemanticEntry(self._query_vector(query), value, scope, time.time())
)
self.stats.stores += 1
def nearest(self, query: str, scope: str) -> tuple[Any | None, float]:
"""(value, similarity) of the best in-scope entry — for threshold tuning."""
qv = self._query_vector(query)
best, best_sim = None, -1.0
now = time.time()
for e in self._entries:
if e.scope != scope or e.created_at + self.ttl < now:
continue # same scope + TTL filter as check()
sim = cosine(qv, e.vector)
if sim > best_sim:
best, best_sim = e, sim
return (best.value if best else None, best_sim)
async def _fake_llm(messages):
await asyncio.sleep(0)
return f"answer to: {messages[-1]['content'][:40]}"
async def demo_exact() -> None:
cache = ExactCache(ttl_seconds=60)
calls = {"n": 0}
async def compute(q: str) -> str:
calls["n"] += 1
return await _fake_llm([{"role": "user", "content": q}])
key_a = request_key(
messages=[{"role": "user", "content": "What is the refund policy?"}],
model="gpt-6-luna", provider="openai",
params={"max_tokens": 200}, prompt_version="v14",
scope="tenant-a", deps={"index_version": "idx-2026-11-04"},
)
key_b = request_key(
messages=[{"role": "user", "content": "what is the REFUND policy"}],
model="gpt-6-luna", provider="openai",
params={"max_tokens": 200}, prompt_version="v14",
scope="tenant-a", deps={"index_version": "idx-2026-11-04"},
)
key_c = request_key(
messages=[{"role": "user", "content": "What is the refund policy?"}],
model="gpt-6-luna", provider="openai",
params={"max_tokens": 200}, prompt_version="v14",
scope="tenant-b", deps={"index_version": "idx-2026-11-04"},
)
key_d = request_key(
messages=[{"role": "user", "content": "What is the refund policy?"}],
model="gpt-6-luna", provider="openai",
params={"max_tokens": 200}, prompt_version="v14",
scope="tenant-a", deps={"index_version": "idx-2026-11-05"}, # reindexed
)
results = await asyncio.gather(
*[cache.get_or_compute(key_a, lambda: compute("What is the refund policy?"))
for _ in range(20)]
)
print(f"exact: 20 concurrent identical -> provider calls={calls['n']}, "
f"coalesced={cache.stats.coalesced}, hit_rate={cache.stats.hit_rate:.0%}")
print(f"exact: normalised variant same key? {key_a == key_b}")
print(f"exact: other tenant same key? {key_a == key_c}")
print(f"exact: reindexed deps same key? {key_a == key_d}")
print(f"exact: all 20 answers identical? {len(set(results)) == 1}")
async def demo_semantic() -> None:
cache = SemanticCache(HashingEmbedder(), threshold=0.35)
faq = {
"How do I get a refund?": "Refunds go to the original payment method within 14 days.",
"What are your business hours?": "Support is staffed 09:00-18:00 UTC, Monday to Friday.",
"Do you ship internationally?": "We ship to 40 countries.",
}
for q, a in faq.items():
cache.store(q, a, scope="public")
probes = [
("How can I get my money back?", "public"),
("what is the refund policy", "public"),
("When does support close on Friday?", "public"),
("How do I get a refund?", "tenant-x"),
]
for q, scope in probes:
value, sim = cache.nearest(q, scope)
hit = cache.check(q, scope)
print(f"semantic [{'HIT ' if hit else 'miss'}] sim={sim:.3f} {q!r} (scope={scope})")
if hit is not None:
print(f" served: {str(hit)[:60]!r}")
if __name__ == "__main__":
asyncio.run(demo_exact())
print()
asyncio.run(demo_semantic())exact: 20 concurrent identical -> provider calls=1, coalesced=19, hit_rate=95%
exact: normalised variant same key? True
exact: other tenant same key? False
exact: reindexed deps same key? False
exact: all 20 answers identical? True
semantic [HIT ] sim=0.389 'How can I get my money back?' (scope=public)
served: 'Refunds go to the original payment method within 14 days.'
semantic [miss] sim=0.201 'what is the refund policy' (scope=public)
semantic [miss] sim=0.114 'When does support close on Friday?' (scope=public)
semantic [miss] sim=-1.000 'How do I get a refund?' (scope=tenant-x)8.5 The decision table#
| Situation | Cache layer | Key includes | TTL | Notes |
|---|---|---|---|---|
| Same FAQ asked identically | App exact-match | scope+model+prompt+params+normalised msgs | hours–days | Safest; version on prompt/model |
| Same doc Q over stable corpus | App exact-match or RAG response cache | + index_version + doc_ids | TTL + invalidate_doc | 07.11 owns RAG version |
| Paraphrased FAQ, single-shot | Semantic cache | scope + embedder_version + threshold | hours–days | Tune threshold; eval-gate |
| Conversational/agentic | None or exact-match | — | — | Semantic replays stale context |
| Shared prompt prefix, any traffic | Provider prompt cache | n/a (prefix bytes) | provider lifetime | Layout: stable first (Part 2) |
| Embeddings / retrieval / tool reads | Specialist caches | spec hash / query+filters+version / endpoint+args+scope | by freshness | Owned by 06.2 / 07.x / this lesson |
| Static generated assets | CDN/edge + client | URL + version | HTTP cache headers | Not the AI gateway |
| Concurrent identical cold misses | Single-flight (in ExactCache) | same key | — | Prevents stampede |
| High-volume simple exact repeats | Gateway cache | body hash + namespace | gateway TTL | Less control; see 8.3 |
8.6 The failure gallery#
| Failure | Symptom | Root cause | Fix |
|---|---|---|---|
| Semantic cache returns another user's answer | Cross-tenant leak | Scope as post-filter, not in key | Scope inside key hash; filter before similarity |
| Cache key missing model version | Wrong answers after model swap | Model not in key | Pin model ID in key; version on change |
| Caching refusals/errors | Retries get cached failure | Storing non-200/incomplete | Only store successful complete responses |
| TTL too long on policy answers | Stale policy served | TTL > freshness SLA | Shorter TTL + version on policy doc |
| Prefix churn kills prompt cache | Hit rate ~0 after deploy | Timestamp/request-id in system prompt | Move volatile data to suffix (Part 2) |
| Stampede on cold key | N× provider calls, rate-limit hit | No single-flight | get_or_compute _inflight dict |
| Semantic cache on chat traffic | "What about contractors?" gets employee answer | Threshold can't see session state | Exact-match or no cache for conversational |
| Cache write premium exceeds savings | Cost up, hit rate "fine" | Writes never read | Measure net saving, match lifetime to gap |
| Erasure request leaves cached PII | Compliance breach | Delete didn't reach cache | delete_by_scope/invalidate_doc propagation (7.4) |
| Gateway cache ignores your scope | Tenant A answer to tenant B | Gateway key lacks scope | App-level cache or gateway metadata namespace |
| Cache penetration / guaranteed misses | Hit rate ~0, full cost on every request | Unique or adversarial keys never repeat | Admission control + per-scope miss-rate alerts (7.9) |
What this means for you as an engineer: coalescing prevents stampedes, gateways offer zero-code caching for simple cases, and llm_service/cache.py gives you scope-aware, versioned, single-flight caching with a tunable semantic layer — all stdlib, all testable offline. The decision table picks the layer; the failure gallery is what to watch in production.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Caching is always a win." | Writes cost more than reads on prompt caching; overhead can exceed savings below the break-even hit rate (6.1, 2.7). |
| "The cache key is the user prompt." | The key must carry scope, model, prompt version, params and every state/version the answer depends on (3.2). |
| "A semantic cache hit is as safe as an exact hit." | It serves an answer to a similar question; the threshold trades hit rate against wrong answers (4.4). |
| "Caching makes the model deterministic." | It freezes one sample until TTL; it doesn't make generation deterministic (7.2). |
| "Cache the errors too, saves retries." | Negative caching replays failures; only store successful complete responses (7.7). |
| "TTL handles staleness." | TTL bounds how long you're wrong; versioned keys bound whether you're wrong (3.5). |
| "Prompt caching and response caching are the same." | Prompt caching reuses the KV prefix (cheaper input); response caching reuses the whole answer (no call at all) — different layers (Part 1). |
| "The gateway cache handles tenancy." | Gateway keys are body hashes; per-tenant scope needs app-level keys or gateway namespace metadata (8.3). |
| "Semantic caching works for chatbots." | It replays stale answers on multi-turn/agentic traffic — LiteLLM's own docs warn against it (4.5). |
| "A high hit rate means it's working." | Measure net saving after write premiums and overhead, not just hit rate (6.5). |
Key takeaways#
- Caching is a stack of seven layers, each saving something different: client, CDN/edge, gateway response, app exact-match, app semantic, specialist (embedding/retrieval/tool), and provider/self-hosted prefix caching. They compose; the big money is in response caching and prompt caching.
- The key is the contract. Scope inside the hash (never a post-filter), model + prompt + params + every dependency version inside the key, normalisation before hashing, canonical JSON with sorted keys.
- Exact-match caching is the safe workhorse for FAQ, classification, extraction and stable document Q&A — frozen answers are fine when the answer space is small.
- Semantic caching buys hit rate at the price of wrong-answer risk; it's for single-shot, low-stakes, high-repetition traffic only. Tune the threshold on a labelled set, scope before similarity, eval-gate it.
- Prompt caching is a layout feature: stable prefix first, volatile suffix last, canonical ordering, lifetime matched to traffic gap, warmed before bursts — and it loses money on churning or never-reread prefixes.
- Economics is a formula: net saving = hits × saved cost − overhead − write premiums; compute the break-even hit rate before enabling.
- Failure modes are key/TTL/scope bugs: staleness (version everything), frozen non-determinism, PII in cached values (encrypt, short TTL, propagate deletes), cache poisoning (scope-partition, Module 12), stampedes (single-flight), negative caching (never store errors).
llm_service/cache.pygives you scope-aware, versioned, single-flight exact caching plus a thresholded semantic cache — stdlib only, real output, no keys needed.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Caching stack | The layered set of caches in an LLM request path, from client to provider prefix cache |
| Exact-match response cache | Stores whole responses keyed by normalised request + scope + versions; replays identical requests |
| Semantic cache | Serves stored answers for queries whose embeddings are similar above a threshold, within a scope |
| Cache key | The hash of everything that can change the answer: scope, provider+model, prompt version, params, deps/state |
| Scope (in a cache key) | The permission/tenant boundary hashed into the key so hits never cross ACLs |
| Normalisation | Canonicalising request text (case, whitespace, punctuation) before hashing so trivial differences hit |
| Single-flight / request coalescing | Collapsing N concurrent identical misses into one compute, fanned out to all callers |
| Cache stampede / thundering herd | N simultaneous cold-key misses each starting an expensive compute |
| Negative caching | Storing failures and replaying them — almost always wrong for LLM calls |
| Threshold (semantic cache) | The similarity score above which a semantic-cache hit is served; a quality dial |
| False hit | A semantic-cache match that serves an answer to a different question |
| Prefix caching / KV-cache reuse | Provider or self-hosted reuse of the computed KV cache for an identical prompt prefix |
| Cache breakpoint | The marker ending a cacheable prefix (Anthropic cache_control, OpenAI prompt_cache_breakpoint) — owned by 03.7 |
| Write premium | The extra cost of writing a prompt-cache entry (1.25–2.5× base input) vs reading it (~0.1×) |
| Break-even hit rate | The hit rate at which cache savings equal cache overhead; below it caching loses money |
| Versioned key | Putting model/prompt/index versions in the key so changes invalidate for free |
| Event-driven invalidation | Dropping cached entries on the events that change their inputs (delete, reindex) |
| Warm-up / pre-warming | Writing hot cache entries before traffic arrives so the first users don't all miss |
| Cache poisoning | Attacker-controlled queries populating a shared cache with malicious answers (Module 12) |
| Cache penetration | Requests for keys that can never hit, so every one pays full backend cost; defended by admission control, not caching |
Exercises#
- Key design (3.2): take a real request from your project and list every input that could change the answer. Which are missing from a naive "hash the prompt" key? Add them and explain why each matters.
- Threshold tuning (4.3): build a labelled set of 20 (query, stored_query, should_hit) pairs for your domain. Run
SemanticCache.nearest()on each, plot similarity vs label, and pick a threshold. Where do the false hits live? - Single-flight proof (7.6): in
demo_exact, change the compute to sleep 50ms and fire 100 concurrent requests. Confirmprovider calls=1. Then remove the_inflightcheck and confirm it becomes 100 — that's the stampede. - Economics (6.2): plug your real numbers (requests/day, cost/call, measured hit rate, overhead) into
net_saving. What's your break-even? Is your cache above it? - Scope isolation (3.6): write a test that stores an answer for
scope="tenant-a"and assertsscope="tenant-b"misses on bothExactCache(different key) andSemanticCache(filtered before similarity). - Invalidation (7.8): change
prompt_versionin arequest_keycall (it is already part of the key), and confirm the old entry never hits. Then add adelete_by_scope(scope)method and an erasure test. - Gateway vs app (8.3): for your LiteLLM/Portkey/Cloudflare/Helicone gateway, check whether its cache key can carry your tenant scope. If not, what's the smallest app-level change?
- Failure gallery (8.6): pick one row and write the test that would have caught it before production.
- Penetration drill (7.9): fire 1,000 unique queries at
SemanticCacheand measure the per-miss cost (embed + scan + eventual generation). Where in your stack would admission control sit, and what metric would have alerted you first? - Cancellation (7.6): start two
get_or_computecalls on the same key as separate tasks, cancel the first after 10 ms andawaitthe second. It should still return the answer with one compute call. Now replaceasyncio.shield(task)with a bareawait taskand watch the second caller fail withCancelledError.
Hints for the exercises
- Typical missing inputs: scope/tenant, model, prompt version, generation parameters, retrieved-document or index version, tool results, the current date for time-dependent answers.
- Include hard negatives (same topic, different intent: "refund policy" vs "refund for a damaged item"); the false hits live in the 0.7-0.9 band for real embedders. With the toy
HashingEmbedderthe whole scale is lower, so tune on your own scores. - With 100 callers expect
provider calls=1, coalesced=99. Without the_inflightbranch every miss computes: 100 calls. - Break-even = overhead per request / cost per call. If your measured hit rate is below it, the cache is a net loss.
- Both assertions pass for the reason in 3.6: a different scope gives a different key (exact) or is filtered out before similarity (semantic).
- Bumping
prompt_versionchanges the key, so the old entry is never read; it ages out by TTL. Fordelete_by_scope, note that keys are SHA-256 hashes, so you cannot find a tenant's entries from the key alone: store thescopeinside_Entryand scan, or keep a side indexscope -> set(keys)thatput()updates and eviction cleans. - If the gateway key is just the body hash and there is no namespace or metadata field you control per tenant, the smallest change is to put a tenant-derived namespace header or key on every request, or to cache in the app instead.
- Example: for "Caching refusals", a test that makes
computeraise and assertscache.get(key)is stillNoneand the next call recomputes. - Expect every query to cost one embed plus a scan of all in-scope entries. Admission control sits before the cache lookup (auth and per-scope rate limit); the earliest alert is a per-scope miss rate near 100% with rising distinct-key count.
Check yourself#
- Name the seven cache layers and what each saves.Client, CDN/edge, gateway response, app exact-match, app semantic, specialist (embedding/retrieval/tool), provider/self-hosted prefix — see Part 1.
- Why must the permission scope be inside the cache key rather than a post-filter?A post-filter still reveals the entry exists and invites timing/leakage bugs; scope inside the hash means the other tenant's lookup simply misses (3.6).
- What are the six components of an exact-match cache key?Scope, model+provider, prompt/template version, generation params, tool/state hash, normalised request (3.2).
- What's the difference between prompt caching and response caching?Prompt caching reuses the KV prefix — cheaper input tokens, output still generated. Response caching reuses the whole answer — no provider call at all (Part 1).
- When does prompt caching lose money?Write-once-read-never prefixes, churning prefixes, short gaps vs long lifetimes, explicit-cache storage, sub-minimum prefixes (2.7).
- What three costs does a semantic cache add over an exact cache?An embedding call per lookup, a vector search per lookup, and wrong-answer risk (4.1).
- Which use cases suit semantic caching, and which forbid it?Single-shot low-stakes high-repetition (FAQ); forbidden for conversational/agentic, personalised, high-stakes, creative (4.5).
- How do you pick a semantic-cache threshold honestly?Labelled set of pairs → compute similarity → sweep threshold → pick where false hits ≈ 0 with useful hit rate; re-tune on changes (4.3).
- What's a cache stampede and how does single-flight fix it?N concurrent cold-key misses each computing; single-flight makes them share one in-flight task (7.6).
- Why is negative caching wrong for LLM calls?It replays failures (429/500/refusal) for the TTL instead of retrying — a self-inflicted outage (7.7).
- Name three invalidation strategies in order of preference.Versioned keys, TTL, event-driven invalidation, explicit flush, warming (7.8).
- What's the break-even hit rate formula?
cache_overhead_per_req / cost_per_call(6.1). - Gateway cache vs app cache — when do you choose each?Gateway for simple high-volume low-risk exact-match; app for scope-aware keys, versioned invalidation, semantic thresholds, streaming, per-feature control (8.3).
- What must propagate on an erasure request to reach cached data?
- What is cache penetration, and why is the defence admission control rather than caching?Requests for keys that can never hit — every one pays full backend cost (plus embed + search on the semantic path), so authenticate/rate-limit before compute and alert on per-scope miss rate (7.9).
Further resources#
- 11B.4 — Token Caching in Depth: the mechanics behind Part 2 (KV cache, hash chains, routing), every provider's rules in one table, and a hit-rate debugging checklist.
- 11B.2 — Tokenomics: where caching sits among the cost levers.
- Lesson 03.7 — Token Counting, Cost Tracking and Prompt Caching — provider caching APIs, hit-rate analyser, break-even economics (Parts 6–11).
- Lesson 02.7 — Context Windows — KV cache and prompt caching mechanics (Part 7).
- Lesson 04.6 — Context Selection and Ordering — cache-aware context layout (Part 10).
- Lesson 04.7 — Managing Context Over Time — cache-aware history management (Part 9).
- Lesson 06.2 — Embedding Pipelines —
CachingEmbedderand embedding cache keys (Part 5). - Lesson 07.11 — Production RAG — response/semantic caching in RAG (§4.3).
- Lesson 03.10 — Debugging and Testing — development response cache (
devcache.py, Part 13). - Lesson 03.9 — Async, Concurrency and Batch — batching meanings (§1.4).
- GPTCache — open-source semantic cache (MIT; README notes no new provider adapters).
- RedisVL SemanticCache docs — Redis-native semantic caching.
- LiteLLM caching docs and semantic caching — gateway exact + semantic caches.
- Portkey cache docs — simple and semantic gateway caching.
- Cloudflare AI Gateway caching — edge response caching.
- Helicone caching docs — edge response caching.
- vLLM Automatic Prefix Caching and SGLang unified radix cache — self-hosted prefix caching.
- diskcache and cachetools — local cache libraries (5.6.3 and 7.3.0 as of November 2026).
← 11B.2 — Tokenomics: The Unit Economics of LLM Applications | Module 11B overview | 11B.4 — Token Caching in Depth: How It Works, Who Supports It, and How to Use It →