Opening: The Key Was Deleted, the Old Title Still Shows
A teacher renames their track. The backend code is correct: update the database, then delete the cache key. Manual tests pass.
The next day the teacher writes: "The old title still shows in the app." You check the database: new title. You check Redis: the old title, with 58 minutes of TTL left.
Nobody forgot to delete the key. What happened is a race: a request read the old title from the database just before it changed, then wrote it to the cache just after the key was deleted. Section 2 reproduces it.
Part 3 covered where to put caches. This part covers the harder question: how a cache stays correct, and how to tell whether it really helps.
Warm-Up Quiz: Do You Still Remember?
Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.
Question 1. The writer updates the database, then deletes the key. Why can the cache still hold the old value?
- A. Redis sometimes fails to delete keys
- B. A slow reader read the old value before the write, then stored it in the cache after the key was deleted
- C. The TTL is too short
Show the answer to question 1
B. This is the classic cache-aside race. The key deletion lands in the middle of someone else's read. Section 2 reproduces it and shows the fix with version numbers.
Question 2. 2,000 keys are filled at the same time with a fixed TTL of 2 seconds. What happens when they expire?
- A. Nothing, Redis deletes them gradually
- B. They all expire together, and 2,000 database queries arrive in the same 100 ms
- C. Redis automatically extends the TTL of frequently read keys
Show the answer to question 2
B. The test in section 4: a peak of 2,000 queries in one 100 ms window. With a random TTL of ±25%, the peak drops to 227, spread across 11 windows.
Question 3. What does stale-while-revalidate mean?
- A. Stale data is deleted and the user waits for fresh data
- B. Stale data keeps being served while fresh data is fetched in the background
- C. Data only refreshes when the user taps refresh
Show the answer to question 3
B. Users never wait for the database. The test in section 5: p99 dropped from 302 ms to 2 ms with the same number of database queries.
Question 4. One viral track is read 20,000 times in 4 seconds from 4 instances. The simplest way to reduce load on one Redis node is...
- A. Add Redis nodes
- B. A copy in process memory with a 1-second TTL, plus single-flight per instance
- C. Remove caching for that track
Show the answer to question 4
B. The test in section 6: from 20,000 GETs to Redis down to 16. Without single-flight, the local copy still produced 2,000 GETs, because every request on an instance refills at the same moment.
Question 5. Your cache has a 10% hit rate. What does that mean?
- A. Good, 10% of requests are faster
- B. 90% of requests pay for two trips (cache, then database). This cache may add latency and cost, and needs a look
- C. Nothing, hit rate does not matter
Show the answer to question 5
B. A cache that rarely hits adds a network trip to almost every request. Measure hit rate per key type, and section 7 shows why the number depends so much on the shape of your traffic.
1. Two Things Always Said Together
Every time someone says "let's just cache it", two questions must be answered together:
- What gets cached? Public data that is read often and changes rarely is the best candidate.
- How does the cache stay correct? How stale data may be, and what happens when it changes.
There are three basic tools, usually used together:
| Tool | How it works | When to use it |
|---|---|---|
| TTL | The key expires automatically after a while | Always, as a safety net |
| Delete the key on change | The writer deletes the key after updating the database | Data whose changes must show quickly |
| Versioned keys | The version goes into the key name: track:123:v7 | When the latest version is easy to know, say from a parent document or URL |
Versioned keys have an often forgotten advantage: you never have to delete anything. A new version means a new key, and the old key is dropped by its TTL or the memory policy. Same pattern as versioned URLs on a CDN (Part 3).
2. Test: The Cache-Aside Race
Two actors run at the same time:
- The reader misses the key, reads the database (old title), then stalls for 50 ms (a GC pause, a busy CPU, or a slow network) before storing it in the cache.
- The writer updates the title in the database after 10 ms, then deletes the key.
async function reader(key, setFn) {
if (await redis.get(key)) return;
const { rows } = await pool.query('SELECT title, version FROM tracks WHERE id = 42');
await sleep(50); // stalls at the wrong moment
await setFn(key, rows[0]);
}
async function writer(key, safe) {
await sleep(10);
const { rows } = await pool.query(
"UPDATE tracks SET title = 'Tidur Nyenyak (versi baru)', version = version + 1 WHERE id = 42 RETURNING version");
if (safe) await redis.set(`${key}:ver`, rows[0].version, 'EX', 3600); // record the latest version first
await redis.del(key); // then delete the cache
}
The fix: the reader may only write to the cache if the version it carries is not older than the latest version recorded by the writer. The check and the write happen atomically in a Lua script:
redis.defineCommand('setIfNewer', { numberOfKeys: 2, lua: `
local v = tonumber(redis.call('GET', KEYS[2]) or '0')
if tonumber(ARGV[2]) < v then return 0 end
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[3])
return 1` });
const safeSet = (key, row) => redis.setIfNewer(key, `${key}:ver`, JSON.stringify(row), row.version, 3600);
The result:
Tanpa pengaman:
database: Tidur Nyenyak (versi baru)
cache : Tidur Nyenyak TTL 3600 detik
Dengan versi:
database: Tidur Nyenyak (versi baru)
cache : (kosong, dibaca ulang dari database) TTL -2 detik
(Tanpa pengaman = without protection, Dengan versi = with versions, versi baru = new version, kosong, dibaca ulang dari database = empty, reread from the database, detik = seconds. Tidur Nyenyak is the track title, "Sound Sleep".)
Without protection, the old title is locked in the cache for a full hour. With versions, the stale write is rejected, and the next request reads the new title from the database.
If version code feels like too much for your data, there are two lighter alternatives: a short TTL (the race only leaves a few seconds of stale data), or delete the key twice, once right away and once more after a short delay. Choose based on how stale the data may be.
For data involving money, the rule is stricter: never cache money decisions without a bound. An entitlement like "this user already bought a ticket" may be cached with a short TTL, but it must be deleted the moment there is a purchase or refund, and the final decision during a transaction always reads the database.
3. Cache Stampede, Briefly
A popular key expires, thousands of requests see an empty cache at once, and they all hit the database. Part 6 of the GCP series has the test: 500 database queries down to 1 with single-flight.
There are three layers of defense, and the next two sections test two of them:
- Single-flight or a lock: only one request refills, the rest wait or use the old data.
- Random TTL (jitter): so keys filled together do not expire together.
- Stale-while-revalidate: serve old data while refreshing in the background.
4. Test: Random TTLs
When are many keys filled at once? After a deploy, after Redis restarts, or when a job warms the cache every morning. I filled 2,000 keys at once, then read all of them every 50 ms. An empty key means one database query to refill it:
await run('TTL tetap 2 detik ', () => 2000);
await run('TTL 2 detik ± 25% acak ', () => Math.round(2000 * (0.75 + Math.random() * 0.5)));
TTL tetap 2 detik : puncak 2000 query database dalam 100 ms, tersebar di 1 jendela 100 ms
TTL 2 detik ± 25% acak : puncak 227 query database dalam 100 ms, tersebar di 11 jendela 100 ms
(TTL tetap = fixed TTL, acak = random, puncak ... dalam 100 ms = peak ... within 100 ms, tersebar di 11 jendela = spread across 11 windows.)
The total number of queries is the same, because every key still needs a refill. What changes is the shape: from one spike of 2,000 to small, spread-out waves. A database handles 227 queries far more easily than 2,000 at once. The code change is one line.
5. Test: Stale-While-Revalidate
The scenario is a home screen built from an expensive query (300 ms), cached for 1 second, with 50 requests every 100 ms for 3 seconds. Two versions:
- A: plain TTL + single-flight. On expiry, one request fetches fresh data, the others wait for it.
- B: stale-while-revalidate. On expiry, every request gets the old data right away, and one refresh runs in the background.
async function getSwr(key) {
const hit = await redis.get(key);
if (hit) {
const e = JSON.parse(hit);
if (e.freshUntil <= Date.now()) refresh(key, 1000); // not awaited: refresh in the background
return e.v; // serve right away, even if stale
}
return refresh(key, 1000);
}
TTL + single-flight : p50 0.9 ms, p99 302 ms, 200 dari 1500 request menunggu > 100 ms, query database 3
stale-while-revalidate : p50 0.6 ms, p99 2 ms, 0 dari 1500 request menunggu > 100 ms, query database 3
(200 dari 1500 request menunggu > 100 ms = 200 of 1,500 requests waited more than 100 ms.)
The database load is exactly the same: 3 queries. But in version A, every expiry left 50 users waiting 300 ms. In version B, nobody waits.
The price: while the refresh runs, users see data that is about 300 ms staler. For a popular track list, nobody notices. For balances or access rights, do not.
The pattern is the same as the HTTP stale-while-revalidate header (Part 3), this time done in Redis.
6. Test: Hot Keys
A stampede is many requests while a key is empty. A hot key is one key read extremely often while it exists. Every request lands on the same Redis node, and that node can max out while others sit idle.
I simulated a viral track: 20,000 requests from 4 application instances in about 4 seconds, counting the GETs that reached Redis with INFO commandstats:
tanpa salinan lokal : 20000 request, GET ke Redis 20000
salinan lokal 1 detik : 20000 request, GET ke Redis 2000
salinan lokal 1 detik + single-flight: 20000 request, GET ke Redis 16
(tanpa salinan lokal = no local copy, salinan lokal 1 detik = 1-second local copy.)
The second line is interesting. A 1-second local copy alone is not enough, because when it expires, every request on that instance refills at the same time: a small stampede on every instance. With single-flight per instance, one GET is shared:
const get = async (inst) => {
if (inst.until > Date.now()) return inst.value; // local copy still fresh
return (inst.inflight ??= load(inst)); // one GET per instance, the rest ride along
};
The price: each instance can serve data up to 1 second behind. For public track details, that is fine. Another option for hot keys is keeping several copies of the key (track:7:copy1 through copy5) so reads spread across several nodes.
7. Measure Hit Rate, and Understand Why It Varies
Hit rate is the percentage of requests served by the cache. It depends heavily on the shape of the traffic, not only the size of the cache. I simulated 1 million requests to a catalog of 100,000 tracks with Zipf popularity (a few tracks very popular, the rest a long tail), with LRU caches of different sizes:
zipf s=1: ukuran cache (persen katalog) → hit rate: 1% → 50.7% 5% → 66.5% 10% → 73.6% 20% → 80.7%
zipf s=0.8: ukuran cache (persen katalog) → hit rate: 1% → 20.5% 5% → 36.9% 10% → 46.7% 20% → 58.7%
(ukuran cache (persen katalog) = cache size as a percentage of the catalog.)
Two lessons:
- Diminishing returns. Going from 1% to 5% of the catalog gives +16 points, from 10% to 20% only +7. At some point, more memory is not worth it.
- Flatter traffic drops hit rate sharply. The same cache with a thicker long tail falls from 73.6% to 46.7%. A feature that makes users explore more widely (say, more diverse recommendations) can lower hit rate without anything being wrong with the cache.
Measure hit rate per key type (track:*, home:*, search:*), not as one number for all of Redis. A cache with a low hit rate only adds latency and cost, and is better removed.
One more lesson from my own project. While testing Elasticsearch semantic search, semantic queries that took 60–80 ms suddenly took only 2 ms after a few runs. The inference cache had served 1,286 of the first 1,920 inferences, and a load test repeating the same queries only measured that cache. With the cache off, the real limit was about 13 inferences per second. A cache can make a load test look great while the real capacity is much lower. Plan capacity from uncached numbers.
8. Three Cache Correctness Traps
Trap one: trusting that deleting the key is enough. A race can write the old value after the key is deleted. Test: the old title stuck for 3,600 seconds. Use versions, short TTLs, or a double delete.
Trap two: the same TTL for keys filled together. Test: 2,000 queries in 100 ms. Add jitter.
Trap three: a load test that only measures the cache. Repeated queries always hit the cache. Use a realistic mix of queries, and also measure with the cache off.
Summary
- Two questions together: what to cache, and how it stays correct. The tools are TTLs (always), deleting keys on change, and versioned keys.
- The cache-aside race: a slow reader writes the old value after the key is deleted. Test: the old title lasted 3,600 seconds; with a version check in Lua, the stale write is rejected.
- Never cache money decisions without a bound: short TTL, delete on purchase or refund, final decision from the database.
- Random TTLs: peak 2,000 → 227 queries per 100 ms, same total.
- Stale-while-revalidate: p99 302 → 2 ms, still 3 database queries. The price is slightly staler data.
- Hot keys: a 1-second local copy + single-flight per instance, 20,000 → 16 GETs to Redis.
- Hit rate depends on traffic shape: 73.6% vs 46.7% for the same cache size. Measure per key type, plan capacity from uncached numbers.
Closing & What's Next
The title from the opening now changes within seconds, because the cache rejects writes with an older version.
The same principle, a copy must know its own version, turns out to be the key to the next topic. A search index like Elasticsearch is also a copy of the database. The next part covers keeping the index in sync: why writing to the database and then calling Elasticsearch is not enough, the outbox pattern, duplicate messages arriving out of order, reconciliation, and changing mappings without downtime.
Grab your coffee, see you in the next part!

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

