Caching
Where to cache, cache-aside, read-through, write-through and write-behind patterns, eviction and TTLs, invalidation, stampedes, hot keys, and consistency pitfalls.
A cache stores the results of expensive work (database queries, computations, remote calls) in fast storage, so repeated requests are served quickly. Caching is the most effective performance tool in system design — and the source of some of its trickiest bugs.
"There are only two hard things in computer science: cache invalidation and naming things." — Phil Karlton
Where caches live
The closer to the user, the faster and cheaper, but the harder to invalidate.
Caching patterns
Cache-aside (lazy loading) — the most common
User getUser(long id) {
String key = "user:" + id;
String cached = redis.get(key);
if (cached != null) return json.read(cached, User.class); // hit
User u = db.findUser(id); // miss
if (u != null) redis.setex(key, 600, json.write(u));
return u;
}
void updateUser(User u) {
db.update(u);
redis.del("user:" + u.id()); // invalidate (don't update) the cache
}def get_user(uid: int):
key = f"user:{uid}"
if (cached := r.get(key)) is not None:
return json.loads(cached)
user = db.fetch_user(uid)
if user:
r.setex(key, 600, json.dumps(user))
return user
def update_user(user):
db.update(user)
r.delete(f"user:{user['id']}")async function getUser(id: number) {
const key = `user:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const user = await db.findUser(id);
if (user) await redis.set(key, JSON.stringify(user), { EX: 600 });
return user;
}Other patterns
| Pattern | Writes go | Pros | Cons |
|---|---|---|---|
| Cache-aside | DB, then invalidate the cache | Simple; the cache holds only what's read | First read is slow; possible stale windows |
| Read-through | — (the cache loads from the DB itself on a miss) | Loading logic centralised in the cache layer | Needs a cache that supports loaders |
| Write-through | Cache and DB synchronously | Cache always fresh | Slower writes; caches data that's never read |
| Write-behind (write-back) | Cache now, DB asynchronously | Very fast writes, batching | Data loss if the cache dies before flushing |
| Refresh-ahead | Refresh popular keys before they expire | Avoids miss latency for hot keys | Wasted refreshes |
Eviction and expiry
Caches are smaller than the data, so something must go:
- LRU — evict the least recently used. The usual default.
- LFU — evict the least frequently used; better for stable popularity.
- TTL — every entry expires after a time; bounds staleness even if invalidation fails.
- Size limits and policies are configurable (
maxmemory-policy allkeys-lruin Redis).
More on the algorithms: Page replacement.
Invalidation: keeping the cache honest
Strategies:
- TTL only — accept up to TTL seconds of staleness. Simplest; often enough.
- Explicit invalidation on write (delete the key).
- Event-driven — publish change events (or tail the DB log) and invalidate everywhere, including in-process caches on every instance.
- Versioned keys —
user:42:v7; bump the version on change and old entries simply age out.
Failure modes
| Problem | What happens | Fix |
|---|---|---|
| Cache stampede (thundering herd) | A hot key expires and thousands of requests hit the DB at once | Request coalescing / single-flight lock, early probabilistic refresh, stale-while-revalidate |
| Cache penetration | Requests for keys that don't exist always miss and hit the DB (possibly an attack) | Cache negative results briefly; Bloom filter of valid keys |
| Cache avalanche | Many keys expire at the same moment, or the cache cluster restarts | Add random jitter to TTLs; warm the cache; replicas |
| Hot key | One key gets a huge share of traffic and overloads one cache node | Local in-process cache in front, replicate the key, split it |
| Cold start | After a deploy or cache flush, everything misses | Warm gradually; protect the DB with rate limits |
What (not) to cache
- ✓ Read-heavy data that changes rarely: profiles, product catalogues, configuration, rendered pages, expensive aggregations.
- ✓ Results of slow external calls (with care about staleness).
- ✗ Data that must always be exactly current: account balances during a transaction, inventory at checkout — read from the source of truth.
- ✗ Highly personalised data with low reuse (a poor hit rate costs memory for nothing).
Measure the hit ratio: a cache with a 30% hit rate may cost more than it saves.
- Cache at every layer: client, CDN, proxy, in-process, distributed, database.
- Cache-aside is the default: read from cache, on miss load from the DB and populate; on write, update the DB and delete the key.
- Write-through keeps the cache fresh; write-behind is fast but risks loss.
- Always use TTLs; prefer delete over update to avoid races.
- Guard against stampedes, penetration, avalanches and hot keys.
QHow do you prevent a cache stampede on a very popular key?medium
Let only one request recompute the value while others wait or receive the stale value (single-flight / mutex in the cache, stale-while-revalidate), refresh the key shortly before expiry (probabilistic early expiration), and add TTL jitter so many keys don't expire together.