v8-memoryAnswer last reviewed July 2026

WeakMap, WeakRef, FinalizationRegistry. When would you actually reach for each of those in server code, and when is each one the wrong tool?

Strong answers place WeakMap, WeakRef, and FinalizationRegistry by their GC semantics, and know finalization timing is unspecified and can't carry cleanup

What an AI-prepared candidate might say

So WeakMap holds its keys weakly, meaning if the key object becomes unreachable everywhere else, the entry gets collected along with it. That makes it the tool for attaching metadata to objects without keeping them alive, like caching computed data per request object. WeakRef is a reference that doesn't keep its target alive. You call deref() and get back either the object or undefined if it was already collected. FinalizationRegistry lets you register a callback that runs after an object gets collected, which is handy for cleanup. Two things to be careful about, I think. Finalization timing isn't guaranteed, so it shouldn't be your primary cleanup path. And a WeakRef cache can lose entries whenever the GC runs. In server code the common one is WeakMap. The other two are more niche, caches, native resource tracking, that kind of thing.

Senior
Locked

The ephemeron semantics that make WeakMap cycles safe, why the whole WeakRef lifecycle comes down to one deref, and exactly what finalization does and doesn't promise.

Unlock the depth
Staff
Locked

The one pattern where WeakMap is genuinely the right tool, metadata on objects you don't own, why explicit lifecycle beats weakness for caches, and finalizers as leak detectors.

Unlock the depth
Follow-up chain
WeakMap, WeakRef, FinalizationRegistry. When would you actually reach for each of those in server code, and when is each one the wrong tool? | NodeBook