Caching is the cheapest performance win and the easiest way to ship stale bugs. This guide walks through the layers of a cache and how to invalidate them without regret.
Think in layers
A request can be answered at several points: the browser, a CDN at the edge, your application, or the database. The closer to the user a response is served, the faster it is, and the harder it is to change once it is out there.
- Browser cache: controlled with Cache-Control headers; ideal for hashed static assets.
- CDN or edge cache: great for public pages and images; use short lifetimes or purge on publish.
- Application cache (for example Redis): good for expensive queries and computed results.
- Database cache: query plans and buffer pools, mostly handled for you.
Pick the right pattern
Cache-aside is the most common: the app checks the cache, falls back to the database on a miss, then stores the result. Write-through updates the cache whenever data is written, which keeps reads fresh at the cost of slower writes.
Invalidation is the real problem
Time-based expiry (TTL) is simple and forgiving. Event-based invalidation, such as purging a page when an editor publishes, is precise but needs discipline. Many teams combine both: a modest TTL as a safety net, plus targeted purges for important changes.
Guard against the classic traps
- Cache stampede: many requests rebuild the same expired entry at once. Use locking or stale-while-revalidate.
- Caching personalised or private data in a shared cache.
- Having no way to see hit rates, which makes the cache impossible to tune.
Measure first, cache the slowest and most repeated work, and always know how you will clear it.



