Sub topic 13
Pitfalls and Accidental Strong References
This chapter assumes you already know the WeakRef and FinalizationRegistry APIs from earlier chapters, including held values and unregister tokens, and the weak-value cache pattern. It also assumes you are comfortable with closures and async/await.
Most bugs with weak references fall into two groups. In the first group, the object never becomes collectable, because some path you forgot about still reaches it. In the second, code assumes the object is still there, or that a callback will run, when the engine promises neither. Neither group produces an error. A leak shows up as slowly growing memory. A missing object shows up as an occasional TypeError in production that you cannot reproduce on your machine.
How an Accidental Strong Reference Works
An object is collected only when no strong path from a root reaches it. The roots include globals, the current call stack, and pending callbacks. A WeakRef adds no strong path. A registry entry adds no strong path to its target either. However, everything else attached to the registry entry or to your own data structures is held strongly. That includes the held value, the cleanup callback, and any value you copy out of deref(). If any of those leads back to the target, the target stays alive forever.
The weak edge does not matter when a strong edge reaches the same object by another route.
Pitfall 1: The Held Value Reaches the Target
The engine rejects the obvious case. registry.register(obj, obj) throws a TypeError. It cannot detect indirect paths, though, and those are the common ones in real code.
const registry = new FinalizationRegistry((info) => {
console.log(`cleanup for ${info.label}`);
});
let session = { label: 'session-1', data: new Array(1e6).fill(0) };
// Bad: no error is thrown, but info.owner keeps session alive forever.
registry.register(session, { label: session.label, owner: session });
// Also bad: a bound function closes over its receiver.
registry.register(session, session.toString.bind(session));
session = null; // session is still reachable through the registryTwo other forms show up often. One is a held value that is a closure using the target, such as () => close(session). The other is a held value that is a parent object whose child property is the target.
The fix is to copy out only what the callback needs, as primitives or as objects the target does not own.
const registry = new FinalizationRegistry((label) => {
console.log(`cleanup for ${label}`);
});
let session = { label: 'session-1', data: new Array(1e6).fill(0) };
registry.register(session, session.label); // a string, so no path back
session = null; // now collectableThe rule to apply is: imagine following every property of the held value. If any path arrives at the target, the registration leaks.
Pitfall 2: The Cleanup Callback Captures the Target
The registry holds its callback strongly, and the callback holds everything it closes over. A callback defined inside a function that has the target in scope can capture it.
function track(obj) {
const registry = new FinalizationRegistry(() => {
console.log('collected', obj.id); // closes over obj
});
registry.register(obj, undefined);
}
track({ id: 7 });This code has a second bug. registry is a local variable, so the registry itself can become unreachable once track returns. The specification allows an unreachable registry to be collected along with its pending callbacks, so this callback may never run. The captured obj and the registry form a cycle that nothing outside reaches. The garbage collector can reclaim the whole cycle, and in that case no cleanup happens.
The fix is to keep a single registry at module scope with a callback that uses only its argument:
const registry = new FinalizationRegistry((id) => {
console.log('collected', id);
});
function track(obj) {
registry.register(obj, obj.id);
}
track({ id: 7 });Pitfall 3: Promoting a deref() Result to a Long-Lived Reference
deref() returns an ordinary strong reference. Keeping it in a local variable for the rest of a function is fine. Storing it anywhere that outlives the function turns the weak reference back into a strong one.
const cache = new Map();
const recentlyUsed = []; // grows forever, holds strong references
function get(key) {
const value = cache.get(key)?.deref();
if (value !== undefined) {
recentlyUsed.push(value); // the cached value can now never be collected
}
return value;
}Other places that leak the same way include event listeners that close over the value, setInterval callbacks, memoized results, error objects that carry the value as a property, and module-level variables such as lastResult. The browser console also leaks: an object you logged in DevTools stays reachable while the console shows it.
If you need a "recently used" list, decide its size on purpose. A bounded list of strong references is a reasonable design: it keeps the last N items alive and lets older ones go weak. An unbounded list is a leak.
Pitfall 4: Assuming the Target Survives an await
The engine keeps a target alive until the end of the current job once deref() has returned it. An await ends the job. Code that checks the reference, awaits, and then calls deref() again is relying on luck.
async function describe(ref) {
if (ref.deref() === undefined) return 'gone';
await new Promise((resolve) => setTimeout(resolve, 1000));
return ref.deref().name; // may throw: Cannot read properties of undefined
}You can fix this in two ways, and they behave differently.
// Option A: hold a strong local for the whole operation.
// The object is guaranteed alive, but its lifetime is extended by the await.
async function describeHeld(ref) {
const obj = ref.deref();
if (obj === undefined) return 'gone';
await new Promise((resolve) => setTimeout(resolve, 1000));
return obj.name;
}
// Option B: re-check after each await.
// The object can be collected while waiting, and the code handles that.
async function describeRechecked(ref) {
if (ref.deref() === undefined) return 'gone';
await new Promise((resolve) => setTimeout(resolve, 1000));
const obj = ref.deref();
return obj === undefined ? 'gone' : obj.name;
}Use option A when the operation needs the object to finish correctly. Use option B when the wait is long and you would rather let the object go.
Pitfall 5: Stale Cleanup in Keyed Structures
In a weak-value cache, the cleanup callback for an old value can run after a new value has been stored under the same key. If the callback deletes by key without checking, it removes the live entry. The cache pattern from the earlier chapter guards against this by confirming that cache.get(key).deref() is undefined before it deletes. Any structure keyed by a string or number needs the same check. That covers maps of sockets by ID, DOM nodes by selector, and workers by name. Without the check, you get entries that disappear at random and are very hard to trace.
Pitfall 6: Invalid Targets and Tokens
These mistakes fail loudly, which makes them the easiest to fix:
const registry = new FinalizationRegistry(() => {});
const attempts = [
() => new WeakRef(42), // primitive target
() => new WeakRef(Symbol.for('app')), // registered symbol
() => registry.register({}, 'x', 'token-string'), // primitive token
() => { const o = {}; registry.register(o, o); }, // held value is target
];
for (const attempt of attempts) {
try {
attempt();
} catch (err) {
console.log(err instanceof TypeError); // true, four times
}
}Using the target itself as its unregister token is allowed. Tokens are held weakly, so this does not keep the target alive.
Pitfall 7: Treating Callbacks as Guaranteed
A callback might run late, run in a different order from the collections, or never run at all. It won't run if the page closes, if the process exits, or if the engine simply never collects the object. Code that needs a callback to run in order to stay correct is a bug, even if it passes every test. Examples include flushing writes, releasing a lock, or decrementing a counter that other code reads. Finalization can log or recover from a missed explicit cleanup. It cannot replace that cleanup.
Quick Reference
| Pitfall | Symptom | Fix |
|---|---|---|
| Held value reaches target | Memory grows, callback never runs | Pass primitives or unrelated objects |
| Callback closes over target | Target never collected | Module-level callback that uses only its argument |
| Registry not kept reachable | Callbacks silently skipped | Keep the registry at module scope |
| `deref()` result stored long-term | Weak cache behaves like a strong one | Keep results local or bound the strong list |
| `deref()` again after `await` | Intermittent `TypeError` | Hold one local, or re-check after each await |
| Unchecked key deletion | Live entries vanish | Confirm the entry is stale before deleting |
| Relying on callbacks | Lost writes, leaked locks | Explicit cleanup, with finalization as backup |
Exercise
A developer writes registry.register(conn, { id: conn.id, close: () => conn.socket.end() }) so that the callback can close the socket. Why does conn never get collected, and how should the registration be rewritten?
Show answer
The close arrow function in the held value closes over conn. The registry holds the held value strongly, so conn stays reachable. Pass the socket itself as the held value instead, as in registry.register(conn, conn.socket), and call socket.end() in the callback. This works as long as the socket does not reference conn.
Exercise
Inside a class constructor, the code runs this.registry = new FinalizationRegistry(cb); this.registry.register(this, this.id);. What goes wrong?
Show answer
Each instance owns its own registry, and the only reference to that registry is the instance being watched. When the instance becomes unreachable, so does its registry, and the engine may collect both without ever running cb. Use one shared registry at module scope.
Exercise
In async function f(ref) { const o = ref.deref(); if (!o) return; await save(o); log(ref.deref().name); }, is the last line safe? Suggest the simplest fix.
Show answer
It is unsafe. The second deref() runs in a later job and could return undefined if o were unreachable. In this code, though, o stays alive while the function still uses it. The simplest fix is to write log(o.name), which uses the strong local that already exists.