Caching
Storing results so repeated work is avoided.
Caching can make a product dramatically faster and cheaper. It also introduces stale data and invalidation bugs. Knowing the cache layers, from the browser to the CDN to the database, helps you choose the simplest one that works.
Why it matters for a product engineer
A cache stores a result so the next request does not pay for it again. It can make a product much faster and cheaper to run. It also brings the hardest bugs in web development: stale data, and caches that disagree with each other. Knowing the layers, from the browser to the CDN to memory, lets you pick the simplest one that works.
How to do it
- Measure first: which requests are slow or expensive, and how often the same answer is asked for.
- Start with the cheapest layer. Correct HTTP cache headers on static files and public pages often give the biggest win.
- For application data, decide where it lives: in the memory of each server, in a shared cache such as Redis, or both.
- Decide how each entry stops being valid: after a time, or when the data changes.
- Build the invalidation with the same care as the cache, and test what happens in the wrong order.
- Watch the hit rate and the memory, and remove caches that do not pay for themselves.
Common mistakes
- Caching before measuring.
- Caching personal data in a shared layer, so one user sees another’s.
- No plan for invalidation, so users see old data for hours.
- A cache that hides a slow query nobody fixes.
- Every team adding its own cache to the same data.
Example
Stack Overflow keeps hot data in the memory of each web server, backed by Redis on a miss. To remove a value early, a server deletes it from Redis and then publishes the key on a purge channel; every web server drops its copy. The order matters: the other way round, a server could fetch the old value again. In 2019 their Redis handled about 1.6 billion commands a day at about 2% CPU.
How Stack Overflow removes a value from every cache
- 04Next request misses and reads the new value from Redis.
Two layers, one rule for removing data from both, and a fixed order so no server can bring the old value back.
ReportedNick Craver, 'Stack Overflow: how we do app caching', Aug 2019
Sources: Stack Overflow: how we do app caching, 2019 edition (Nick Craver) ↗ · HTTP caching (MDN Web Docs) ↗
Resources
2- articleStart here
Prevent unnecessary network requests with the HTTP cache ↗
web.dev (Google) · 2018 · 12 minA practical starting point for setting cache headers on assets and pages.
- docsGo deeper
HTTP caching ↗
MDN Web Docs · 25 minEverything about Cache-Control and revalidation, the cheapest performance win on the web.
Tools
2- ToolOpen source
Lighthouse
Open-source audits for performance, accessibility, SEO and best practices, built into Chrome.
- ToolOpen source