Sub topic 10
What the Engine Does Not Promise
This chapter assumes you already know how to create a WeakRef, call deref(), and register objects with a FinalizationRegistry using held values and unregister tokens. It also assumes you understand jobs and the event loop at a conceptual level. Here we look at what the ECMAScript specification leaves out on purpose. Most bugs with weak references come from code that relies on a behavior the engine never promised.
Why the Specification Stays Vague
Garbage collectors differ a great deal between engines. V8, SpiderMonkey, and JavaScriptCore each use generational, incremental, and concurrent collection in their own ways. They also tune those strategies for memory pressure, battery life, and pause times. If the specification fixed a collection schedule, it would block those optimizations. So the specification describes what collection is allowed to do and leaves the rest to the engine.
The proposal that introduced these features said it directly: correct use of FinalizationRegistry means not depending on cleanup callbacks for program logic. Read every API in this area as "the engine may", never "the engine will".
The Explicit Non-Guarantees
An unreachable object may never be collected
Unreachability means an object is eligible for collection. It does not mean the object will be collected. A short-lived script may finish before any major collection runs. An engine may also keep an object alive longer than your source code suggests. For example, a closure can capture a whole scope, or an optimizing compiler can hold a value in a register. As long as the object is not collected, deref() keeps returning it.
A cleanup callback may never run
Even after an object is collected, the specification allows the engine to skip its cleanup callback. Common cases:
- The program exits. Node.js does not run pending cleanup callbacks before the process ends.
- A browser tab is closed or navigated away. Pending callbacks are dropped.
- The
FinalizationRegistryitself has become unreachable. A collected registry has no obligation to call its callback. - The engine simply chooses not to. This is allowed.
Timing is unspecified
When a callback does run, the engine can run it immediately after a collection or much later. It can also batch several callbacks together. You cannot predict the delay from your code, and it changes between engine versions, flags, and machines.
Order is unspecified
If objects a and b become unreachable in that order, their callbacks may run as b then a. If they belong to different registries, the engine still promises no order between those callbacks. Objects that refer to each other in a cycle are usually collected together, so their callbacks arrive in an arbitrary order.
Callbacks never interrupt synchronous code
This one is a real guarantee, and it is useful. Cleanup callbacks run in their own jobs, which the host schedules with HostEnqueueFinalizationRegistryCleanupJob. They never run in the middle of your synchronous code. Combined with the kept-alive rule from the earlier chapter, this means that within a single job the weak state you observe stays consistent.
What You Can Rely On
The specification does commit to a few things. Know these exactly, so you neither rely on too much nor distrust too much.
| Behavior | Guaranteed? | Notes |
|---|---|---|
| Unreachable objects are eventually collected | No | Collection may never happen |
| `deref()` returns the same result throughout one job | Yes | Targets observed with `deref()` or `new WeakRef()` are kept alive until the job ends |
| All `WeakRef`s to one target are cleared together | Yes | The specification clears them atomically with the registry cells |
| `deref()` returns `undefined` before that target's callback runs | Yes | Clearing happens first, and the cleanup job is only queued |
| A callback runs after collection | No | It may be skipped entirely |
| Callbacks run within some bounded time | No | No deadline exists |
| Callbacks run in registration or collection order | No | Order is arbitrary |
| Callbacks run in the middle of synchronous code | Never | They run as separate jobs |
| Callbacks run before the process or page exits | No | Pending work is dropped |
The two "Yes" rows about clearing deserve attention. When an engine collects an object, the specification describes a single atomic step. Every WeakRef pointing at the object is emptied, every registry cell for the object is emptied, and a cleanup job is queued for each affected registry. Your code can therefore see deref() return undefined before the matching callback has run. Any code that reads a weak cache has to handle that gap.
Seeing the Gaps in Practice
Callbacks lost at exit
Run this script with plain node:
const registry = new FinalizationRegistry((label) => {
console.log(`callback for ${label}`);
});
for (let i = 0; i < 100000; i++) {
registry.register({ index: i }, `obj-${i}`);
}
console.log('registered 100000 objects');All 100,000 objects are unreachable once their loop iteration ends. On most runs you will see only registered 100000 objects, because the process exits with nothing left on the event loop. On some runs a collection happens during the loop and a few callbacks print. Either outcome is correct. A program that needed all 100,000 callbacks to run has a bug.
The kept-alive rule overriding a forced collection
Run this with node --expose-gc:
const registry = new FinalizationRegistry((label) => {
console.log(`callback ran for ${label}`);
});
let target = { name: 'demo' };
const ref = new WeakRef(target);
registry.register(target, 'demo');
target = null;
globalThis.gc();
console.log('same job, after gc():', ref.deref()); // still the object
setTimeout(() => {
globalThis.gc();
console.log('later job, after gc():', ref.deref()); // usually undefined
setTimeout(() => {
console.log('one more turn of the event loop');
}, 0);
}, 0);The first deref() must return the object. Creating the WeakRef added the target to the kept-alive set for the current job, so even a forced gc() cannot collect it. In the later job the object is usually gone. The words "usually" and "may" in the output comments are accurate. --expose-gc only requests a collection. V8 may still keep the object alive, and the callback line may print before, after, or not at all relative to the other logs.
Designing Around the Gaps
The practical rule is this: your program must behave correctly if no cleanup callback ever runs. Callbacks can make things more efficient, for example by freeing a map entry sooner, but they must never be needed for correctness.
Compare two ways of tracking open connections:
// Fragile: the count is only correct if every callback runs.
let openCount = 0;
const counter = new FinalizationRegistry(() => {
openCount--;
});
function openFragile() {
const conn = { open: true };
openCount++;
counter.register(conn, null);
return conn;
}
// Correct: the count changes only through explicit calls.
const live = new Set();
function openExplicit() {
const conn = {
open: true,
close() {
if (!this.open) return;
this.open = false;
live.delete(this);
},
};
live.add(conn);
return conn;
}
const a = openExplicit();
const b = openExplicit();
a.close();
console.log('open connections:', live.size); // 1, every time
console.log(openFragile().open, 'fragile count:', openCount); // count never goes down reliablyThe fragile version reports a number that drifts upward forever if callbacks are delayed or skipped. The explicit version is exact. Later chapters build on this idea: weak caches treat a callback as an optional tidy-up, and resource wrappers treat finalization only as a last-resort warning.
A few more design rules follow from the non-guarantees:
- Always check
deref()forundefined, even when a callback "should have" removed the entry already. - Never use a callback's arrival to signal that work is finished, for example to resolve a promise that other code awaits.
- Keep the registry reachable for as long as you want its callbacks to be possible. A registry stored in a local variable that goes out of scope may be collected along with its pending callbacks.
- Don't do expensive work in callbacks. They can arrive in large batches.
- Don't look for a
cleanupSome()method to force callbacks. It was proposed but is not part of the standard.
Exercise
A cache removes an entry inside a FinalizationRegistry callback. Another function reads the cache with cache.get(key).deref().value. Users report occasional "Cannot read properties of undefined" errors. Which guarantee explains this, and how do you fix the reader?
Show answer
When the engine collects the target, it clears all WeakRefs to it atomically and only queues the cleanup job. Between that moment and the callback running, the map still holds a WeakRef whose deref() returns undefined. The reader must handle that state: const v = cache.get(key)?.deref(); if (v === undefined) { /* recompute */ }.
Exercise
A test registers an object, drops the reference, calls gc() under --expose-gc, waits 50 ms, and asserts that the callback ran. It passes locally. List two reasons it may fail elsewhere, and state what the test should assert instead.
Show answer
The engine may not collect the object even when gc() is called, for example if a closure or the optimizer keeps it alive. And if it is collected, the cleanup job may run after 50 ms or never, since the specification sets no deadline. The test should check behavior that is correct whether or not the callback runs, such as that explicit close() releases the resource, and treat the callback as optional.
Exercise
True or false: if a cleanup callback runs for object A, then any WeakRef to A will return undefined from deref() in that callback and afterward.
Show answer
True. The engine clears all WeakRefs to a target and its registry cells in one atomic step before it queues the cleanup job, so by the time the callback runs, deref() on any WeakRef to A returns undefined.