Most systems are read-heavy, and most reads ask for the same small set of things: the front page, a popular product, a celebrity's profile. A cache keeps those answers somewhere faster than the database, usually in memory, so a repeat question costs about a millisecond and puts no load on the database.
Where caches live
Caching happens at every layer, from the user's device to the disk:
- Browser cache: controlled by HTTP headers. It's free and the fastest, but you can't purge it.
- CDN: shared edge caches near users, mostly for static files. See CDNs.
- In-process cache: a map inside each app server. No network hop, but every server has its own copy and they drift apart.
- Distributed cache: Redis or Memcached, shared by every app server. This is what people usually mean by "add a cache".
- Database buffer pool: the database caches hot pages in RAM on its own.
Read and write patterns
| Pattern | How it works | Good for |
|---|---|---|
| Cache-aside (lazy loading) | The app reads the cache. On a miss it reads the DB and writes the result into the cache. | The default. Only caches what's actually requested. |
| Read-through | The cache library loads from the DB itself on a miss. | Same as cache-aside, with less app code. |
| Write-through | Every write goes to the cache and the DB together. | Data that's read right after it's written. |
| Write-behind (write-back) | Writes go to the cache and are flushed to the DB later. | Very high write rates, if you accept losing data when the cache dies. |
| Write-around | Writes go straight to the DB. The cache fills on the next read. | Data written once and rarely read. |
Hit rate is everything
If h is the hit rate, the share of requests reaching the database is 1 − h. That makes the last few percent worth far more than they look:
Hit rate rises with cache size, longer TTLs and skewed popularity. Real workloads usually follow a power law, so a cache holding the top 1% of keys can serve most of the traffic.
Eviction
Memory runs out, so something has to go. LRU (least recently used) is the common default. LFU (least frequently used) protects items that are always popular from a burst of one-off reads. A TTL on each key bounds how stale data can get, even if you forget to invalidate it.
Invalidation, the hard part
A cache is a copy, and copies go stale. Common strategies:
- TTL only: accept data up to N seconds old. Simple and often good enough.
- Delete on write: after updating the database, delete the cache key so the next read reloads it. Delete rather than update. Updating the cache from two concurrent writers can leave the older value in place.
- Versioned keys: put a version in the key (
user:42:v7), so a change creates a new key and the old one ages out.
Failure modes to plan for
- Cache stampede: a hot key expires and a thousand requests miss at once, all hitting the database. Fix it with request coalescing (one request reloads while the others wait), random jitter on TTLs, or serving stale data while one request refreshes in the background.
- Hot keys: one key gets so much traffic that its cache node saturates. The cluster looks fine on average while one node maxes out its CPU or network. See below.
- Cold start: after a restart the hit rate is zero, and a database sized for 10% of reads suddenly sees 100%. Warm caches gradually, or keep enough database capacity to survive a cold cache.
Finding and fixing hot keys
Detect them by looking for skew, not totals:
- Per-node metrics: one cache node with far higher CPU, network or operations per second than its peers is the first sign.
- Per-key counts: sample requests in the app or a proxy and keep a top-K list. A count-min sketch keeps the memory small. Redis can report its hottest keys with
redis-cli --hotkeyswhen the eviction policy is LFU. - Avoid
MONITORon a busy production Redis. It streams every command and can halve throughput.
Fix them by spreading or absorbing the load:
- Keep a small in-process cache with a short TTL (a second or two) for the hottest keys, so most reads never leave the app server.
- Replicate the key: write
trending#0totrending#9on different nodes and have each reader pick one at random. - Coalesce requests, so a thousand concurrent misses become one fetch.
In the game: each level sets a hit rate (85% in Database Meltdown). Adding the cache multiplies the reads reaching your database by 1 − hit rate. One cache costs less than one read replica and removes far more load, which is why it's the cheaper way through that level. In Thundering Herd, the hot keys expire twice mid-rush; request coalescing, TTL jitter or serving stale each stop the stampede for free.
Interview checklist
- Say what you're caching, where, and with which pattern (usually cache-aside).
- Estimate the hit rate and the database load that's left.
- Choose a TTL and an invalidation strategy.
- Mention stampede protection for hot keys.
- Say what happens if the cache is empty or down.
Level 4: Thundering Herd
Put this into practice against live traffic. Your progress in the game is saved in your browser.
Play level 4Do it by hand
Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.
Further reading
- Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly). The standard book on replication, partitioning and consistency.
- Site Reliability Engineering, Google's free book on running reliable systems.
- The Amazon Builders' Library: practical articles on timeouts, retries, caching and load shedding.
- The System Design Primer: a broad, community-maintained overview.