Design building blocks · core
Caching strategies and cache failures
Use cache-aside by default: read the cache, fill on a miss, delete on update. Know write-through and write-back, TTL, the update race, and the herd after a cache restart.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Cache-aside: read the cache; on a miss read the database and set the key with a TTL. On an update, write the database, then delete the key. Simple and the most common.
- Write-through writes the cache and database together; reads are warm but writes are slower. Write-back writes the cache and flushes later: fast but data can be lost, so fine for view counts and wrong for orders or money.
- TTL by data: long for descriptions and images; seconds, or event-based invalidation, for price and stock. Change events from the database (CDC with Debezium into Kafka) can delete keys; versioned keys also work.
- The race: after write then delete, a slow reader can put an old value back. A short TTL, a delayed second delete or version checks reduce it.
- Eviction is LRU or LFU with a memory limit. Watch for hot keys. One key always maps to one cache node, so more nodes do not spread a single hot key.
- Hot key fixes: a local in-process cache with short TTL, copies under suffixes (code#1 to code#N) read at random, read replicas, and request coalescing.
- After a cache restart every key misses and all requests hit the database (a thundering herd). Retries multiply the load. Use request coalescing, a per-key lock, early refresh, serving stale data, a circuit breaker and warm-up.
- Keys written together with the same TTL expire together. Add random jitter to TTLs.
The red pen
Common traps: mistake → fix
Mistake: Cache with no TTL and no invalidation is fine
Fix: it serves old data forever.
Mistake: Update the cache first, then the database
Fix: a failure leaves the cache wrong.
Mistake: More cache nodes fix a hot key
Fix: one key lives on one node.
Mistake: Increase the TTL to fix a herd
Fix: it only delays the next herd.
Easy to hard
Questions interviewers ask, easy to hard
- Cache-aside, write-through or write-back: when each?
- How do you keep a cache and a database consistent?
- The database fell over after a cache restart. Why and how do you prevent it?
- What is a hot key and how do you fix it?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.