System Design Playbook
12 · Performance & traffic9 min read

What is caching, and where can the cache live?

Keeping a copy of data somewhere faster and closer than its original source. The layers where a cache can live, from the browser to the database, how caches get filled and invalidated, and the problems they bring.

In one sentence

A cache stores copies of data that are expensive to get (slow query, far away server) so the next request can be answered from somewhere fast and close.

The idea

Reading from memory takes nanoseconds, from a database across the network milliseconds, and from a server on another continent a hundred milliseconds or more. Most apps also read the same popular data over and over: the trending video, the homepage, a user's profile.

A cache exploits that: the first request pays the full price, the next ones are served from the copy. Below, each request stops at the first layer that has the item. Toggle layers and watch the hit ratio, the latency and the load on the database.

A request falling through cache layers
Browserlocal cache~0 msCDNnear the user~15 msApp serverin-memory~2 msRedisshared cache~3 msDatabasesource of truth~45 ms
Requests
0
Cache hit ratio
0%
Avg. latency
0 ms
Queries reaching DB
0%
Each request stops at the first layer that has the item. Turn layers on and off: popular items get served close to the user, and the database only sees the misses.
Coloured squares are the items each cache currently holds. Popular items get requested much more often than the rest, as in real traffic.

Where can the cache live?

There isn't one cache. There is a chain of them between the user and the data, and a single request can cross several.

Where can a cache live?
↑ closer to the user · faster
↓ closer to the data · fresher

CDN / edge

What it stores

Copies of static files and cacheable responses in data centers around the world.

Example

Netflix and YouTube serve video chunks from servers near you.

Great for

Images, video, JS/CSS, public API responses.

Watch out

Personalized data must not be cached for everyone.

Tap a layer

How data gets into the cache

PatternHow it worksWhen
Cache-aside (lazy loading)App checks the cache; on a miss it reads the DB and stores the resultThe default for most apps
Read-throughThe cache itself loads from the DB on a missWhen a library or managed cache supports it
Write-throughEvery write goes to the cache and the DB togetherData that is read right after it's written
Write-back (write-behind)Writes go to the cache and are flushed to the DB laterVery high write rates where losing a few seconds is acceptable
async function getUser(id) {
  const cached = await redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);          // hit
  const user = await db.users.findById(id);       // miss
  await redis.set(`user:${id}`, JSON.stringify(user), "EX", 300);
  return user;
}

Invalidation: the hard part

A cache is a copy, and copies go stale. You need a rule for when a cached value stops being valid.

  • TTL (time to live): every entry expires after N seconds. Simple and safe; data can be stale for up to N seconds.
  • Explicit invalidation: when the data changes, delete or update the cache key. Fresh, but easy to forget one place.
  • Versioned keys: profile:42:v7. Changing the version makes old entries unused.

When the cache is full, an eviction policy decides what goes: LRU (least recently used) is the common default, LFU (least frequently used) keeps long-term favourites.

When to cache, and when not to

Cache it

  • Read far more often than written
  • Expensive to compute or fetch
  • Fine if it's a few seconds old (feeds, counts, catalogs)

Think twice

  • Must always be exact (bank balance at payment time)
  • Changes on almost every request
  • Rarely read twice, so the hit ratio would be low

Key takeaways

  • 01A cache trades freshness for speed by serving copies close to the user.
  • 02Caches live at every layer: browser, CDN, proxy, app memory, Redis, database.
  • 03Cache-aside with a TTL is the default; add explicit invalidation for data that must update fast.
  • 04Measure the hit ratio: a cache that rarely hits only adds complexity.

Check your understanding

1 of 3

What is a cache?

Related concepts