Caching

Lesson 3.3 · 8 min read · by Vinay C

We'll cover the following

Visual summary

Infographic summarizing Caching: Imagine a product page that 10,000 people load every second. Each load runs the same database query, and each query…

Download imageFree to share, please link back to this lesson.

The problem: the same question, asked 10,000 times a second

Imagine a product page that 10,000 people load every second. Each load runs the same database query, and each query takes about 5 ms. The database is now doing 10,000 identical jobs a second to return the same answer. Meanwhile the answer barely changes.

A cache is a small, fast store (usually memory) that keeps recent answers so you can skip the slow source. Reading from a memory cache takes under 1 ms, and it takes load off the database. The words you need:

  • Cache hit: the answer was in the cache. Fast.
  • Cache miss: it was not, so you go to the database, then usually save the result in the cache for next time.
  • TTL (time to live): how long an entry may stay before it expires, e.g. 60 seconds.
  • Eviction: removing entries to make room, because the cache is smaller than the database.

Where caches sit

A request can be answered at several points on its way to the data. The closer to the user, the faster it is, but the harder it is to keep fresh.

browser -> CDN -> app server -> app cache (Redis) -> database
(user's    (edge     (small local   (shared, in memory)   (slowest,
 device)    servers)  in-process)                          source of truth)

Most interview answers focus on the application cache (Redis or Memcached), because that is the one you design and control.

Cache-aside: the default strategy

In cache-aside, your application code talks to both the cache and the database. The cache never talks to the database by itself. Here is the full read and write flow:

READ product 42
  1. look in cache for key product:42
  2. hit  -> return it (done, under 1 ms)
  3. miss -> read the DB (about 5 ms)
  4. put the result in the cache with a TTL (say 60 s)
  5. return it

WRITE product 42
  1. update the DB (the source of truth)
  2. DELETE product:42 from the cache
  (the next read misses and refills it with the new value)

Why delete on write, not update?

It feels natural to write the new value into the cache. That fails when two writers run at the same time, because the DB write and the cache write are two separate steps and they can interleave:

Update-on-write (broken):
  t1  writer A: DB = 1
  t2  writer B: DB = 2
  t3  writer B: cache = 2
  t4  writer A: cache = 1      <- A was slow
  Result: DB says 2, cache says 1 -> stale until the TTL ends

Delete-on-write:
  t1  writer A: DB = 1
  t2  writer B: DB = 2
  t3  writer B: delete cache
  t4  writer A: delete cache
  Result: cache is empty; the next read loads 2 from the DB

Deleting is safe in any order because it does not carry a value that can be out of date. The TTL stays on as a backstop for the rarer races that remain.

The three write strategies

StrategyHowTrade-off
Cache-aside (default)App reads the cache, fills it from the DB on a miss. On write: update the DB, then delete the cache entry.Simple, the app manages it. Delete (not update) avoids stale-write races.
Write-throughWrite to the cache and the DB together.Always fresh, but every write is slower.
Write-backWrite to the cache only, flush to the DB later.Very fast, but data is lost if the cache dies before the flush.

How to choose

  • Start with cache-aside. It fits most read-heavy systems and the cache can go down without losing data.
  • Use write-through when readers must see a write right away and you can afford slower writes.
  • Use write-back only when losing a few seconds of data is fine, such as a view counter that is flushed in batches. Never for money or orders.
  • Cache only what is read far more than it is written. Data that changes on every read gains nothing.

Eviction, sizing and staleness

The cache is smaller than the database, so something must go when it fills up. LRU (least recently used) throws out the entry untouched for the longest time. It is the default answer. A TTL separately limits how long any entry can live.

How big should it be? By the 80/20 rule, about 20% of the data gets about 80% of the reads. Cache that hot 20%, not everything.

TTL also sets how stale users may see data. With a one-hour TTL, a change in the DB can stay invisible for up to an hour. You have three choices: a short TTL, delete the entry on every write (invalidation), or accept staleness where it does not matter (a like count can lag, a price should not).

Four ways a cache fails

A cache that works at normal load can still hurt you in these four situations. Picture each, then know the fix.

ProblemThe pictureFix
StampedeA hot key expires at noon. In the next millisecond 10,000 requests all miss and all hit the DB at once.Request coalescing (the first request refills, the rest wait for it), a lock, or refresh the key before it expires.
PenetrationSomeone asks for ids that do not exist. They are never in the cache, so every request goes to the DB.Cache the "not found" result with a short TTL, or put a Bloom filter in front (see the Bloom filter lesson).
Hot keyOne celebrity profile gets huge traffic. It lives on one cache node, which is overloaded while the others sit idle.A small local in-process cache on each app server, replicate the key as key#1..#5 across nodes (read a random copy), or read replicas.
Cold startThe cache restarts empty. Every request misses and the DB is flooded.Warm the cache before sending traffic to it.

The hot key insight: adding more cache nodes does not help, because the key still lives on only one of them. Sharding spreads keys evenly, not traffic. The same idea returns as a hot partition in DynamoDB.

Check yourselfA celebrity key expires at noon and 10K requests arrive at once. What happens?

Cache stampede: all 10K miss and hit the DB together. Fix with request coalescing or a lock so one request refills it, or refresh the key before it expires.

Check yourselfYour cache has 20 nodes, but one celebrity profile still overloads one of them. Why does adding 20 more nodes not fix it, and what does?

A key lives on exactly one node, so more nodes only spread other keys, not the traffic for this one. Copy the hot key instead: a local in-process cache on each app server, or store it as key#1..#5 on different nodes and read a random copy.

Summary: say it in the interview

  • "Cache-aside with delete-on-write: simple, and it avoids stale-write races."