⚡ Fix a WeakMap-Based Cache Still Leaking Memory Because the Key Object Is Held Alive by an Unrelated Closure Elsewhere
A WeakMap is specifically designed so its entries can be garbage collected the instant nothing else in the program still references the key object – the cache entry itself never keeps the key alive. That guarantee only helps if nothing ELSE is keeping the key alive, though, and a completely unrelated closure – an event listener that captured the object, a setTimeout callback still pending, a second, ordinary cache that happens to also hold a reference – is enough to keep that key reachable indefinitely, in which case the WeakMap entry can never be collected either, not because the WeakMap failed at its job, but because the key was never actually eligible for collection in the first place.
🔎 The Problem
const computedCache = new WeakMap();
function attachHandlers(node) {
const result = expensiveCompute(node);
computedCache.set(node, result); // weak reference, fine on its own
node.addEventListener('click', () => {
console.log(node.dataset.id); // closure captures 'node' directly
});
// This listener is never removed, even after 'node' is detached
// from the document - as long as the listener (or whatever added
// it) is still referenced, 'node' stays reachable, and so does
// the WeakMap entry keyed on it.
}
// Profiling heap snapshots months later still shows thousands of
// detached DOM nodes retained, each with a live WeakMap cache
// entry - the WeakMap was never the leak, the listener closures were.
✅ Fix: Find and Release Whatever Else Is Holding the Key
- Take a heap snapshot in DevTools and use ‘retainers’ on a detached node that should have been collected – this traces the actual reference chain keeping it alive, which is almost always more useful than staring at the WeakMap code itself, since the WeakMap is rarely the culprit.
- Explicitly remove event listeners (or use an AbortController’s signal to attach them, so a single abort() call detaches everything at once) when a node is removed from the document, rather than assuming garbage collection will clean up listeners on its own.
- Audit any other cache, registry, or list in the codebase that might also hold a plain (non-weak) reference to the same objects – a single ordinary Map or array alongside the WeakMap is enough to pin every key the WeakMap was supposed to let go of.
🚨 Why This Is Dangerous
- A WeakMap’s presence in the code can create false confidence that ‘the caching layer can’t be the leak’, which sends debugging effort in the wrong direction while the actual retaining reference – a listener, a timer, a second cache – goes unexamined for far longer than it should.
A WeakMap only releases a key when nothing else is holding onto it – find that other reference, and the WeakMap takes care of itself.
