Full answer
Plain memoization stores fn(args) the first time and returns the stored value later. A TTL (time to live) adds a lifetime: an entry older than ttl milliseconds is stale and must be computed again.
Implementation points:
- Key:
JSON.stringify(args)works for simple arguments. Accept akeyoption for objects, functions, or large arguments. - Entry:
{ value, expires }. On a call, read the entry. If it exists andnow() < expires, return the value. Otherwise compute, store, and return. Lazy expiry on read is simple and needs no timers, so nothing keeps the process alive. - Async functions: store the promise, not the resolved value. Then two callers that arrive while the request is in flight share one call (this is called request deduplication). If the promise rejects, delete the entry so an error is not cached for the full TTL.
- Memory: a cache without a limit is a memory leak. Add a
maxSizeand drop the oldest entry when full. A Map keeps insertion order, so the first key is the oldest. - Testing: pass
nowas an option so a test can move the clock. - Extras: a
clear()method, adelete(key)method, and stale-while-revalidate (return the old value while a refresh runs) for latency-sensitive reads.
A caveat is this: use a regular function and fn.apply(this, args) if the memoized function is used as a method. Also never memoize functions with side effects, or functions that depend on hidden state, such as the current time or random numbers, unless that is what you want.
function memoizeWithTtl(fn, { ttl, maxSize = 100, key = (...args) => JSON.stringify(args), now = () => Date.now() }) {
const cache = new Map();
function memoized(...args) {
const id = key(...args);
const entry = cache.get(id);
if (entry && now() < entry.expires) return entry.value;
cache.delete(id);
const value = fn.apply(this, args);
cache.set(id, { value, expires: now() + ttl });
if (cache.size > maxSize) cache.delete(cache.keys().next().value);
if (value instanceof Promise) {
value.catch(() => {
if (cache.get(id)?.value === value) cache.delete(id);
});
}
return value;
}
memoized.clear = () => cache.clear();
memoized.size = () => cache.size;
return memoized;
}
let clock = 0;
let calls = 0;
const slowSquare = memoizeWithTtl((n) => (calls++, n * n), { ttl: 1000, now: () => clock });
console.log(slowSquare(4), slowSquare(4), 'calls:', calls);
clock = 999;
slowSquare(4);
console.log('before expiry, calls:', calls);
clock = 1000;
slowSquare(4);
console.log('at expiry, calls:', calls);
const limited = memoizeWithTtl((n) => n, { ttl: 10000, maxSize: 2, now: () => clock });
limited(1); limited(2); limited(3);
console.log('size capped at', limited.size());
async function main() {
let fetches = 0;
let fail = true;
const load = memoizeWithTtl(
async (id) => {
fetches++;
await new Promise((resolve) => setTimeout(resolve, 5));
if (fail) throw new Error('network down');
return { id };
},
{ ttl: 1000, now: () => clock },
);
const [first, second] = await Promise.allSettled([load(1), load(1)]);
console.log('shared in-flight call:', fetches, first.status, second.status);
await Promise.resolve();
fail = false;
console.log('after failure the error is not cached:', await load(1), 'fetches:', fetches);
await load(1);
console.log('success is cached:', fetches);
}
main();Run with Node.js v24.22.1 as js-107.js; two runs gave identical output. Output: 16 16 calls: 1 before expiry, calls: 1 at expiry, calls: 2 size capped at 2 shared in-flight call: 1 rejected rejected after failure the error is not cached: { id: 1 } fetches: 2 success is cached: 2
Key points
- Cache entries hold a value and an expiry; check expiry on each read.
- Build the key from the arguments, or accept a custom key function.
- For async functions, cache the promise so concurrent calls share one request, and delete on rejection.
- Add a size cap, since an unbounded cache leaks memory.
- Inject the clock for tests; do not memoize impure functions.
Common mistakes
- Caching the resolved value of an async function, so parallel calls all hit the network.
- Caching a rejected promise for the whole TTL.
- Using JSON.stringify for keys with functions, undefined, or circular objects.
- Leaving the cache unbounded.
Follow-ups
- How would you add stale-while-revalidate behavior?
- What is the difference between this and an LRU cache?
- How would you share a cache across several servers?
Tips
- Say that you cache the promise for async work and why.
- Mention expiry on read, a size cap, and an injected clock.
- Warn against memoizing impure functions.