Lesson 4 of 16
12. Caching: The Basics

12.3 Where does a cache physically live?

3 min read+10 XP

In the kitchen: Two options. A snack in your pocket (instant, but only you can use it, and it's gone when you change clothes) or a shared pantry for the whole flat (everyone uses the same shelf, but you take a few steps to reach it).

In the system:

KitchenWhereExampleGoodNot so good
PocketInside your app's memoryA dictionary, or a library like CaffeineFastest, no networkEach app server has its own separate copy; lost when the app restarts
PantryOn a separate cache serverRedis, MemcachedOne shared copy for all your app serversOne network hop; one more system to run

Those are the two you build yourself. Along a real request there are more layers, from closest to the user to closest to the data:

browser, CDN edge, in-app pocket, Redis pantry, database buffer cache.

Figure: caches at every layer. Cache as close to the user as the data allows.

  • Browser: keeps copies of images, scripts and some API responses on the user's device (HTTP caching, Chapter 13).
  • CDN edge: keeps public content near users worldwide (Chapter 26).
  • Pocket and pantry: your app's own caches.
  • The database's buffer cache: the database keeps hot pages in its own memory. You get it for free, but it still pays for parsing and planning every query (12.2).

Memory code: "Pocket or Pantry." In-app cache = your pocket (fast, private). Redis = the shared pantry (shared, a short walk).