Caching strategies
Keep copies of expensive reads in faster storage; choose how writes reach the cache, bound staleness with TTLs or invalidation, and protect the origin from stampedes when hot keys expire.
Analogy: A barista keeps the five most-ordered pastries on the counter and fetches the rest from the back. If everything on the counter sells out at once, every customer queues at the back room.
How it works
- Cache-aside is the default: read the cache; on a miss, load from the DB and fill it.
- Write-through keeps reads fresh but slows writes; write-behind writes fast but loses data if the cache dies.
- Origin load tracks the miss rate: going from 90% to 99% hits cuts backend traffic 10×.
- Stop stampedes on hot keys with request coalescing, jittered TTLs or stale-while-revalidate.
- AI stacks add three caches: provider prompt caching, response caches, and embedding caches keyed by
hash(model, text).
Check yourself
Answer to mark it learned; your answers aren't scored.
Your RAG app caches answers for 1 h, keyed by hash(normalized question). You re-index updated docs and ship a new prompt version; an hour later users still get answers citing the old docs. Best fix?
Go deeper
Full explanation
A cache keeps a copy of expensive-to-get data in faster storage (process memory, Redis, a CDN edge) so repeated reads skip the slow path. Average latency is hit_rate × cache_time + miss_rate × origin_time, and origin load is proportional to the miss rate.
How data gets in:
- Cache-aside (the default): read the cache; on a miss, load from the DB and fill it. The cache can die without losing data.
- Read-through: the same flow, but the cache layer loads on a miss.
- Write-through: every write updates DB and cache synchronously — fresh reads, slower writes.
- Write-behind: write to the cache, flush to the DB asynchronously — fast writes, data loss if the cache dies.
Staleness: a TTL bounds how old data can get; invalidation deletes the key on write (delete, don't set, so racing writers can't cache an old value). Eviction when memory fills: LRU (recency) or LFU (frequency, resists one-off scans).
Stampede: a hot key expires and thousands of requests hit the DB at once. Fixes: request coalescing (one fetch, the rest wait), jittered TTLs, stale-while-revalidate.
AI stacks add three caches: provider Prompt caching of a stable prefix, response caches (exact or Semantic caching), and embedding caches keyed by hash(model, text) so re-ingestion skips unchanged chunks.
Code Cache-aside with jittered TTL and request coalescing
import json, random, time
import redis
r = redis.Redis(decode_responses=True)
BASE_TTL = 300 # seconds
def get_product(pid: str) -> dict:
key = f"product:{pid}"
if (hit := r.get(key)) is not None:
return json.loads(hit) # hit: sub-millisecond
# Miss: only one caller rebuilds the key (request coalescing)
if r.set(f"lock:{key}", "1", nx=True, ex=10):
try:
value = db_load_product(pid) # slow path, e.g. 50 ms
ttl = int(BASE_TTL * random.uniform(0.9, 1.1)) # jitter: no synchronized expiry
r.set(key, json.dumps(value), ex=ttl)
return value
finally:
r.delete(f"lock:{key}")
for _ in range(20): # the rest wait up to ~1 s
time.sleep(0.05)
if (hit := r.get(key)) is not None:
return json.loads(hit)
return db_load_product(pid) # filler too slow: fall through
def update_product(pid: str, fields: dict) -> None:
db_update_product(pid, fields)
r.delete(f"product:{pid}") # delete, don't set: racing writers can't cache old dataReal example
A RAG assistant answers 2M questions a day, with three caches stacked:
- Embedding cache keyed by
sha256(model + chunk): the nightly re-ingest of 1M chunks finds 97% unchanged and embeds only ~30k. - Response cache keyed by normalized question + model + prompt version + index version, TTL 1 h: FAQ-style traffic gives a ~15% hit rate, and bumping the index version invalidates everything without a purge.
- Prompt cache: the 8k-token system prompt and tool schemas form a stable prefix, read at ~0.1× the input price.
Trade-offs +3 · −3
+ You gain
- Cuts latency and origin load by orders of magnitude on read-heavy, skewed traffic.
- Cheap capacity: one Redis node absorbs reads that would otherwise need many DB replicas.
- In AI stacks, every hit is an LLM or embedding call you don't pay for.
− You pay
- Two copies of the truth: staleness and invalidation bugs are the classic failure.
- Hit-ratio cliff: if the cache restarts cold or dies, the origin takes the full load at once.
- More infrastructure, memory cost and consistency reasoning on every write path.
Use it when
Read-heavy, skewed access (few keys get most reads), expensive recomputation (joins, embeddings, LLM calls), and data that tolerates seconds to minutes of staleness.
Avoid it when
Write-heavy or uniformly random access (low hit rate), data that must be exact (balances, permissions), or personalized LLM output that rarely repeats.
Numbers to know 5
- Average latency = hit × cache + miss × origin: with 1 ms vs 50 ms, 90% hits → ~5.9 ms, 99% → ~1.5 ms.
- Origin load scales with the miss rate: going from 90% to 99% hits cuts backend traffic 10×.
- Latency ladder (Jeff Dean): RAM reference ~100 ns, same-datacenter round trip ~0.5 ms, disk seek ~10 ms.
- Rule of thumb: one Redis instance handles ~100k simple ops/s at sub-millisecond latency.
- Anthropic prompt-cache reads cost ~0.1× base input; the default TTL is 5 minutes, refreshed on each hit.
Common pitfalls 4
- Setting the cache on write instead of deleting: two racing writers can leave the older value cached.
- Identical TTLs on keys loaded together (deploy, warm-up): they all expire in the same second. Add jitter.
- LLM response keys without model, prompt version and index version: you serve answers from an old model or a stale corpus.
- Sharing cached LLM answers across tenants or users without their id or permissions in the key.
Interview questions 2
Answer out loud first, then reveal.
Your hit rate is 98%, yet the database falls over every few hours. What's going on?Show answer
Probably a stampede: a hot key, or a batch of keys loaded together, expires and thousands of concurrent misses hit the origin in the same second. A healthy average hides it. I'd confirm by correlating DB spikes with key expiries. Fixes, cheapest first: jittered TTLs, request coalescing so one caller rebuilds while the rest wait, and stale-while-revalidate for keys that tolerate it. Facebook's memcache paper uses leases for exactly this. Then I'd put a rate limit in front of the database as the backstop.
Where would you put caches in an LLM application?Show answer
In layers, safest first. Provider prompt caching: I order the prompt so tools, system prompt and documents form a stable prefix, which cuts input cost and TTFT with zero staleness. An embedding cache keyed by model and content hash, so re-ingestion only pays for changed chunks. An exact-match response cache keyed by normalized input, model, prompt version and index version. A semantic cache only for FAQ-like traffic, with a strict threshold and an eval of false hits, because a wrong cached answer is worse than a slow one.