Caching

The same product page, read again and again. Put Redis in front of the database and watch hits, misses and a TTL, then change the price and see who still shows the old one.

Level: BasicWatch: 12 steps · ~1 minuteRead, change the price, waitRecall: 3 questions · 8 cardsCompare 4 waysTypeScript · redis-cli · nginx

What you'll take away

  • Explain cache-aside: ask Redis first, and on a miss read the database and SET a TTL
  • Pick a TTL by how long the data can be out of date before anyone minds
  • Fix stale reads: write the database, then DEL the key, and keep a TTL as a safety net
  • Spot a cache stampede when a hot key expires, and let one request rebuild it

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
No cachethe database, every time
you · the product page
the app
Redis · not used
DatabaseDB · price 990
t = 0 s (simulated)
Open the product page → …
Step 1 / 12 · step by step
–hit rate
0 msAvg read (simulated)
0Database reads
0Stale reads

The picture: you on the plaza, the app up the avenue, Redis the low building next door and the database at the far end of the street. The moving light is a request; the slab on Redis's roof is the cached price (red once the database says otherwise) with its time to live as the bar beside it; the dots on the pavement are your reads (teal a hit, amber a miss, light blue straight to the database, red the old price). The times are the model's (Redis about 1 ms, the database 40 ms), not measurements.

Step 4 · Every option at once, on one clock

Compare them all: Caching

The same story in every tile: three reads of the product page, the price changes from 990 to 890, two more reads, a minute passes, two more reads. See which is fast, which keeps the database busy, and which shows the old price.

0.0 s · a read
No cachethe database, every timeDB reads 0 · avg 0 ms · stale 0

Use it when Data that is rarely read, or a database that copes easily: nothing extra to look after

Skip it when The same page read thousands of times a second: the database does the same work over and over and everything slows

A model: TTL 60 s, Redis about 1 ms, the database 40 ms (made-up figures, not measurements). The dots under each picture are the reads. Press any tile to see it large above, with when it fits.

What happens when the data changes?

WayA readAfter a changeCosts
No cacheThe database, every timeAlways freshThe database does all the work
TTL onlyRedis, after the first missOld until the TTL runs outNothing extra, but stale data
Delete on writeRedis, after the first missThe next read misses, then freshOne more database read per change
Write-throughRedisFresh at onceA SET on every write, memory for values nobody reads

A cache is a copy

Redis doesn't know what happens in your database. It holds a copy and answers with it until the copy expires or you remove it. So every cache needs an answer to one question: when the data changes, who tells the copy? A TTL is the longest it can be wrong; deleting the key on write makes it right sooner.

Delete after the write, and keep a TTL

Write the database first, then delete the key. Delete first, and a reader in between can put the old value back. Even in the right order, a slow reader can still race you, so keep a TTL as the safety net. And when a hot key expires, don't let a thousand requests rebuild it at once: one fetches, the rest wait (a lock, or nginx's proxy_cache_lock).

What not to cache

Things read once, things that change on every request, and anything personal under a key that someone else could hit. If the cache goes down, the app should still work, only slower; plan for the database taking the full load for a moment.

In real code

cache-aside.ts
// Cache-aside with a TTL: ask the cache first; on a miss read the database and keep the answer for 60 seconds.
// The cache has Redis's shape (get / set with EX / del). A Map with expiry times stands in so the file runs
// anywhere; with the `redis` package it's `await client.get(key)`, `client.set(key, value, { EX: 60 })`, `client.del(key)`.
// The clock is ours too, so "61 seconds later" takes no time.
// Run: node cache-aside.ts   (Node 23.6+; on Node 22: node --experimental-strip-types cache-aside.ts)
import assert from "node:assert/strict";

let now = 0; // seconds
const store = new Map<string, { value: string; expires: number }>();
const cache = {
  get(key: string): string | null {
    const e = store.get(key);
    if (!e || e.expires <= now) { store.delete(key); return null; } // Redis drops an expired key the same way
    return e.value;
  },
  set(key: string, value: string, opts: { EX: number }) { store.set(key, { value, expires: now + opts.EX }); },
};

const db = { products: new Map([[42, { id: 42, price: 990 }]]), reads: 0 };
function readProductFromDb(id: number) {
  db.reads++;
  const row = db.products.get(id);
  if (!row) throw new Error(`no product ${id}`);
  return { ...row };
}

function getProduct(id: number): { id: number; price: number; from: "cache" | "db" } {
  const key = `product:${id}`;
  const hit = cache.get(key);
  if (hit !== null) return { ...JSON.parse(hit), from: "cache" };
  const row = readProductFromDb(id);
  cache.set(key, JSON.stringify(row), { EX: 60 });
  return { ...row, from: "db" };
}

const seen = [getProduct(42), getProduct(42), getProduct(42)].map((p) => p.from);
assert.deepEqual(seen, ["db", "cache", "cache"]);
assert.equal(db.reads, 1); // three reads, one trip to the database

now += 61; // the TTL has run out
assert.equal(getProduct(42).from, "db");
assert.equal(db.reads, 2);

console.log(`reads: ${seen.join(", ")} · 61 s later: db again · database reads: ${db.reads} of 4`);
Run: node cache-aside.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: reads: db, cache, cache · 61 s later: db again · database reads: 2 of 4

Ask the cache, on a miss read the database and SET the answer for 60 s. A Map with expiry times stands in for Redis so the file runs anywhere; with the redis package it's the same get / set with EX / del. The clock is the file's own, so 61 seconds take no time.

Common questions

What is cache-aside?

The app does all of it: ask the cache first, use the answer on a hit, and on a miss read the database and SET the answer with a TTL. The cache never talks to the database itself.

How long should the TTL be?

Ask how long the data can be behind before anyone minds. View counts can lag for minutes; prices and permissions shouldn't. A shorter TTL is fresher but misses more, and don't let lots of keys expire at the same moment.

The price changed. Why do people still see the old one?

The cache holds a copy and doesn't know the database changed. With only a TTL, everyone gets the old value until it expires. Delete the key when you write (or SET the new value) and the new one shows up sooner.

On a write, should I delete the key or SET the new value?

SETting it (write-through) makes the next read a hit at once, but spends memory on values nobody may read. Deleting the key costs one database read, then the cache fills with only what's really read, and it's simpler.

Table: when the data changes

Why write the database first and delete the key after?

Delete first, and a reader in between misses, reads the old row and puts the old value back. Even in the right order a slow reader can still race you, so keep a TTL too.

Read: delete after the write

What happens when a popular key expires?

Everyone misses at the same moment and a thousand requests read the same thing from the database at once (a cache stampede). Let one rebuild it while the rest wait, with a lock or nginx's proxy_cache_lock.

Read: delete after the write

What shouldn't go in a cache?

Things read once, things that change on every request, and anything personal under a key someone else could hit. And on the day the cache is down, the app should still work, only slower.

Read: what not to cache

Next lesson

Database indexesLevel: Intermediate

A miss still goes to the database; next, an index makes that read fast.