JavaScriptFundamental (ES6), part 2
Cache with TTL (time to live) in JavaScript
90 A cache that expires, on a clock you control
fairCache exchange rates for a fixed time to live. A read inside the window is served from memory; a read after it goes back to the loader. Use an injected clock, expire lazily on read, and then look at two things people get wrong: what the map still holds after an entry has expired, and what happens when the value you cached is undefined.
Stuck? Three hints, smallest first
- 1. Store
{ value, expiresAt }, whereexpiresAtisclock.now() + ttlMs. - 2. Expire on read: if the entry is stale, delete it and report a miss. No timer required.
- 3.
getreturningundefinedfor both a miss and a storedundefinedis whyhasneeds its own answer.
function makeClock() {
let now = 0;
return { now: () => now, advance(ms) { now += ms; } };
}
function ttlCache({ ttlMs, clock }) {
const entries = new Map();
const fresh = (entry) => entry !== undefined && entry.expiresAt > clock.now();
return {
set(key, value) {
entries.set(key, { value, expiresAt: clock.now() + ttlMs });
return value;
},
get(key) {
const entry = entries.get(key);
if (fresh(entry)) return entry.value;
entries.delete(key); // lazy eviction, on the read that noticed
return undefined;
},
has(key) { return fresh(entries.get(key)); },
getOrSet(key, load) {
const entry = entries.get(key);
if (fresh(entry)) return entry.value;
return this.set(key, load(key));
},
get rawSize() { return entries.size; },
};
}
const clock = makeClock();
const rates = ttlCache({ ttlMs: 500, clock });
rates.set('NGN/USD', 1650);
const straightAway = rates.get('NGN/USD');
clock.advance(499);
const justInsideTheWindow = rates.get('NGN/USD');
clock.advance(1);
const sizeBeforeAnyoneLooked = rates.rawSize;
const onceExpired = rates.get('NGN/USD');
const sizeAfterTheRead = rates.rawSize;
let loads = 0;
const load = (key) => { loads++; return key === 'NGN/GBP' ? 2090 : 0; };
const firstLoad = rates.getOrSet('NGN/GBP', load);
const secondLoad = rates.getOrSet('NGN/GBP', load);
const loadsInsideTheWindow = loads;
clock.advance(500);
const afterExpiry = rates.getOrSet('NGN/GBP', load);
const loadsAfterExpiry = loads;
// A cached zero is a real value; a cached undefined is not distinguishable.
const zero = rates.getOrSet('NGN/XOF', load);
rates.set('NGN/GHS', undefined);
const storedUndefined = [rates.get('NGN/GHS'), rates.has('NGN/GHS'), rates.get('never/cached'), rates.has('never/cached')];
console.log('straight away :', straightAway);
console.log('at 499ms :', justInsideTheWindow, '| at 500ms:', onceExpired);
console.log('loads :', loads, 'for three distinct keys');
console.log('undefined vs miss:', storedUndefined);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a value set is a value served', straightAway, 1650);
test('one millisecond before the ttl it is still a hit', justInsideTheWindow, 1650);
test('at exactly the ttl it is a miss', onceExpired, undefined);
test('the stale entry was still sitting in the map until a read noticed it', [sizeBeforeAnyoneLooked, sizeAfterTheRead], [1, 0]);
test('getOrSet loads once and serves the rest of the window from memory', [firstLoad, secondLoad, loadsInsideTheWindow], [2090, 2090, 1]);
test('and loads again once the window has passed', [afterExpiry, loadsAfterExpiry], [2090, 2]);
test('a cached zero is a hit, not a miss, because freshness is checked not truthiness', [zero, rates.has('NGN/XOF')], [0, true]);
test('but a stored undefined reads exactly like a key that was never cached', storedUndefined, [undefined, true, undefined, false]);
Lazy expiry is the right default: no intervals, no timers per key, nothing to unsubscribe, and an entry costs memory rather than CPU while it waits to be noticed. The fourth assertion is the price — a stale entry stays in the map until something reads it, so a cache of keys nobody revisits grows for ever. That is what a maximum size and an eviction policy are for, and an LRU is the usual pairing.
The seventh assertion is the bug hiding in almost every hand-rolled cache: if (cached) treats a cached 0, '' or false as a miss and reloads it every single time. Checking the entry for freshness rather than the value for truthiness is what fixes it, and it costs nothing.
The last assertion is the honest limitation. get has one channel to answer on, so a stored undefined and a key that was never there both come back as undefined; only has can tell them apart. If your loader can legitimately return undefined or null — a lookup for a customer who does not exist, which is exactly the result worth caching — then get must return { hit, value } or you will hammer the upstream for every negative answer.