WeakRef and FinalizationRegistry: GC-aware caches (ES2021)
What you’ll learn
Section titled “What you’ll learn”- How
WeakRef.prototype.deref()behaves before and after collection. - How
FinalizationRegistrycallbacks, held values and unregister tokens work, and what is not guaranteed. - How to build a cache that reuses large objects only while something else still uses them.
Summary
Section titled “Summary”TL;DR: new WeakRef(obj) holds obj without preventing garbage collection; ref.deref() returns the object, or undefined once it has been collected. new FinalizationRegistry(callback) lets you register(obj, heldValue) and have callback(heldValue) called at some point after obj is collected, if the engine chooses to.
Both were added in ECMAScript 2021. Since ECMAScript 2023, non-registered symbols can also be targets. Current browsers and server runtimes support both (see Compatibility). The TC39 proposal’s own advice applies: avoid them if you can. Collection timing is unpredictable and differs between engines, versions and memory conditions.
The problem it solves
Section titled “The problem it solves”OrdersPortal parses large quarterly reports. A Map cache keyed by report id avoids parsing twice, but it holds every report forever. A WeakMap does not help here: it holds its keys weakly, and keys must be objects, not id strings.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). Samples that force a collection must be run with node --expose-gc sample.mjs; globalThis.gc() is a V8 debugging hook, not a standard API, and real programs never call it. Outputs were produced with Node.js 22.23 and were identical on Node.js 24.22, but collection timing is engine-specific.
const load = (id) => ({ id, rows: new Array(100_000).fill(0) });
// A Map cache holds every report strongly: nothing is ever freed.const strongCache = new Map();for (const id of ['2026-Q1', '2026-Q2', '2026-Q3']) strongCache.set(id, load(id));console.log('Map cache entries:', strongCache.size);
// A WeakMap holds its *keys* weakly, and keys must be objects or non-registered symbols.try { new WeakMap().set('2026-Q3', load('2026-Q3'));} catch (error) { console.log(`${error.name}: ${error.message}`);}Output:
Map cache entries: 3TypeError: Invalid value used as weak map keyWhat the cache needs is the reverse: a strong string key and a weak value. That is what WeakRef provides, and FinalizationRegistry removes the empty entries afterwards.
How it works
Section titled “How it works”// Run with: node --expose-gc wr-basics.mjs (globalThis.gc is a V8 debugging hook, not a standard API)const nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));
const registry = new FinalizationRegistry((heldValue) => { console.log('cleanup callback:', heldValue);});
let report = { id: 'R-1', rows: new Array(1_000_000).fill(0) };const ref = new WeakRef(report);registry.register(report, `report ${report.id} was collected`);
console.log('before:', ref.deref()?.id);report = null; // drop the only strong reference
await nextTask(); // let the current job finish; deref() keeps its target alive until thenglobalThis.gc();console.log('after gc:', ref.deref());
await nextTask(); // cleanup callbacks run later, as a separate taskOutput:
before: R-1after gc: undefinedcleanup callback: report R-1 was collectedThe API is small:
| Member | What it does |
|---|---|
new WeakRef(target) |
Holds target weakly. target must be an object or a non-registered symbol, otherwise TypeError. |
ref.deref() |
Returns the target, or undefined after collection. |
new FinalizationRegistry(callback) |
Creates a registry; callback(heldValue) may run after a registered target is collected. |
registry.register(target, heldValue, unregisterToken?) |
Watches target. heldValue is held strongly and passed to the callback; it must not be target itself. |
registry.unregister(unregisterToken) |
Removes every registration made with that token; returns true if any were removed. |
The keep-alive rule
Section titled “The keep-alive rule”The specification guarantees read consistency inside one synchronous run of code (a job): new WeakRef(obj) and a deref() that returns an object both keep it alive until the current job finishes. So an object cannot disappear between if (ref.deref()) and ref.deref().method(). Still, read it once into a local variable.
// Run with: node --expose-gc wr-keep.mjslet session = { user: 'u-42' };const ref = new WeakRef(session); // creating a WeakRef also keeps the target until the job endssession = null;
globalThis.gc();console.log('same job:', ref.deref()?.user); // still alive: kept for the rest of this job
await new Promise((resolve) => setTimeout(resolve, 0));globalThis.gc();console.log('next task:', ref.deref()?.user);Output: same job: u-42, then next task: undefined. This is also why the samples wait for the next task before calling gc().
What is not guaranteed
Section titled “What is not guaranteed”The specification says an engine may empty a weak reference once its target is unreachable, and may schedule a cleanup job; it is never required to. Callbacks can run late, in batches, or never, for example when the page closes or the process exits. They never run synchronously during gc(), and they run on the same thread as your code. A related cleanupSome() method was split into its own proposal and withdrawn in 2023, so there is no standard way to force cleanup.
Realistic example
Section titled “Realistic example”The OrdersPortal report cache keeps a WeakRef per report id. While a dashboard holds a report, get() returns the same object without reparsing. Once nothing else uses it, the garbage collector may reclaim it, and the registry callback deletes the empty map entry.
// report-cache.mjs - OrdersPortal: reuse big parsed reports while something still uses them.// Run with: node --expose-gc report-cache.mjsexport class ReportCache { #load; #entries = new Map(); // id -> WeakRef(report) #registry = new FinalizationRegistry((id) => { // The id may have been reloaded since; only delete the entry if it is still empty. if (this.#entries.get(id)?.deref() === undefined) { this.#entries.delete(id); this.evicted.push(id); } }); evicted = [];
constructor(load) { this.#load = load; }
get(id) { const cached = this.#entries.get(id)?.deref(); if (cached) return cached;
const report = this.#load(id); this.#entries.set(id, new WeakRef(report)); this.#registry.register(report, id); // held value is the id string, never the report return report; }
get size() { return this.#entries.size; }}
let loads = 0;const cache = new ReportCache((id) => { loads += 1; return { id, rows: Array.from({ length: 200_000 }, (_, i) => i) };});
const pinned = cache.get('2026-Q3'); // a dashboard keeps this one opencache.get('2026-Q2'); // used once, then droppedconsole.log('same object:', cache.get('2026-Q3') === pinned, '| loads:', loads, '| size:', cache.size);
await new Promise((resolve) => setTimeout(resolve, 0));globalThis.gc();await new Promise((resolve) => setTimeout(resolve, 0)); // let cleanup callbacks run
console.log('evicted:', cache.evicted, '| size:', cache.size);cache.get('2026-Q3');cache.get('2026-Q2');console.log('loads after re-reading both:', loads, '| pinned still', pinned.id);Output:
same object: true | loads: 2 | size: 2evicted: [ '2026-Q2' ] | size: 1loads after re-reading both: 3 | pinned still 2026-Q3Three details matter. The callback re-checks deref() because the id might have been reloaded before the old report’s callback ran. The held value is the id string; if it were the report, the registry would keep it alive forever. And the cache stays correct if the callback never runs: it only leaks a few empty entries. In production, pair it with a small strong LRU of recent reports so a collection between two requests does not force a reparse.
Common mistakes
Section titled “Common mistakes”- Using
FinalizationRegistryto release resources. File handles, sockets, locks and database connections must be closed explicitly withtry...finallyor aclose()method. Theusingdeclarations from the Explicit Resource Management proposal (stage 4, expected in ES2027) are the language-level answer; finalizers are at best a leak detector that logs “you forgot to close this”. - Making the held value reference the target.
register(obj, obj)throws, butregister(obj, { obj })or a closure that capturesobjsilently keeps it alive. - Calling
deref()twice across anawait. The keep-alive rule only covers one job. After anawait, the object can be gone; read once into a local and use that. - Testing timing with
gc(). Tests that depend on collection are flaky. Test the cache logic with an injected fake. - Registering primitives or registered symbols.
new WeakRef(42)andnew WeakRef(Symbol.for('id'))throwTypeError, because those values can be recreated and so can never be collected. Unregister tokens follow the same rule. - Forgetting
unregister. When you dispose an object yourself, callregistry.unregister(token)so the callback does not run later. The object itself can be the token.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
| Attach data to an object for as long as the object lives | WeakMap (no GC observation needed) |
| Mark objects as seen without keeping them alive | WeakSet |
| Cache large objects by a string or number key, reusing them while in use | WeakRef values plus a FinalizationRegistry to tidy keys |
| Observers or listeners that should not keep subscribers alive | WeakRef to the subscriber, checked on each notification |
| Release external resources | try...finally, close(), or using (not finalizers) |
| Detect leaks in development | FinalizationRegistry logging objects that were collected without being closed |
If the program’s correctness would change depending on when, or whether, collection happens, do not use these APIs. They are for memory optimization and diagnostics only.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data (@mdn/browser-compat-data 8.1.9), WeakRef and FinalizationRegistry are supported in Chrome 84, Edge 84, Firefox 79, Safari 14.1 (iOS 14.5), Node.js 14.6.0, Deno 1.0 and Bun 1.0. Non-registered symbols as targets (ES2023) need Chrome 109, Edge 109, Firefox 146, Safari 16.4, Node.js 20.0.0 and Deno 1.28. Neither API can be polyfilled, because user code cannot observe garbage collection. TypeScript’s types are in lib.es2021.weakref.d.ts.
Interview questions
Section titled “Interview questions”1. What is the difference between a WeakMap and a WeakRef?
A WeakMap holds its keys weakly and its values strongly as long as the key lives; it never lets you observe collection. A WeakRef holds one target weakly, and deref() tells you whether it has been collected. Use WeakMap to attach data to objects; use WeakRef when you need a weak value, such as a cache keyed by a string.
2. Can ref.deref() return an object in one line and undefined on the next?
Not within the same synchronous job: creating a WeakRef or getting a target from deref() keeps the target alive until the job ends. Across an await or a timer callback, yes.
3. Is a FinalizationRegistry callback guaranteed to run?
No. The specification allows engines to delay callbacks indefinitely or skip them, for example on shutdown or when the registry itself is collected. Code must stay correct if they never run.
4. Why does registry.register(obj, obj) throw, and what is the subtler version of the bug?
The held value is kept strongly, so using the target as the held value would keep the target alive forever; the specification rejects it with a TypeError. The subtle version is a held value or callback closure that contains a reference to the target, which is not detected and leaks.
5. Senior scenario: an OrdersPortal browser app keeps a client-side cache of decoded product images and order histories. Memory grows over long sessions. Would you use WeakRef?
First measure with heap snapshots to find what actually retains memory. For data with a natural owner object (a component or a DOM node), a WeakMap keyed by the owner is simpler and deterministic. For entries keyed by id, use a bounded strong LRU for recent items, and optionally a WeakRef layer behind it so items still referenced elsewhere are reused instead of reloaded. Use a FinalizationRegistry only to remove empty map entries, re-checking deref() in the callback, and design every path to work if collection never happens. Anything holding real resources (object URLs, workers, sockets) gets explicit release.
Key takeaways
Section titled “Key takeaways”WeakRef(ES2021) holds a weak value;deref()returns the target orundefined.- A target obtained from
new WeakRef()orderef()stays alive until the current job ends, but not acrossawait. FinalizationRegistrycallbacks are optional, late and unordered: use them for tidying and diagnostics, never for correctness or resource release.- Held values are strong; never let them reference the target.
- Prefer
WeakMap, explicitclose(), bounded caches andtry...finallywhenever they solve the problem.
Related pages
Section titled “Related pages”- WeakMap and WeakSet: weakly held keys without observing collection.
- Map and Set: the strong collections a weak cache usually wraps.
- Symbol: why registered symbols cannot be held weakly.
- Private fields: the
#fields used in the cache class. - Closures: how callbacks accidentally retain objects.
- Python weak references: the same ideas in Python’s
weakrefmodule.
Official references
Section titled “Official references”- ECMAScript Language Specification: WeakRef Objects, FinalizationRegistry Objects and Execution (when targets may be emptied) (current draft; first published in ECMAScript 2021, 12th edition)
- ECMAScript 2021 Language Specification (ECMA-262, 12th edition): WeakRef Objects
- TC39 proposal: WeakRefs
- TC39 proposal: Symbols as WeakMap keys (ES2023)
- TC39 proposal: FinalizationRegistry
cleanupSome(withdrawn) - MDN: WeakRef
- MDN: FinalizationRegistry
- MDN: Memory management