Sub topic 11
Building a Weak-Value Cache
This chapter assumes you already know the WeakRef constructor and deref(), how FinalizationRegistry.register() uses held values and unregister tokens, and that the engine makes no promises about when callbacks run. Here those pieces are combined into a cache whose values can be garbage collected whenever nothing else in the program uses them.
The Problem a Weak-Value Cache Solves
Suppose you decode images, parse large documents, or build expensive view models, and each result has a string or numeric ID. You want two requests for the same ID to get the same object, and you don't want to compute it twice. A plain Map does that, but it keeps every value alive forever, so it is a memory leak with a nicer name.
A WeakMap doesn't fit either. A WeakMap holds its keys weakly, and the keys must be objects. Here the keys are strings that live forever, and the thing you want held weakly is the value. That combination is a weak-value cache:
| Structure | Key held | Value held | Key type | Typical use |
|---|---|---|---|---|
| `Map` | Strongly | Strongly | Any | Ordinary lookup tables |
| `WeakMap` | Weakly | Strongly while the key lives | Objects, non-registered symbols | Attaching metadata to objects |
| `Map` of `WeakRef` + `FinalizationRegistry` | Strongly | Weakly | Any | Deduplicating expensive objects by ID |
The design has two parts:
- A
Mapfrom key toWeakRef(value). Lookups callderef(). If the result isundefined, the value is gone and the cache recomputes it. - A
FinalizationRegistrythat removes the deadMapentry after a value is collected. Without it, theMapslowly fills with emptyWeakRefwrappers. Each one is small, but they add up over a long-running process.
A Complete Implementation
class WeakValueCache {
#entries = new Map();
#registry = new FinalizationRegistry((key) => {
const ref = this.#entries.get(key);
// The key may have been reused for a newer, still-live value.
if (ref !== undefined && ref.deref() === undefined) {
this.#entries.delete(key);
}
});
get(key) {
return this.#entries.get(key)?.deref();
}
set(key, value) {
// Throws TypeError for primitives and registered symbols.
const ref = new WeakRef(value);
const old = this.#entries.get(key);
if (old !== undefined) {
this.#registry.unregister(old);
}
this.#entries.set(key, ref);
// target: value, held value: key, unregister token: ref
this.#registry.register(value, key, ref);
return this;
}
getOrCompute(key, compute) {
const cached = this.get(key);
if (cached !== undefined) return cached;
const value = compute(key);
this.set(key, value);
return value;
}
delete(key) {
const ref = this.#entries.get(key);
if (ref === undefined) return false;
this.#registry.unregister(ref);
return this.#entries.delete(key);
}
// Number of Map entries, including dead ones not yet cleaned up.
get approximateSize() {
return this.#entries.size;
}
// Remove dead entries now instead of waiting for callbacks.
prune() {
for (const [key, ref] of this.#entries) {
if (ref.deref() === undefined) {
this.#entries.delete(key);
}
}
}
}
module.exports = { WeakValueCache };Why each argument to register() is what it is
- The target is
value. The registry should fire when the value is collected. - The held value is
key, a string or number. The callback needs it to find the rightMapentry. A primitive key cannot keep the value alive. If you passed something like{ key, value }as the held value, the registry would hold the value strongly and it would never be collected. - The unregister token is the
WeakRefobjectref. TheMapalready holds it strongly, and eachset()creates a new one, so it identifies exactly one registration. Whenset()overwrites a key ordelete()removes it, the old registration is cancelled and a stale callback can't fire for it later.
The Key-Reuse Race
The check inside the callback deals with the most important edge case. Here is the order of events it guards against:
set('a', v1)registersv1with held value'a'.v1becomes unreachable and is collected. Its cleanup callback is queued but hasn't run yet.getOrCompute('a', ...)finds an emptyWeakRef, computesv2, and stores a new entry under'a'.- The queued callback for
v1finally runs with'a'.
A naive callback that always calls this.#entries.delete(key) would now delete the live entry for v2. Nothing breaks immediately, but the next lookup recomputes a value that was still in use, and two different objects now exist for the same ID. That defeats the deduplication the cache exists for.
The guard ref.deref() === undefined fixes this. If the current entry holds a live value, the callback leaves it alone. If the current entry is also dead, deleting it is correct no matter which collection triggered the callback.
You might expect the unregister(old) call in set() to cover this case. It doesn't. In step 3 the cache goes through set(), which calls unregister(old). But the engine may already have queued the cleanup for v1, and the specification doesn't promise that unregistering cancels a callback that is already queued. Treat unregister() as an optimization and the deref() check as the actual guarantee.
Using the Cache
// demo.js — run with: node --expose-gc demo.js
const { WeakValueCache } = require('./weak-value-cache.js');
const cache = new WeakValueCache();
let computeCount = 0;
function loadDocument(id) {
computeCount++;
return { id, body: 'x'.repeat(1_000_000) };
}
let doc = cache.getOrCompute('report', loadDocument);
const again = cache.getOrCompute('report', loadDocument);
console.log(doc === again, computeCount); // true 1
// Drop every strong reference we hold.
doc = null;
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
(async () => {
// Let the current job finish so deref'd targets are no longer kept alive.
await wait(0);
for (let i = 0; i < 10 && cache.get('report') !== undefined; i++) {
globalThis.gc();
await wait(10);
}
console.log('value after gc:', cache.get('report')); // usually undefined
await wait(50);
console.log('entries left:', cache.approximateSize); // usually 0, not guaranteed
})();Look at again in this script. It is a module-level const that still points at the document, so in practice the document stays alive and the first log line after GC prints the object. Remove again, or set it to null too, and the value goes away. A forgotten strong reference like this is the usual reason a weak cache seems not to work.
The words "usually" in the comments are there on purpose. Even with --expose-gc, the engine may decline to collect the value, may collect it without running the callback, or may run the callback later than this script waits.
Edge Cases and Design Decisions
| Situation | What happens | How the implementation handles it |
|---|---|---|
| Value is a primitive (`42`, `'text'`) | `new WeakRef` throws `TypeError` | `set()` builds the ref first, so the `Map` is untouched |
| Value is a registered symbol (`Symbol.for('x')`) | `new WeakRef` throws `TypeError` | Same as above |
| Key reused before the callback runs | Stale callback arrives with the same key | `deref()` check in the callback |
| Key overwritten with `set()` | Old registration is still pending | `unregister(old)` using the `WeakRef` as token |
| Callback never runs | Dead `WeakRef` wrappers stay in the `Map` | `prune()` can be called on a timer or when the cache grows |
| `get()` then reading in the same job | Target is kept alive until the job ends | Safe; no need to re-check within one synchronous run |
| Value strongly reachable from its key object | Never collected | Use primitive keys, or use `WeakMap` when keys are objects |
| Cache itself becomes unreachable | Registry may never call back | Harmless; the whole structure is garbage |
Don't report exact size
approximateSize has that name for a reason. Between a collection and its callback, the Map still counts the dead entry. If you need an exact count, call prune() first. Even then, the count can be out of date by the next job.
Weak caches can be too weak
A weak-value cache only deduplicates objects that something else is still using. In a short-lived request handler, the value may become unreachable as soon as the response is sent, so the cache rarely hits. If the goal is to avoid recomputation, a bounded strong cache such as an LRU (least recently used) cache is usually better. A common hybrid keeps the last N values strongly in an LRU and everything else in the weak layer, so recent items survive collection and older items are still deduplicated while they are in use.
Don't hide the key inside the callback's closure
The callback above reaches the Map through this, and it gets the key from its argument. Don't create a separate closure per value that captures the value, for example by registering a fresh arrow function that mentions value. The registry holds its callback strongly, so the captured value would never become unreachable.
Exercises
Exercise
A teammate simplifies the cleanup callback to (key) => this.#entries.delete(key). Describe a sequence of calls that makes this version misbehave, and explain the visible symptom.
Show answer
Call set('a', v1) and drop every reference to v1. The GC collects v1 and queues its callback. Before the callback runs, getOrCompute('a', fn) sees an empty WeakRef and stores v2. The stale callback then runs with 'a' and deletes the live entry for v2. The next getOrCompute('a', fn) recomputes and returns v3 while code that still holds v2 keeps using it, so two different objects now exist for the same key and deduplication fails.
Exercise
Why does the implementation register key as the held value instead of { key, ref } or { key, value }? Is either alternative safe?
Show answer
The registry holds held values strongly. { key, value } holds the target strongly, so the value can never be collected and the cache leaks; passing the value itself directly would throw a TypeError. { key, ref } is safe, because a WeakRef doesn't keep its target alive, and it would let the callback compare this.#entries.get(key) === ref, which is an exact identity check. A primitive key is simpler and allocates nothing extra, and the deref() check gives the same correctness.
Exercise
Your service keeps a WeakValueCache of parsed configuration objects, and memory profiling shows the Map growing into the millions of entries even though few configs are live. What is the likely cause, and what two changes would you make?
Show answer
Cleanup callbacks are not guaranteed to run, or are running too slowly to keep up, so dead WeakRef wrappers pile up in the Map. First, call prune() periodically or when approximateSize passes a threshold, instead of relying only on the registry. Second, check whether the keys are unbounded, for example a unique ID per request. If they are, the cache can never hit and should be removed or replaced with a bounded LRU.