DEV Community

Cover image for You're Leaking Memory With That Cache. WeakMap Fixes It.
Parsa J
Parsa J

Posted on Originally published at bestpractic.org

You're Leaking Memory With That Cache. WeakMap Fixes It.

Open the memory profiler on a page that's supposed to be idle, and the retained-size graph should flatten out. On this one it didn't. Every navigation added a little more, and none of it ever came back down.

The suspect wasn't a leaked event listener or a forgotten setInterval — both had already been ruled out. It was a cache. A perfectly reasonable-looking one:

const metadataCache = new Map();

function getMetadata(record) {
  if (metadataCache.has(record)) return metadataCache.get(record);
  const computed = expensiveParse(record);
  metadataCache.set(record, computed);
  return computed;
}
Enter fullscreen mode Exit fullscreen mode

record objects came from an API response, got rendered, and were thrown away the moment the user navigated elsewhere. Except they weren't thrown away — not really. metadataCache still had a reference to every single one, and a Map never lets go of a key on its own. The garbage collector doesn't get a vote: as long as something holds a strong reference, the object stays on the heap, parse result and all.

Why Map can't be trusted with throwaway keys

This isn't a bug in Map — it's doing exactly what a Map is for. A Map is built to keep what you put in it until you explicitly delete it. That's the correct behavior for a cache keyed by a string or a small fixed set of values. It's the wrong behavior for a cache keyed by objects whose whole lifecycle is "used once, then gone" — because nothing ever calls .delete() for you, and the moment you forget to, the cache becomes a second copy of every object your app ever touched, held open forever.

The usual first fix is WeakMap:

const metadataCache = new WeakMap(); // same calls, weak keys

function getMetadata(record) {
  if (metadataCache.has(record)) return metadataCache.get(record);
  const computed = expensiveParse(record);
  metadataCache.set(record, computed);
  return computed;
}
Enter fullscreen mode Exit fullscreen mode

Same API, one word different, and the leak is gone. A WeakMap holds its keys weakly: once nothing else in the program references a given record, the engine is free to collect it, and its entry in the WeakMap disappears with it — automatically, with no .delete() anywhere. WeakMap has existed since ES2015, and for "cache keyed by an object, evict when the object is gone," it's the entire answer. Reach for it first.

🎮 Try it yourself

▶️ Open the interactive playground →

Runs right in your browser — poke at it and watch the concept react live.

The case WeakMap can't cover

WeakMap only solves the problem when the weak thing is a map key. Two situations fall outside that:

  • You need to hold a weak reference by itself — in a class field, an array entry, a plain object property — not as a Map key at all. WeakMap/WeakSet have no API for that; they only accept objects as keys or set members.
  • You need to do something when the object actually gets collected — close a WebSocket, cancel a subscription, remove an entry from an unrelated index — and WeakMap gives you silence. The entry just vanishes; nothing tells your code it happened.

That's what the other two ES2021 additions are for.

WeakRef wraps a single object in a container you can hold anywhere, without that container keeping the object alive:

let ref = new WeakRef(record);

ref.deref(); // the record, while it's still alive
ref.deref(); // undefined, once nothing else references it — could be later in the same function
Enter fullscreen mode Exit fullscreen mode

.deref() is the only thing you do with it: call it, and either get the live object back or undefined. There is no event, no promise, no way to ask "is it gone yet" without calling .deref() and checking.

FinalizationRegistry is the piece that gives you a callback instead of a poll:

const registry = new FinalizationRegistry((heldValue) => {
  console.log(`cleaning up after ${heldValue}`);
  releaseExternalResource(heldValue);
});

registry.register(record, record.id);
Enter fullscreen mode Exit fullscreen mode

register(target, heldValue, unregisterToken?) watches target. Once target becomes unreachable and the engine gets around to collecting it, the registry calls your callback with heldValue — never with target itself, because the callback runs after target is already gone. That's also why target and heldValue can't be the same object: pass the same reference for both and register() throws a TypeError, because the registry holding heldValue strongly would defeat the entire point by keeping target alive forever.

If you dispose of something yourself before GC gets to it, call registry.unregister(unregisterToken) — a third argument to register() — so the callback doesn't fire twice.

Building a cache that cleans up after itself

Put the two together and the parse-result cache gets an upgrade WeakMap alone couldn't give it: logging (or releasing an external resource) the moment an entry is actually swept.

const metadataCache = new WeakMap();
const cleanupLog = new FinalizationRegistry((id) => {
  console.log(`metadata for record ${id} was collected`);
});

function getMetadata(record) {
  if (metadataCache.has(record)) return metadataCache.get(record);
  const computed = expensiveParse(record);
  metadataCache.set(record, computed);
  cleanupLog.register(record, record.id);
  return computed;
}
Enter fullscreen mode Exit fullscreen mode

The WeakMap still does the actual weak-caching — it's the right tool for that half. The FinalizationRegistry is bolted on purely for visibility and side effects: if getMetadata also opened a BroadcastChannel per record, this is where you'd close it, instead of hoping the caller remembers to.

The guarantee you don't get — and why that's fine

Here's the part that trips people up the first time they read the spec: there is no guarantee a FinalizationRegistry callback ever runs. Not "runs eventually" — possibly never. If the page unloads first, if the engine decides the cleanup isn't worth the cycles, if the object happens to never get collected during the page's lifetime — the callback is simply skipped. ECMA-262 says this on purpose, because it leaves engines free to optimize garbage collection however they want without being locked into a cleanup contract.

That single sentence should decide every use of these two APIs. WeakRef and FinalizationRegistry are for optimization and housekeeping — a cache that's allowed to forget things, a debug log, releasing a resource a little sooner than it otherwise would be. They are the wrong tool for anything that must happen: closing a file handle your app's correctness depends on, flushing data the user will notice if it's lost, releasing a lock another process is waiting on. For deterministic cleanup, reach for an explicit dispose()/close() call (or using, if your runtime supports resource management) — something that runs because your code said so, not because the garbage collector eventually agreed to.

What actually changed

WeakMap and WeakSet have quietly prevented this class of leak since 2015; most caches never needed anything newer. WeakRef and FinalizationRegistry — both ES2021, both supported in every evergreen browser and in Node since 14.6 — only earn their place when the weak reference isn't a map key, or when something genuinely needs to happen on collection rather than just disappear quietly.

The fix for the original leak, in the end, was one word: Map became WeakMap. The heap snapshot flattened out on the next deploy. But the question worth sitting with is the one that found it in the first place — next time a retained-size graph only ever goes up, which cache in your code is the one still holding the door open?

🧠 Test yourself

Think it clicked? Take the 7-question quiz →

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Top comments (0)