Predict the output · Node.js
The Stale Cache Set
Medium Predict the output
A cache-aside read and a price update run concurrently. What does it print? See The Stale-Set Race.
What does this print?
const db = { price: 100 };
const cache = new Map();
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function read() {
if (cache.has("price")) return cache.get("price");
const value = db.price; // cache miss → SELECT
await sleep(20); // slow network / GC pause
cache.set("price", value); // SET
return value;
}
async function update() {
await sleep(5);
db.price = 80; // UPDATE … COMMIT
cache.delete("price"); // invalidate
}
await Promise.all([read(), update()]);
console.log(db.price, cache.get("price"));
80 80
80 100
80 undefined
100 100
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
80 100
The reader loaded 100, the writer then committed 80 and deleted the key, and only afterwards did the slow reader
set its old value. The cache now holds 100 until its TTL: a stale set. Prevent it with version-checked sets or
leases, and bound it with short TTLs. See The Stale-Set Race.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium