Caching Strategies — System Design

A cache keeps a copy of data somewhere fast (for example Redis, an in-memory database) so the main database isn't called every time. A hit means the data is…

The Archipelago Concert price on TicketTune drops from $75 to $70. The database has changed, but users still see $75. How?

This is like the price board at a coffee stall. Prices are written on the board so the cashier doesn't have to open the stock book every time someone asks. But if a price goes up and nobody wipes the board, customers see the old price. Here the cashier is the application, and the stock book is the database. The price board is the cache: a copy of data kept somewhere faster to reach, so the application doesn't have to go to the original source (usually the database) every time. The rules for when that copy is filled, updated and thrown away are called a caching strategy.

Hit, miss and hit ratio

TicketTune keeps concert data in Redis (a very fast in-memory database) under the key (the name it is stored under) event:42. When a request finds the data in the cache, that's a cache hit. When it doesn't, that's a cache miss, and the data has to come from PostgreSQL, TicketTune's main database. Hit ratio = hits ÷ total requests.

The Lab's example model: 50 read requests a second (one every 20 ms) for 60 seconds, so 3,000 requests. During the ticket war, one query (a command to the database) takes 200 ms. At second 20 the price drops. Caches can live in many places (browser, CDN, application server, database). This lesson is about the application cache in Redis.

Cache-aside

The most common strategy: the application checks the cache first. On a miss, it reads the data from the database, then stores it in the cache. It's also called lazy loading (loading only when needed), because data only enters the cache when someone asks for it. Here is TicketTune's read function with cache-aside:

// Read: cache-aside with a 30-second TTL (ioredis + node-postgres)
async function getEvent(id) {
  const key = "event:" + id;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached); // hit

  const { rows } = await pool.query("SELECT * FROM events WHERE id = $1", [id]); // miss: 200 ms
  await redis.set(key, JSON.stringify(rows[0]), "EX", 30); // store it, deleted automatically after 30 seconds
  return rows[0];
}

The result in the model: of 3,000 requests, only 20 miss. The hit ratio is 99.3% (2,980 hits ÷ 3,000).

TTL and cache stampede

Where do those 20 misses come from? At second 0 the cache is still empty. While the first query runs (200 ms), 10 requests arrive, counting that first request. All of them miss, and all of them run their own database query. The same happens again when the key expires: 10 more misses, so 20 in total. This is a cache stampede (also called thundering herd): a key disappears, then many requests hit the database at once. In a ticket war, 10 can become 10,000, and the database stops working exactly when it's needed most. The same effect appears when many keys are created with the same TTL and expire together.

The cures:

The TTL is a trade-off too. With a 5-second TTL, the hit ratio drops to 96.0% and the database gets 120 queries. With a 5-minute TTL, the hit ratio is 99.7%, but old data stays for a long time, as the next section shows.

Invalidation: when the data changes

At second 20, the price changes in the database, but event:42 in Redis still holds $75. Users keep seeing the old price until that key expires. In the model, the 10 queries from the first stampede each write the key again with a fresh TTL. The last one finishes at second 0.38, so the key expires at second 30.38. So users still see $75 until about second 30. That's 519 requests reading the old price. Reads of old data from the cache are called stale reads. With a 5-minute TTL, the old price lasts to the end of the model: 2,000 stale reads.

Invalidation means throwing the copy in the cache away when the original data changes. This code changes the price in the database, then deletes the key:

// Write: change the database, then delete the key
async function updatePrice(id, price) {
  await pool.query("UPDATE events SET price = $1 WHERE id = $2", [price, id]);
  await redis.del("event:" + id); // the next request misses and reads the new price
}

The result is 0 stale reads. The cost is one extra burst (group) of misses at second 20, because the key was just deleted.

⚠️ That 0 comes from the model, and the model leaves out one order of events. When the site is busy, del still leaves a gap:

  1. Request A misses and reads the old price from the database (the query takes 200 ms).
  2. Meanwhile, updatePrice writes the new price to the database and deletes the key.
  3. A's query finishes, and A writes the old price to the cache.

This order was tested with getEvent and updatePrice above, using a fake Redis and database. The result: the database has the new price, but the cache has the old one until the TTL ends. That is why the TTL stays as a safety net: the wrong copy is still deleted when the TTL ends. If this gap is not acceptable, there are two other ways:

Way When to pick it
Delete twice (delayed double delete): del, then del again after waiting a little longer than one query takes the cheapest way, enough for most data
Versioned key: the key holds a version number (event:42:v7), and an update raises the number an old copy is never read again; the cost is one extra read to learn the latest version

Write-through and write-back

Two other strategies take care of the cache when writing (changing data). DB in this table means database.

Strategy When the price changes Strength Risk
Cache-aside write the DB, delete the key (or wait for the TTL) only requested data enters the cache the first miss is slow, stale reads if you forget to delete
Write-through write the DB and the cache together the cache is always fresh, 0 stale reads every write does twice the work; the cache can hold data that's rarely read
Write-back (write-behind) write the cache first, the DB follows (in the model, 5 seconds later) very fast writes data is lost if the cache stops before it's written to the DB

In the write-back model, Redis restarts (starts again with empty memory) at second 22, before the flush (the write to the database) at second 25. The price change is lost: the database stays at $75, and the 1,900 requests after it read the wrong price. So write-back fits data that may lose a little, such as view counts (how many times a page was seen), not prices or money.

When is cache-aside better than write-through? When data rarely changes and not all of it needs caching. With cache-aside, only the concerts people are actually opening end up in Redis.

Two other read strategies are often named next to cache-aside. Read-through: the cache library or service itself reads from the database on a miss, so the application code talks only to the cache. Refresh-ahead: popular keys are refreshed before their TTL ends, so readers do not get a miss. The cost is queries for keys that may not be read again.

📌 The browser cache: Cache-Control and ETag

Browsers keep a cache too, controlled by headers (extra information) from the server. Details are in the API Caching lesson.

⚠️ Stale prices and a database that stops working

TL;DR: A cache keeps a copy of data somewhere fast (for example Redis, an in-memory database) so the main database isn't called every time. A hit means the data is found in the cache, a miss means it isn't, and hit ratio = hits ÷ total. Cache-aside: check the cache, on a miss read the database and store the result with a TTL (how long the copy lives before it is deleted). It's the most common strategy, and fits when data rarely changes and not all of it needs caching. When a copy in the cache disappears, many requests can hit the database at once: a cache stampede (thundering herd). The cures are a lock (only one request reads the database), jitter (random seconds added to the TTL) and pre-warming (filling the cache first). When data changes, delete its copy in the cache (invalidation). Otherwise users read stale (old) data until the TTL ends. Write-through writes the cache and the database together (consistent, slower writes). Write-back writes the cache first and the database later (fast, but data can be lost). In the browser, max-age=31536000, immutable = keep it a year with no revalidation (no asking the server again). ETag = a version tag from the file's content, Last-Modified = the timestamp (time) of the last change.

⚡ Cache-aside: check the cache first

Write:

const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // hit

const { rows } = await pool.query("SELECT * FROM events WHERE id = $1", [id]); // miss: 200 ms
await redis.set(key, JSON.stringify(rows[0]), "EX", 30); // store it, deleted automatically after 30 seconds

Meaning: key here holds "event:42", the name of concert 42's copy in the cache. The code checks the cache (Redis) first. On a hit (the data is found in the cache), the data is returned right away without touching the database. On a miss (not found), the code reads the database, then stores the result with a 30-second TTL: how long the copy lives before Redis deletes it. In the example model of the ticket app TicketTune, the hit ratio (the share of requests that hit) is 99.3%.

⚡ Cache stampede

Guess first: the copy of the concert data in the cache (key event:42) expires, then 10 requests arrive at once. How many queries (read commands) reach the database?

Ten: all of them miss, and each runs its own query. In a ticket war, 10 can become 10,000.

Meaning: This is called a cache stampede. The cures are a lock (only the first request queries, the rest wait), jitter (random seconds on the TTL so keys don't expire together), and pre-warming (filling the cache first). In the 60-second model, a lock cuts the database queries from 20 to 2.

⚡ Delete the key when data changes

Write:

await pool.query("UPDATE events SET price = $1 WHERE id = $2", [price, id]);
await redis.del("event:" + id); // the next request misses and reads the new price

Meaning: When the price changes, this code changes the database, then deletes the key in Redis (invalidation). Without invalidation, users read the old price until the TTL ends: in the model there are 519 stale reads (reads of old data). With redis.del, zero.

⚡ Write-through and write-back

Meaning: Write-through writes the cache and the DB (database) together, so the cache is always fresh. Write-back (write-behind) writes the cache first and the DB follows later: fast, but the data is lost if the cache stops before the flush (the write to the DB). Don't use write-back for prices or money.

What you will learn