Why cache
A cache keeps the result of expensive work (a DB query, a computation, a remote call) in fast storage so repeated requests skip the work. If 90% of reads hit the cache, your database sees one tenth of the load, and p50 latency drops from milliseconds to sub-millisecond.
A cache is the spice rack next to the stove. The pantry (database) has everything, but walking there for salt every time would ruin dinner. You keep the few things you use constantly within arm's reach, and occasionally check whether they've gone stale.
Where caches live
| Layer | Hit cost | Shared? | Good for |
|---|---|---|---|
| Browser / app | 0 network | Per user | Static assets, user's own data |
| CDN | ~10–30 ms nearby | All users in a region | Images, video, JS, public API responses |
| In-process | ~100 ns | Per server | Config, feature flags, tiny hot sets |
| Distributed (Redis) | ~0.3–1 ms | All servers | Sessions, objects, counters, computed results |
| DB buffer pool | in DB | DB only | Automatic; why "add more RAM" helps |
Caching strategies
| Strategy | Read | Write | Pros | Cons |
|---|---|---|---|---|
| Cache-aside | App checks cache, loads on miss | App writes DB, deletes cache key | Simple, only caches what's used | First read is slow; brief staleness windows |
| Read-through | Cache loads from DB itself | — | Cleaner app code | Needs a cache that supports loaders |
| Write-through | — | Write cache and DB synchronously | Cache always fresh | Slower writes; caches unread data |
| Write-behind | — | Write cache; flush to DB later | Very fast writes, absorbs bursts | Data loss risk if cache dies |
| Refresh-ahead | Refresh popular keys before expiry | — | No miss latency for hot keys | Wasted refreshes on keys nobody reads |
On writes, delete the cache key rather than updating it. Two concurrent updates can set the cache in the wrong order and leave it permanently stale; a delete simply forces the next read to reload the truth.
Invalidation and TTLs
You have three tools, usually combined:
- TTL: every key expires after N seconds. Bounds staleness, even if everything else fails. Add random jitter (300 s ± 10%) so keys don't all expire together.
- Explicit invalidation: delete keys when the source changes, from the app or from a CDC stream.
- Versioned keys:
product:42:v17. Bumping the version makes old entries unreachable instantly.