Lesson 5 of 38Building blocks
Caching
Choose where to cache, pick a read and write pattern, handle eviction and invalidation, and avoid cache stampedes.
When an interviewer says "the database is at 90% CPU and most traffic is reads", the first answer they hope to hear is add a cache. A cache keeps a copy of data in a faster place (usually memory) so you skip the slow work next time. Done well, it cuts latency from tens of milliseconds to one and takes 90% or more of the load off your database. Done badly, it serves wrong data to users.
Where caches live
Caches exist at every layer between the user and the disk. A request that is answered high up never touches the layers below.
The DNS, CDNs, and Client Caching lesson covered these two: HTTP headers decide what browsers and CDNs keep.
Read and write patterns
The question that defines a caching strategy is: who puts data in the cache, and when does the database get written? There are four classic answers. Step through each.
Cache-aside (lazy loading) is the default. The app checks the cache, and on a miss loads from the database and fills the cache itself. Writes go to the database and delete the cached key.
GET user:42 from Redis. Miss: the key is not there.
Pros: only data that is actually read gets cached, and if Redis dies the app still works (just slower). Cons: the first read of every key is slow, and there is a window where cache and database can disagree.
Write-through: every write goes to the cache and the database before the request returns. The cache is always warm and in sync.
The app writes the new value to the cache layer.
Pros: reads never see stale data. Cons: every write pays for two writes, and you cache data that may never be read.
Write-back (write-behind): writes go only to the cache and return immediately. The cache flushes them to the database later, often in batches.
The write lands in memory and returns in about 1 ms.
Pros: very fast writes, absorbs write spikes. Cons: if the cache node dies before flushing, those writes are lost. Fine for view counters and metrics, wrong for payments.
Write-around: writes go straight to the database and skip the cache. The cache only fills on reads (usually combined with cache-aside).
A user uploads a log entry. It goes directly to the database.
Pros: the cache holds only data people read. Cons: the first read after a write is always a miss.
Eviction: what to throw out
Memory is limited, so a full cache must evict something to make room. The policy decides what.
- LRU (least recently used): evict the key that has gone longest without being read. The default almost everywhere, because recently used data tends to be used again.
- LFU (least frequently used): evict the key with the fewest reads. Better when a few keys are popular for a long time and a one-off scan should not flush them.
- TTL (time to live): every key expires after a set time, whether or not the cache is full. This is less an eviction policy than a freshness guarantee, and you almost always set one.
Redis lets you choose with maxmemory-policy, e.g. allkeys-lru or allkeys-lfu. Run this tiny LRU with capacity 3 and watch the order.
Press Run (⌘ Enter) to see what happens.put x, put y, get x, put z. Which key is evicted?Hit rate math
The hit rate is the fraction of reads the cache answers. It controls both latency and how much load reaches the database.
Press Run (⌘ Enter) to see what happens.Going from 90% to 99% looks small but cuts database load 10x (1,000 QPS to 100). That is why teams obsess over the last few percent.
Hit rate 90%, a hit costs 1 ms, a miss costs 21 ms. Average latency?
print(round(0.9 * 1 + 0.1 * 21, 1))
Invalidation, stampedes, and thundering herds
There is an old joke that the two hard problems in computer science are naming things and cache invalidation. When the data changes, the cached copy is wrong until something fixes it. Your options:
- TTL only: accept data up to N seconds stale. Simple, and fine for most read-heavy content.
- Delete on write: after updating the database,
DEL user:42. The next read reloads it. Prefer deleting over updating the cached value, because two concurrent updates can write cache values in the wrong order. - Event-driven: the database change stream (CDC) publishes updates and a consumer invalidates keys. Used at large scale.
A cache stampede happens when a hot key expires and thousands of requests miss at the same instant, all run the same expensive query, and the database falls over. The broader version, many keys expiring together or a cold cache after a restart, is called a thundering herd. Fixes:
- Request coalescing (single flight): only one request rebuilds the key, usually by taking a short lock (
SET lock:key 1 NX EX 5); the others wait briefly or serve the stale value. - TTL jitter: add randomness (300 s ± 30 s) so keys written together do not expire together.
- Early refresh / stale-while-revalidate: refresh a hot key in the background shortly before it expires.
- Warm the cache before sending traffic to a new cluster.
Redis vs Memcached
| Redis (or Valkey) | Memcached | |
|---|---|---|
| Data types | Strings, hashes, lists, sets, sorted sets, streams | Strings only |
| Persistence | Optional (snapshots, append-only file) | None |
| Replication and failover | Yes (replicas, Sentinel, Redis Cluster) | No, client-side sharding |
| Threads | Mostly single-threaded command execution | Multi-threaded |
| Extra uses | Leaderboards, rate limiters, queues, pub/sub, locks | Pure cache |
Redis is the default choice today because one tool covers caching plus several other jobs you will meet in this unit. Memcached is still a fine, simple, very fast pure cache. (Valkey is the open-source fork of Redis that many cloud providers now run.)
LRU cache
Build the cache that sits in front of a slow database. It holds at most capacity entries. When it is full and a new key arrives, it evicts the least recently used key: the one that has gone longest without a get or a put.
get(key)returns the value, or-1if the key is missing. A successfulgetcounts as a use.put(key, value)inserts or updates the key and counts as a use. If that pushes the size pastcapacity, evict the least recently used key.
Both operations must be O(1).
cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
cache.get(1) # 10 (1 is now the most recent)
cache.put(3, 30) # evicts 2
cache.get(2) # -1- cache-aside
- The app reads the cache, loads from the DB on a miss, and fills the cache itself. Writes delete the key.
- write-through vs write-back
- Write-through writes cache and DB together; write-back writes the cache now and the DB later, risking loss.
- LRU
- Evict the least recently used key. The default eviction policy.
- hit rate
- The share of reads the cache answers. It sets latency and how much load reaches the database.
- cache stampede
- Many requests miss the same hot key at once and overload the DB. Fixed with locks, jitter, or early refresh.
- invalidation
- Removing or updating cached data when the source changes, by TTL, delete-on-write, or events.