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.
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
DELthe 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.
Open the page a few times, change the price, open it again and see which price you get. Then switch modes and do it again. The times are the model's (Redis about 1 ms, the database 40 ms), not measurements
Cache-aside with a 60 s TTL. A product's price has just changed in the database, and nobody touched the cache. Which price does someone opening the page now see?
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.
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.
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?
| Way | A read | After a change | Costs |
|---|---|---|---|
| No cache | The database, every time | Always fresh | The database does all the work |
| TTL only | Redis, after the first miss | Old until the TTL runs out | Nothing extra, but stale data |
| Delete on write | Redis, after the first miss | The next read misses, then fresh | One more database read per change |
| Write-through | Redis | Fresh at once | A 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 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`);
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 4Ask 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.
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.
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.
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.
Next lesson
Database indexesLevel: Intermediate
A miss still goes to the database; next, an index makes that read fast.