How to Implement Memoization Safely
Memoize without breaking correctness: key by all inputs, bound the cache, invalidate when data changes, and avoid caching errors or mutable values.
On this page
Introduction
Memoization caches a function’s result so repeated calls with the same inputs return the cached value instead of recomputing it. It is one of the simplest performance techniques and one of the easiest to make incorrect. A key that misses an argument returns the wrong result; an unbounded cache leaks memory; a cache that never expires serves stale data; and a cached error turns a transient failure into a persistent one. Safe memoization is about keys, bounds, and invalidation.
This tutorial covers the four decisions that make memoization safe: what goes in the key, how to bound and expire the cache, when to invalidate, and what not to cache. It ends with tests for keys, bounds, and error handling. The examples use an LRU cache with a TTL, which provides both bounds and expiry.
Key by every input that changes the result
The cache key must include every argument that affects the result. For a function of primitive arguments, serialize them into a stable key. For arguments that are objects, serialize their relevant fields canonically, or require a key field. A function whose result depends on external state, such as the current time or a global, should not be memoized unless that state is part of the key.
Canonicalize so equivalent inputs share a key. Sort object keys, normalize case where the function is case-insensitive, and use a stable serialization. A key that is not canonical produces two entries for equivalent inputs, which is a performance loss, while a key that omits an input produces a correctness bug. Watch for default arguments and optional parameters that change the result but are not in the key.
import { LRUCache } from 'lru-cache';
const cache = new LRUCache<string, number>({ max: 1000, ttl: 60_000 }); // bounded + TTL
function memoExpensive(a: string, b: number, opts: { caseSensitive?: boolean } = {}): number {
const key = JSON.stringify({ a: opts.caseSensitive ? a : a.toLowerCase(), b }); // all inputs
const hit = cache.get(key);
if (hit !== undefined) return hit;
const value = computeExpensive(a, b, opts);
cache.set(key, value);
return value;
}
Bound the cache and give entries a lifetime
An unbounded memo grows with the number of distinct inputs, so a function called with many different keys, or from user input, becomes a memory leak. Bound the cache with a maximum entry count and an eviction policy such as least-recently-used, so the hot entries stay and the cold ones are evicted. This keeps memory proportional to the working set, not to every input ever seen.
A TTL adds a freshness bound. A value computed from data that can change should expire, so the cache does not serve a stale result indefinitely. Set the TTL to how long the result may lag its source, and remember that with a TTL and no invalidation, the staleness is at most the TTL. For a value that must be current immediately, a TTL is not enough; use an explicit invalidation.
from functools import lru_cache
@lru_cache(maxsize=1024) # bounded: at most 1024 entries, LRU eviction
def expensive(n: int) -> int:
return compute(n)
# for data that can change, prefer a cache with a TTL or explicit invalidation,
# not lru_cache alone, which never expires entries
Invalidate when the source changes
A memoized value is stale the moment its source changes. If the function reads a configuration or a database row, a change to that data must clear the relevant entries or the cache serves the old value. Provide a way to clear a single key and a way to clear all, and call the right one on the event that changes the source. Without an invalidation path, the only freshness control is the TTL, which is too coarse for data that changes unpredictably.
Versioning is an alternative to clearing. Include a version in the key that changes when the source changes, so the new key is a miss and the old entries are simply never asked for again. When the source is an entire configuration, bumping a global version invalidates every dependent entry at once, which is simpler than enumerating them.
let configVersion = 1;
function memoWithVersion(input: string): string {
const key = 'cfg' + configVersion + ':' + input; // version in the key
const hit = cache.get(key);
if (hit !== undefined) return hit;
const value = compute(input);
cache.set(key, value);
return value;
}
export function onConfigChange() {
configVersion++; // every old key becomes unreachable; no enumeration needed
}
Do not cache errors or mutable values
Do not cache a thrown error as if it were a result. A transient failure, such as a network error during a fetch, becomes a persistent one if the failure is memoized, because every later call returns the cached error instead of retrying. If you must cache a failure, cache it briefly and only for failures that are stable, and give it a short TTL so a recovery is picked up quickly.
Do not return a shared mutable value from a memo, because a caller that mutates it corrupts the cache for everyone. Return a copy when the value is mutable, or freeze it so a mutation is caught. Structured clone the value on the way in and out if copies are cheap, or store it immutable and require callers to treat it as read-only. A memoized array that a caller sorts in place is a bug waiting to surface.
async function memoFetch(url) {
const hit = cache.get(url);
if (hit) return structuredClone(hit); // return a copy, not the shared value
const value = await fetch(url).then((r) => r.json());
cache.set(url, value, { ttl: 30_000 });
return structuredClone(value);
// a rejection is not cached: the next call retries
}
Test keys, bounds, errors, and mutation
Test that two different inputs produce two entries and do not share a result, which catches a key that omits an input. Test that the cache does not exceed its maximum, by calling with more distinct keys than the bound and asserting the size stays at the bound. Test that a function that throws is not memoized as an error, so a later call retries. Test that a returned mutable value is a copy, by mutating it and asserting the next call returns the original.
node -e '
const m = require("./memo");
m.f(1); m.f(1); // second is a hit
m.f(2); // miss: different key
for (let i = 0; i < 5000; i++) m.f(i);
console.log("size within bound:", m.cache.size <= 1000);
try { m.f(-1); } catch {} // error path
console.log("error not cached:", !m.cache.has("-1"));
'
Common pitfalls
A key that omits an argument so different calls collide, an unbounded cache that leaks memory, no TTL or invalidation so stale values persist, caching an error so a transient failure sticks, and returning a shared mutable value that a caller mutates are the recurring mistakes. Keys over every input with canonicalization, a bounded cache with a TTL, an invalidation or versioning path, no error caching, and copies of mutable values address them.
Conclusion
Memoization is safe when the key, the bound, and the invalidation are right. Key by every input with a canonical serialization, bound the cache and give it a TTL, invalidate or version when the source changes, and never cache errors or hand out mutable values. Self-check by asserting different inputs miss, the cache stays bounded, an error is not cached, and a mutated return does not corrupt the cache. Then the cache is a pure speedup with no correctness cost.
Sources: MDN: Promise and memoization patterns, Python: functools.lru_cache, Node.js: lru-cache.
FAQ
- What should not be memoized?
- Values that depend on mutable state the cache cannot see, values that must be current every call, and errors. Caching an error can make a transient failure stick, and caching a value that changes under you serves stale data with no way to notice.
- Why bound the cache?
- An unbounded memo grows with the number of distinct inputs, so a function called with many different keys leaks memory. A bounded cache with an eviction policy keeps memory in check and, with a TTL, also bounds staleness.
Report a problem with this articleOpens a pre-filled issue on GitHub.