Guide

A cache stores the result of expensive work, so the next request can skip the work. A hit means the answer was in the cache. A miss means the work ran. Caches don't live in one place. They sit at almost every layer between the user and the disk.

The big idea

Picture a stack of shelves between a customer and a warehouse. The shelf by the door is the fastest to reach, and it saves the most trips. It is also the hardest to restock, because you can't reach into every customer's home. The shelf in the back room is slower but easy to control.

Each layer trades speed against control. The browser cache is fastest, and you control it least. The database's buffer pool is slower to reach, and it manages itself.

Walking through it

LayerExampleTypical hit latencyGood forHow it's invalidated
ClientBrowser cache, mobile app storageAbout zero, no networkStatic assets, rarely changing dataHard. Use versioned URLs
CDNCloudflare, CloudFront, Fastly5–30 msImages, video, JS and CSS, public pagesPurge APIs and short TTLs
Reverse proxyNginx, VarnishAbout 1 msWhole HTTP responsesPurge and TTL
In-processAn LRU map, Caffeine, lru-cacheAbout 100 nsTiny, very hot, rarely changing dataPer process. Copies drift
DistributedRedis, Memcached, Valkey0.2–1 msShared data across many serversExplicit deletes and TTLs
DatabaseBuffer pool in Postgres or InnoDBInside the queryHot pagesAutomatic

Most systems use several at once. A product page might come from the CDN for anonymous visitors. A logged-in request might read product data from Redis and fall back to Postgres, whose buffer pool keeps hot pages in RAM.

Common mistakes

  • Forgetting which layer is serving stale data. When a user sees an old page, check the CDN, the browser and the proxy, in that order.
  • Counting on client caches. You can't reach into a phone to delete a copy. Use versioned URLs, so a new version gets a new address.
  • Trusting in-process caches across servers. Each process holds its own copy, so N servers can hold N versions.

Check yourself

  1. Why are in-process caches hard to keep consistent across servers? Each process has its own copy, so the copies drift apart whenever the data changes.
  2. Why do versioned URLs help with client caches? A new version gets a new URL, so devices fetch it fresh without you deleting anything on them.

Key takeaways

  • A cache can sit at any layer, from the browser to the database buffer pool.
  • The closer a cache is to the user, the more it saves and the harder it is to invalidate.
  • Use several layers together, and know which one serves each request.

Further learning

The CDN and edge page covers the outer layer in depth.

Next, read about cache patterns, which decide how data gets into a cache.