Caching
A cache stores the results of expensive work (database queries, API calls, rendered pages) somewhere faster, so the next request can reuse them. It's the most effective performance tool in system design: a cache in memory answers in under a millisecond what a database answers in 10–100 ms, and it shields the database from most of the load.
"There are only two hard things in computer science: cache invalidation and naming things." (Phil Karlton)
Where caches live
| Layer | Example | Caches |
|---|---|---|
| Browser | HTTP Cache-Control, service workers |
Pages, images, API responses for one user |
| CDN | Cloudflare, CloudFront, Fastly | Static files and public pages, near users worldwide |
| Load balancer / reverse proxy | nginx, Varnish | Whole responses |
| Application | Redis, Memcached, in-process memory | Query results, sessions, computed objects |
| Database | Buffer pool, query cache | Hot pages of data in RAM |
Cache-aside (lazy loading)
The most common pattern: the application checks the cache first; on a miss it reads from the database and stores the result, with an expiry time (TTL):
Real traffic is usually skewed like this (a few items are very popular), which is why caches work so well.
Writing: keeping the cache correct
When data changes, the cached copy becomes stale. Strategies:
| Strategy | How | Trade-off |
|---|---|---|
| TTL only | Let entries expire | Simple; data may be stale for up to the TTL |
| Invalidate on write | Update the database, then delete the cache key | Fresh data; the next read reloads it (most common) |
| Write-through | Write to cache and database together | Cache always warm; slower writes, caches data nobody reads |
| Write-behind | Write to the cache, flush to the database later | Fastest writes; risk of losing data |
Deleting rather than updating the cached value avoids a race where two concurrent writers leave the cache holding the older value.
Eviction: when the cache is full
Memory is limited, so caches evict entries. The usual policy is LRU (least recently used: you built one in the DSA track); alternatives include LFU (least frequently used) and Redis's approximated versions (maxmemory-policy allkeys-lru).
Caching pitfalls
The thundering herd (cache stampede)
A very popular key expires, and a thousand simultaneous requests all miss and hit the database at once:
Fixes: let only one request rebuild a key (a lock, or request coalescing), serve the stale value while refreshing in the background, and add random jitter to TTLs so keys don't all expire at the same moment.
Other problems to plan for
- Cache penetration: requests for keys that don't exist always miss. Cache "not found" results briefly, or use a Bloom filter.
- Hot keys: one key gets so much traffic that its cache node overloads. Replicate it, or keep a small in-process cache in front.
- Cold start: after a restart, the empty cache sends everything to the database. Warm it up gradually.
- Consistency: decide, per feature, how stale data may be. A product description can be a minute old; an account balance can't.
Practice
- Change the cache-aside simulation's TTL to 5 seconds. What happens to the hit rate and why?
- Add a maximum size to the cache with LRU eviction, and measure the hit rate with room for 10, 50 and 200 products.
- Decide a caching strategy (TTL, invalidation, or no caching) for: a product page, a shopping cart, stock levels, a user's profile picture.
1.In cache-aside, what happens on a cache miss?
2.After updating a row, why delete the cached key rather than overwrite it?
3.What is a cache stampede?