Sub topic 12
Finalization as a Safety Net for External Resources
This chapter assumes you already know FinalizationRegistry, held values, and unregister tokens from earlier chapters. It also assumes you know that cleanup callbacks have no timing guarantees. Here those pieces come together in one practical pattern: using finalization to catch resources that code forgot to release.
The problem: resources the collector cannot see
The garbage collector manages JavaScript memory. It knows nothing about the things your objects stand for outside the heap. Examples include file descriptors, sockets, database connections, native buffers, GPU textures, and locks held on a server. A LogFile object might be a few dozen bytes on the heap while it holds an operating system file descriptor. There is a per-process limit on file descriptors.
If a caller forgets to call close(), the wrapper object eventually becomes unreachable and its memory is reclaimed. The descriptor stays open. Do this enough times and the process fails with EMFILE: too many open files.
A FinalizationRegistry can notice that the wrapper was collected and release the external resource then. This is a safety net. It catches some mistakes, some of the time, eventually. It never replaces the explicit close().
The shape of the pattern
The pattern has three parts:
- A wrapper object that user code holds and calls methods on.
- An inner handle, the raw resource (a descriptor number, a native handle, a state object). It is passed to the registry as the held value.
- A registration that uses the wrapper as both the target and the unregister token.
Only the left branch is under your control. The right branch exists to shrink the damage from bugs.
A runnable example with real file descriptors
The example below uses Node.js file descriptors. Save it as logfile.js and run it with node --expose-gc logfile.js.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const leakRegistry = new FinalizationRegistry((fd) => {
console.warn(`LogFile leaked: closing fd ${fd} from finalizer`);
try {
fs.closeSync(fd);
} catch {
// Never let an exception escape a cleanup callback.
}
});
class LogFile {
#fd;
#closed = false;
constructor(filePath) {
this.#fd = fs.openSync(filePath, 'a');
// target = this, held value = the raw fd, unregister token = this
leakRegistry.register(this, this.#fd, this);
}
write(line) {
if (this.#closed) throw new Error('LogFile is closed');
fs.writeSync(this.#fd, line + '\n');
}
close() {
if (this.#closed) return; // idempotent
this.#closed = true;
leakRegistry.unregister(this); // cancel the safety net first
fs.closeSync(this.#fd);
}
}
const file = path.join(os.tmpdir(), 'safety-net-demo.log');
// Correct use: no warning is ever printed.
const good = new LogFile(file);
good.write('explicitly closed');
good.close();
// Buggy use: the wrapper is dropped without close().
(function leak() {
const bad = new LogFile(file);
bad.write('forgotten');
})();
setTimeout(() => {
if (typeof globalThis.gc === 'function') globalThis.gc();
// The warning will probably appear shortly after, but nothing guarantees it.
}, 0);Look at a few details:
- The held value is the number
fd. It carries no reference to the wrapper, so the registry does not keep the wrapper alive. close()callsunregister(this)before releasing the resource. Onceclose()returns, the callback can no longer close the same descriptor again.close()is idempotent. Calling it twice is harmless, which matters once cleanup can come from more than one place.- The callback catches its own errors. If a cleanup callback throws, the error is reported the way an uncaught exception would be. In Node.js that can crash the process.
Keeping mutable state outside the wrapper
A plain number works when the resource never changes. Real resources often have state: a connection may reconnect and get a new socket, or it may be half-closed. Since the held value is fixed at register() time, put that state in a separate object. Both the wrapper and the registry share that object, and it never points back at the wrapper.
const registry = new FinalizationRegistry((state) => {
if (state.closed) return;
state.closed = true;
console.warn(`Connection ${state.id} leaked; releasing`);
state.release();
});
let nextId = 1;
class Connection {
#state;
constructor() {
const id = nextId++;
this.#state = {
id,
closed: false,
release: () => console.log(`released native connection ${id}`),
};
registry.register(this, this.#state, this);
}
reconnect() {
// Mutating the shared state is fine; the registry sees the same object.
this.#state.id = nextId++;
}
close() {
if (this.#state.closed) return;
this.#state.closed = true;
registry.unregister(this);
this.#state.release();
}
}
const c = new Connection();
c.reconnect();
c.close(); // prints: released native connection 2The release arrow function closes over id, a local variable, and not over this. That is deliberate. If the arrow function used this, the state object would reference the wrapper. The registry holds the state strongly, so the wrapper would never become unreachable and the callback would never fire.
The accidental strong reference that disables the net
Mistakes in this pattern fail silently. Nothing throws and nothing warns. The safety net just never fires. Every one of these keeps the wrapper alive forever:
const registry = new FinalizationRegistry((held) => held.cleanup());
class Broken {
constructor(handle) {
this.handle = handle;
// 1. Held value contains the wrapper.
registry.register(this, { owner: this, cleanup() {} });
// 2. Held value is a closure that captures `this`.
registry.register(this, { cleanup: () => this.handle.close() });
// 3. The inner handle points back at the wrapper.
handle.owner = this;
registry.register(this, handle);
}
}Only register(obj, obj) is rejected with a TypeError. Indirect cycles through the held value are allowed and never collected. A useful check: starting from the held value, follow every property and every closure variable. If you can reach the wrapper, the pattern is broken.
What the net cannot catch
Callbacks may run late, out of order, or never. That rules out several kinds of resource:
| Resource | Suitable for a finalization safety net? | Why |
|---|---|---|
| File descriptors, sockets | Yes, as a backup | The OS also reclaims them at process exit, so a missed callback costs little |
| Native memory or GPU buffers | Yes, as a backup | Late release is wasteful but correct |
| Buffered writes that need a flush | No | Data is lost if the callback never runs, for example at exit |
| Remote locks, leases, server sessions | No | Nothing reclaims them on the other side, and a late release blocks other clients |
| Database transactions | No | Commit or rollback must happen at a well-defined point |
| Temporary files on disk | Weak | Files outlive the process, so a missed callback leaves garbage behind |
Some more limits:
- Process exit. Engines do not run pending finalizers when a Node.js process exits or a browser tab closes. Anything that must happen at shutdown needs an explicit hook.
- Pressure feedback. The collector runs when heap memory is low, not when descriptors run out. A program can exhaust descriptors while the heap has plenty of room, so no collection runs and no callback fires.
- Async cleanup. A callback may start async work, such as
socket.end()or a promise. Nobody awaits it, so attach your own error handling. - Callback context. The callback runs as its own job, later. Don't count on any surrounding state, such as an open transaction, an active request, or a set timer, still being there.
Capturing where the leak came from
A warning that says "fd 21 leaked" does not help much. To point at the caller, capture a stack trace when the resource is created and keep it in the held value. A string or an Error object is safe because neither refers to the wrapper.
const DEBUG = process.env.NODE_ENV !== 'production';
const registry = new FinalizationRegistry(({ id, createdAt }) => {
console.warn(`Resource ${id} was never closed.`);
if (createdAt) console.warn(createdAt);
});
class TrackedResource {
constructor(id) {
this.id = id;
const createdAt = DEBUG ? new Error('Created here').stack : undefined;
registry.register(this, { id, createdAt }, this);
}
close() {
registry.unregister(this);
}
}
new TrackedResource('demo'); // dropped immediately; may warn laterCapturing stacks costs time and memory, so keep it to development builds.
Combining with explicit disposal
The safety net works alongside whatever explicit cleanup API you offer, whether that is a close() method, try/finally, or Symbol.dispose with using declarations where the runtime supports them. A disposal method just calls close(). Because close() unregisters, a correctly disposed object never reaches the finalizer. The callback runs only when the explicit path was skipped. The final chapter compares the explicit options in detail.
Exercise
A teammate writes registry.register(this, () => this.socket.destroy(), this) and the callback calls held(). Leaked sockets are never cleaned up. Why, and how do you fix it?
Show answer
The held value is an arrow function that captures this. The registry holds the held value strongly, so the wrapper stays reachable and is never collected. Pass the socket itself (registry.register(this, this.socket, this)) and call socket.destroy() in the callback, or use a state object that holds the socket but not the wrapper.
Exercise
Why does close() call registry.unregister(this) before closing the file descriptor, and what could go wrong if it skipped the unregister call entirely?
Show answer
Unregistering first means the callback can no longer fire for a resource that has been released. Without it, the callback could run after the wrapper is collected and call closeSync on the old descriptor number. The OS may have reused that number for a different file, so the finalizer would close an unrelated, live file.
Exercise
A class holds a lease on a remote job queue that must be returned within 30 seconds. Should a FinalizationRegistry release the lease? Justify your answer.
Show answer
Not as the release mechanism. The callback may run much later than 30 seconds, or never, for example if the heap is not under pressure or the process exits. Nothing on the server reclaims the lease early. Release it explicitly with close(), try/finally, or a disposal method. A finalizer can at most log that a lease was leaked.