Part 1 · How V8 runs your code: bytecode, tiers and deoptimisation
From source text to machine code
A Node service that is fine at launch and dies at 3 am a week later usually has a memory problem.
V8 is the JavaScript engine, written in C++, that runs inside Node.js and Chrome. It does not interpret your text line by line. It parses the source and turns each function into bytecode, a compact instruction list for a small virtual machine. An interpreter called Ignition runs that bytecode. This starts quickly, because compiling to bytecode is cheap, but the code runs slowly.
V8 watches which functions run often. A function that gets hot is compiled to machine code, and V8 has more than one compiler for that. The V8 team describes the tiers as follows, from cheapest to most ambitious.
Tier
What it is
Trade-off
Ignition
the bytecode interpreter
starts at once, slowest to run
Sparkplug
a baseline compiler that turns bytecode straight into machine code without optimising
very fast to compile, modest speed-up
Maglev
a mid-tier optimising compiler
fast to compile, good code
TurboFan
the top-tier optimising compiler
slow to compile, fastest code
A function can climb through the tiers while a program runs. A short script may never leave the first one. You do not choose a tier. V8 chooses, based on how hot the function is, and it can move code back down as well as up.
Optimised code is a bet
The optimising tiers make code fast by assuming what they have already seen. If shape.w has always been read from objects built as { w, h }, the compiled code can fetch it from a fixed position without looking anything up. V8 records the layout of each object in a hidden structure called a map, also known as a hidden class. Objects created with the same properties in the same order share one map. That is why property access can be so quick.
The assumption can break. If an object arrives whose properties were added in a different order, it has a different map, and the fast code no longer applies. V8 throws the optimised code away and goes back to the bytecode. This is called deoptimisation, or a bailout, and V8 may optimise again later. One bailout costs little. A function that bails out again and again wastes the time that optimising was meant to save.
The script feeds the same function 200,000 objects of one shape, then one object with the properties in the opposite order, then 200,000 more.
js
function area(shape) {
return shape.w * shape.h;
}
let total = 0;
for (let i = 0; i < 200_000; i++) {
total += area({ w: i, h: 2 });
}
total += area({ h: 2, w: 3 });
for (let i = 0; i < 200_000; i++) {
total += area({ w: i, h: 2 });
}
console.log(total);
bash
node --trace-opt --trace-deopt l1-deopt.mjs
Reading the trace
V8 prints a long line for every compile and every bailout, and a lot of them belong to Node's own code. The output below keeps only the lines that mention area, and removes the memory addresses. This is edited output, not the full trace.
text
[marking area for optimization to MAGLEV, reason: hot and stable]
[compiling method area (target MAGLEV)]
[marking area for optimization to TURBOFAN_JS, reason: hot and stable]
[compiling method area (target TURBOFAN_JS)]
[bailout (kind: deopt-eager, reason: wrong map), function: area]
[marking area for optimization to MAGLEV, reason: hot and stable]
[compiling method area (target MAGLEV)]
Node 24.18.0, V8 13.6. Filtered as described.
The story is in the order. area became hot and was compiled by Maglev, then by TurboFan. When the object with the other property order arrived, V8 logged reason: wrong map: the optimised code had expected one map, and this was another. It discarded the code, area ran as bytecode for a moment, and it was marked hot and compiled by Maglev again.
Two habits keep your code on the fast path without any effort. Create objects of the same kind with the same properties, in the same order, usually in one constructor or one factory function. And do not add or delete properties on an object after you create it. Neither is a reason to write strange code. V8 is built to run ordinary, consistent JavaScript well.
This is also a reason to measure before tuning. The next lessons turn to memory, and a later chapter covers profiling.
What does reason: wrong map mean in a deoptimisation line?
The optimised code was built for objects with one hidden class (map), and it met an object with a different one. V8 threw the optimised code away and fell back to bytecode.
Why does V8 not compile every function with the strongest compiler at once?
Optimising compilers are slow, and most functions run only a few times. Starting in bytecode makes programs begin quickly, and only the hot functions pay for the better compilers.
Your hot function keeps bailing out. What is the first thing to check in the code that calls it?
Whether its arguments have the same shape every time: the same properties, added in the same order, with the same kinds of values.
Part 2 · The heap: young and old generations
Where objects live and how the collector finds garbage
Every object you create sits in V8's heap until nothing refers to it. Knowing how that heap is divided explains why some code is cheap on memory and some is not.
Local variables of simple types and the chain of function calls live on the stack, which grows and shrinks as functions run. Objects, arrays, strings and closures live on the heap. V8 frees heap memory automatically with a garbage collector: it starts from a set of roots, which are the stack and the global object, follows every reference, and treats whatever it reached as alive. Everything else is garbage. An object is never freed because you stopped using it. It is freed because nothing can reach it.
Most objects die young. A request object, a temporary array or a string built for one response is useless within milliseconds. V8 exploits this with a generational heap. This is how the V8 team describes the design in their garbage collector write-up.
The young generation is small. New objects are allocated here. It is split into two halves called semi-spaces, and only one half is in use at a time.
A scavenge (a minor collection) copies the live objects from the used half into the other half and abandons the rest. Its cost depends on how many objects survive, not on how many were created.
An object that survives two scavenges is promoted to the old generation.
The old generation is cleaned by a major collection, called mark-sweep-compact: mark everything reachable, sweep the gaps into free lists, and compact the most fragmented pages. Much of this work runs on helper threads while your JavaScript continues.
Exactly when an object is promoted is an internal policy, and it changes between V8 versions. The scene follows one cached object through the whole path.
The life of one object
Animated sceneOne object, through the generations0:16
Watch for one cached object moving up from new space to old space
Read it as steps
An object is allocated in new space, survives two scavenges, is promoted to old space and is freed by a major collection.
This object took the long path, because the cache kept referring to it. The exits in the diagram show what usually happens instead. At the first or second scavenge nothing refers to the object, so it is simply left behind, at no cost. A service that creates short-lived objects is therefore cheap. A service that keeps objects alive for a while, such as a cache or a large queue, sends them all through the copying and into the old generation.
Watching it in numbers
Node lets you read the spaces. v8.getHeapSpaceStatistics() returns one record per space. The script prints those that are in use, in megabytes.
js
import v8 from'node:v8';
const mb = (n) => (n / 1024 / 1024).toFixed(1).padStart(6);
const rows = v8.getHeapSpaceStatistics()
.filter((s) => s.space_size > 0);
console.log('space'.padEnd(20) + ' used size (MB)');
for (const s of rows) {
console.log(s.space_name.padEnd(20) + mb(s.space_used_size)
+ mb(s.space_size));
}
text
space used size (MB)
new_space 0.41.0
old_space 2.92.9
code_space 0.00.5
trusted_space 0.91.4
large_object_space 0.30.3
A freshly started Node 24.18.0 process.
Two spaces matter most here: new_space for the young generation, and old_space. large_object_space holds single objects too big for a regular page, such as a very large array. code_space holds machine code.
Now the generational idea in a run. The next script watches garbage collections through a PerformanceObserver while a loop creates three million short-lived objects. Each one is stored in a ring of 100 slots and is overwritten a hundred iterations later.
js
import { PerformanceObserver, constants } from'node:perf_hooks';
const kinds = new Map([
[constants.NODE_PERFORMANCE_GC_MINOR, 'minor (scavenge)'],
[constants.NODE_PERFORMANCE_GC_MAJOR, 'major (mark-sweep-compact)'],
]);
const seen = {};
const obs = new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
const k = kinds.get(e.detail.kind) ?? 'other ' + e.detail.kind;
seen[k] = (seen[k] ?? 0) + 1;
}
});
obs.observe({ entryTypes: ['gc'] });
// Short-lived garbage: each object is stored in a small ring and is// overwritten 100 iterations later, so it dies young.const ring = new Array(100);
for (let i = 0; i < 3_000_000; i++) {
ring[i % 100] = { id: i, tags: [i, i + 1] };
}
setTimeout(() => {
console.log(seen);
obs.disconnect();
}, 100);
text
{ 'minor (scavenge)': 189 }
The same count came out on five runs.
Three million objects produced 189 scavenges and no major collection at all. The young generation is cleared again and again, and nothing is promoted because nothing survives.
The ring is there on purpose. A first version of this loop assigned each object to one variable and nothing else. The optimising compiler can then skip creating most of those objects, and the count shrank to a handful that changed from run to run (5 to 18 here). With the optimising compilers switched off, the same loop ran 392 scavenges every time. Storing the objects where the program can reach them makes the allocation real, and the count steady.
Objects that stay
The last script keeps what it creates. It reads old_space before and after holding 400,000 small objects in an array, and then allocates an array with two million slots.
js
import v8 from'node:v8';
const used = (name) => v8.getHeapSpaceStatistics()
.find((s) => s.space_name === name).space_used_size;
const mb = (n) => (n / 1024 / 1024).toFixed(1) + ' MB';
console.log('old_space before:', mb(used('old_space')));
const survivors = [];
for (let i = 0; i < 400_000; i++) {
survivors.push({ id: i, name: 'order-' + i });
}
console.log('old_space after 400,000 kept objects:',
mb(used('old_space')));
const big = new Array(2_000_000).fill(0);
console.log('large_object_space:', mb(used('large_object_space')),
'(a 2,000,000-slot array)', big.length);
text
old_space before: 2.9 MB
old_space after 400,000 kept objects: 18.5 MB
large_object_space: 12.6 MB (a 2,000,000-slot array) 2000000
Holding 400,000 objects grew old_space from 2.9 MB to 18.5 MB, because the survivors were promoted there. The two-million-slot array did not go to the young generation. It went straight to large_object_space, which shows 12.6 MB.
You can watch the cost difference with --trace-gc, which prints one line for every collection. The sizes are heap used and, in brackets, heap committed, before and after, in megabytes. The figure after them is how long the collection took in milliseconds. The script runs the survivors script and then the ring script. For the first it shows every scavenge. For the second it prints only the average of its 189. Process id and address prefixes are removed, and the end of each line is cut.
bash
trim() {
sed -E 's/^\[[^]]*\] +//; s/, pooled.*MB//; s/ +\(average.*//'
}
node --trace-gc l2-promote.mjs | grep Scavenge | trim
node --trace-gc l2-scavenge2.mjs | grep Scavenge | trim |
awk '{ n++; t += $(NF-3) }
END { printf "%d scavenges, average %.2f ms\n", n, t / n }'
While the survivors piled up, each scavenge had more live objects to copy, and the pause grew from under 1 ms to over 9 ms in this run. The scavenges in the ring script took 0.07 ms on average, because almost nothing was alive when they ran. This is what a cost that depends on survivors, and not on allocation, looks like in a trace.
So the cost of memory in Node is mostly the cost of what you keep. Creating a lot of garbage is cheap. Holding on to a lot of objects is not, because it fills the old generation and makes major collections longer.
A request handler creates a 10-element array per call and returns. Does that put pressure on the old generation?
Hardly. The array dies before the next scavenge or after it, and is never promoted. The young generation handles this kind of garbage cheaply.
In the run above, three million objects caused 189 scavenges. Why did no major collection happen?
Each object was unreachable almost at once, so nothing was promoted and the old generation did not fill up. Major collections are triggered by old-space growth.
Which space did the two-million-slot array land in, and why?
large_object_space. Objects above a size threshold get their own pages instead of the semi-spaces.
Part 3 · Heap limits, and memory outside the heap
The heap limit
Your JavaScript objects live in a heap of limited size, and a process can be killed for using too much memory even when the heap is small. You need to know which number to look at.
V8 sets a heap size limit, and a program that needs more than that aborts. You can read the limit, and change it with the --max-old-space-size flag, which takes the size of the old space in mebibytes (MiB). The script prints the limit. It runs once as it is, and once with the flag set to 512.
The first line is a default run, the second used --max-old-space-size=512.
The default on this machine is 4,288 MB. It depends on the machine's memory and on the Node version, so another machine gives another number. When the flag asked for 512, the reported limit was 704 MB. That is higher than the flag, because the figure includes the young generation as well as the old space. Do not expect it to equal what you passed.
bash
show='console.log(Math.round(
require("v8").getHeapStatistics().heap_size_limit / 1048576) + " MB")'
for size in642565121024; do
echo -n "old $size: "
node --max-old-space-size=$size -e "$show"
done
for semi in163264128; do
echo -n "old 512, semi $semi: "
node --max-old-space-size=512 --max-semi-space-size=$semi -e "$show"
done
text
old 64: 256 MB
old 256: 448 MB
old 512: 704 MB
old 1024: 1216 MB
old 512, semi 16: 560 MB
old 512, semi 32: 608 MB
old 512, semi 64: 704 MB
old 512, semi 128: 896 MB
Node 24.18.0 on this machine.
Every line is the old-space limit plus a young generation: 192 MB on top of 64, 256, 512 and 1024 alike. The last four lines vary --max-semi-space-size with the old space fixed at 512, and the extra amount moves with it: 48, 96, 192 and 384 MB. It is three times the semi-space size, and the 192 MB default means this machine allows a semi-space of 64 MB. Those defaults can differ between machines and Node versions, so read the number on yours. The Node documentation names --max-semi-space-size as the flag that sizes the young generation. A larger value means scavenges run less often, at the price of more memory.
What happens at the limit is not an exception you can catch. The next script keeps allocating arrays in a loop, with the limit set to 64 MB.
js
const keep = [];
while (true) keep.push(new Array(10_000).fill('x'.repeat(10)));
text
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap
out of memory
exit code: 134
Run with --max-old-space-size=64. The line is wrapped.
V8 prints a fatal error and the process aborts. A try/catch cannot help, and neither can an uncaughtException handler. Raising the limit only buys time. The fix is to find out what is holding the memory, which the next two lessons cover.
Memory that is not in the heap
Look at the numbers process.memoryUsage() reports, and notice how they differ.
Field
What it counts
rss
resident set size: all the physical memory the process holds, including the heap, code, stacks and native libraries
heapTotal
memory V8 has reserved for its heap
heapUsed
the part of the heap in use by live and not yet collected objects
external
memory used by C++ objects tied to JavaScript objects, such as buffers
arrayBuffers
memory held by ArrayBuffer and Buffer objects, a part of external
A Buffer stores its bytes outside the V8 heap. The heap holds only a small handle. The script below measures this.
A 200 MB buffer raised rss by 200 MB and external and arrayBuffers by about the same, while heapUsed stayed at 5 MB. An array of five million numbers behaved the other way: heapUsed rose by 76 MB, and rss followed.
Which number to watch
A heap limit on its own does not protect you from running out of memory. A container, a process manager or the operating system kills a process by rss, and that covers buffers and everything native. A service that handles file uploads in memory can reach its container limit while heapUsed looks calm.
So watch both. heapUsed shows what the garbage collector could in principle free. A steady climb is the signature of a leak. rss shows what the platform will judge you by. external and arrayBuffers tell you when the climb comes from buffers and not from objects.
When you set --max-old-space-size, leave room below the container's memory limit for buffers, the young generation, code and the Node runtime itself. A heap limit equal to the whole container limit can only end one way. The right figure depends on the service, so measure rss under real load before deciding.
Reading the heap through a snapshot, covered two lessons ahead, tells you what the objects are. The graphs of rss, heapUsed and external over time tell you whether memory comes back after a quiet period. If heapUsed drops back and rss does not, the process holds on to freed memory, which is normal. If neither falls, something is retaining it.
A service shows heapUsed flat at 90 MB but rss climbing to 1.5 GB. Where do you look first?
external and arrayBuffers. Buffers live outside the V8 heap, so a leak of buffers or native memory does not show up in heapUsed.
You run node --max-old-space-size=512 app.js and heap_size_limit reports 704 MB. Is something wrong?
No. The reported limit counts more than the old space, so it can be larger than the flag. Plan around the flag but read the limit as reported.
What happens when a Node process reaches its heap limit?
V8 prints FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory and the process aborts, with exit code 134 in the run above. It cannot be caught.
Part 4 · Four common memory leaks
What a leak is in a garbage-collected language
A leak in Node is rarely a lost pointer. It is an object that your program still refers to, so the collector is right not to free it.
The collector frees only what is unreachable, so every leak comes down to a reference that you forgot to remove, and whatever hangs off it. Four patterns cause most real cases.
Pattern
How it leaks
Fix
Unbounded cache
a Map or object gains an entry per key and never loses any
a size limit, an expiry, or a real cache library
Listeners and timers
emitter.on(...) runs per request and is never removed, or a setInterval is never cleared
once, off, clearInterval, and removal on close
Closures
a callback that outlives its job keeps every variable in its scope alive
copy out the small value you need, and do not capture the large one
Unbounded queue
work is added faster than it is taken out
a limit with a rejection or back-pressure, and monitoring of depth
A request-per-minute service hides these for days. A cricket score app at the end of a final shows them in minutes.
A cache with no limit
The cache is the most common one. A page cache keyed by a request id looks harmless in code review. The script serves 250,000 requests with unique ids, in five rounds, and after each round it forces a collection with global.gc() so that only reachable objects remain. This needs the --expose-gc flag, which you should use for experiments only.
js
const cache = new Map();
function handle(id) {
if (!cache.has(id)) {
cache.set(id, { id, rows: new Array(100).fill(id) });
}
return cache.get(id);
}
const mb = (n) => (n / 1024 / 1024).toFixed(1);
for (let round = 1; round <= 5; round++) {
for (let i = 0; i < 50_000; i++) handle(round * 1_000_000 + i);
global.gc();
console.log('after', round * 50_000, 'requests: cache size',
cache.size, ' heapUsed', mb(process.memoryUsage().heapUsed), 'MB');
}
text
after 50000 requests: cache size 50000 heapUsed 47.9 MB
after 100000 requests: cache size 100000 heapUsed 92.4 MB
after 150000 requests: cache size 150000 heapUsed 138.2 MB
after 200000 requests: cache size 200000 heapUsed 180.5 MB
after 250000 requests: cache size 250000 heapUsed 222.9 MB
Run with --expose-gc.
heapUsed grew with the cache: about 44 MB per 50,000 entries, even after a forced collection. The collector ran and found nothing to free, because the Map held every entry. That straight line is the shape of a leak.
The next script is the same service with a limit of 10,000 entries. It uses the fact that a Map keeps its keys in insertion order: a hit moves the entry to the end, and an insert beyond the limit deletes the first key, which is the least recently used one.
js
const MAX = 10_000;
const cache = new Map();
function handle(id) {
if (cache.has(id)) {
const hit = cache.get(id);
cache.delete(id);
cache.set(id, hit);
return hit;
}
const entry = { id, rows: new Array(100).fill(id) };
cache.set(id, entry);
if (cache.size > MAX) cache.delete(cache.keys().next().value);
return entry;
}
const mb = (n) => (n / 1024 / 1024).toFixed(1);
for (let round = 1; round <= 5; round++) {
for (let i = 0; i < 50_000; i++) handle(round * 1_000_000 + i);
global.gc();
console.log('after', round * 50_000, 'requests: cache size',
cache.size, ' heapUsed', mb(process.memoryUsage().heapUsed), 'MB');
}
text
after 50000 requests: cache size 10000 heapUsed 13.2 MB
after 100000 requests: cache size 10000 heapUsed 13.5 MB
after 150000 requests: cache size 10000 heapUsed 13.5 MB
after 200000 requests: cache size 10000 heapUsed 13.5 MB
after 250000 requests: cache size 10000 heapUsed 13.5 MB
Now the cache holds 10,000 entries and the heap stays near 13.5 MB through the same 250,000 requests. The straight line became a flat one. A bound is the cheapest fix there is.
How long until it crashes
From the leak run you can estimate when this service would die. The slope between the first and last round is about 175 MB for 200,000 entries, which is a little over 900 bytes per entry on this machine.
Animated sceneHow long before the heap limit0:16
Time to an out-of-memory abort: ≈ 42 min (if nothing is ever evicted)
Read it as steps
From the measured size of one cache entry and the heap limit, the time to an out-of-memory crash.
The traffic figure is an assumption, and the rest comes from the run. The point is the scale. A leak this small per request kills a busy service in under an hour, and kills a quiet one only after days, which is why such crashes seem to come from nowhere.
The other three, in code you recognise
A listener leak adds a listener inside a request handler. Each request adds one more to an emitter that lives as long as the process, such as a shared event bus. Every listener keeps its closure alive. Node warns when one event has more than ten listeners (MaxListenersExceededWarning), and that warning is a leak signal, not noise. The fix is to register once, or to remove the listener when the request ends. The same goes for a timer: a setInterval created per connection keeps running after the connection is gone unless you clear it.
A closure leak is subtler. A function keeps alive the variables of the scope it was created in, so a small callback can hold a huge buffer or response body just because both were in the same function. If the callback is stored somewhere long-lived, for example in a retry table, the large object stays too. The fix is to pass only what is needed. Compute the small value first, and let the large one go out of scope.
An unbounded queue is a leak that looks like load. A producer adds jobs to an array faster than the consumer removes them. Memory grows with the backlog, and all the while latency worsens. Put a limit on the queue and decide what happens beyond it: reject the new work, or slow the producer down. The streams chapter covers the second option.
Each of these has a different cause and one shared symptom. heapUsed rises and does not fall after a forced collection. The next lesson shows how to see which objects are accumulating.
A Map caches an object for every user id and never deletes. After a forced garbage collection, heapUsed is still rising. Why does the collector not free the objects?
They are reachable: the Map refers to every one of them, and the Map itself is reachable from the program. The collector frees only unreachable objects.
In the bounded cache, what makes cache.keys().next().value the right key to delete?
A Map iterates in insertion order, and a cache hit deletes and re-inserts its key, so the first key is the least recently used.
You see MaxListenersExceededWarning after a few hours. What does it most likely mean?
Listeners are being added repeatedly and never removed. It usually points to code that registers a listener per request on a long-lived emitter.
Part 5 · Finding a leak with heap snapshots
What a heap snapshot is
You know that something is leaking. A heap snapshot tells you what.
A heap snapshot is a file that lists every object in the V8 heap at one moment, with its type, its size and what refers to it. v8.writeHeapSnapshot() writes one. The format is JSON, the file ends in .heapsnapshot, and Chrome DevTools opens it in its Memory tab. The usual technique takes two snapshots with the leak running in between, and compares them: the object type whose count grew by roughly the amount of work done is the suspect.
A snapshot has costs. Per the Node documentation, writing one needs about twice the memory the heap currently holds, and it blocks the event loop for as long as it takes. That is a reason not to take one on a process that is already close to its limit, and a reason to take it on one instance with traffic moved away.
You can read the file yourself. It is JSON with a flat nodes array, several numbers per node, and a strings table. The helper below counts objects of one class name. It looks only at nodes whose type is object, since the class also appears as a function, a string and a piece of code.
The counts are exact: 1,000 and then 6,000. Each Session takes 40 bytes of its own, and the heap snapshot grew by about 2.8 MB, because each Session also holds a 200-character string and an entry in the Map. In DevTools you would see this as a row for Session in the Comparison view, with a delta of +5,000, and clicking a single Session shows its retainers. The retainers are the chain of references from a GC root to the object. The leak is whatever stands at the top of that chain: here, the Map called sessions.
The retainer path is the main reason to use a snapshot and not a guess. The class that grows is often not the culprit. A growing Array or Object is too general to blame, but its retainer chain still names the variable that holds it.
Getting a snapshot from a running service
You do not always know in advance when to take one. Node offers three ways to ask a live process.
--heapsnapshot-signal=SIGUSR2 makes the process write a snapshot every time it receives that signal. Send it with kill -USR2 <pid>.
--heapsnapshot-near-heap-limit=3 tries to write up to three snapshots as the heap approaches its limit, so you capture the leak just before it kills the process.
v8.writeHeapSnapshot() inside your own code, for example behind an admin-only endpoint.
The signal option needs a signal Windows does not deliver, so this run is Linux, with Node 24.18.0 under WSL. The script starts, waits, and the shell sends it the signal.
Linux, Node 24.18.0. The file name holds date, time, process id and a sequence number.
The file appeared in the working directory with a name that carries the date, the time and the process id. Download it from the machine and open it in DevTools. For a leak you are chasing, take two with a few minutes of load between them.
A heap snapshot answers "what is being kept". A related tool, the sampling heap profiler started with --heap-prof, answers "which code allocates it". The profiling chapter uses it.
Why filter on node type object in the helper?
A class name shows up on several kinds of nodes: the objects, the constructor function, a string and compiled code. Only the object nodes are instances.
Two snapshots show 1,000 and then 6,000 Session objects. What do you look at next in DevTools?
The retainers of one Session: the chain of references from a GC root. It names the collection or variable that is holding them all.
Why not take a snapshot of a process that is nearly out of memory?
Writing a snapshot needs about as much memory again as the heap holds, and it blocks the event loop while it runs. It can push the process over the edge.
Part 6 · Weak references: WeakMap, WeakRef and FinalizationRegistry
Holding an object without keeping it alive
Sometimes you want to attach data to an object, or watch it, without becoming the reason it stays in memory. JavaScript has three tools for that.
An ordinary reference is a strong reference. It keeps its target alive. A weak reference does not. If only weak references remain, the collector may free the object, and the weak reference then stops pointing at anything.
WeakMap is a map whose keys are held weakly. Keys must be objects. The entry exists while the key object is reachable from somewhere else. When the key becomes unreachable, the entry is eligible for collection together with its value. Use it to add private metadata to objects that you do not own, such as a request or a socket, without a cleanup step. A Map in the same place would be a leak, as the previous lessons showed. WeakSet is the same idea for a set.
A WeakMap is deliberately not iterable, has no size and has no clear. If you could count entries, your program would behave differently depending on when the collector ran, and the language avoids exposing that.
WeakRef wraps one object. Calling deref() returns the object while it is alive and undefined once it has been collected. It suits an optional cache of a large, rebuildable object: use it if it is still there, and rebuild it if not.
FinalizationRegistry lets you ask for a callback after an object has been collected. The language does not promise when, or that it will run at all, for instance when the process exits first.
The run
The script ties the three together on one object, a user. It sets metadata in a WeakMap, takes a WeakRef, registers a finalizer, then drops the only strong reference and forces a collection. The experiment needs --expose-gc. A WeakMap cannot be inspected, so the WeakRef is how we observe that the object is gone. The await sleep(0) matters: deref() keeps the object alive until the end of the current job, so the script lets the job end before it collects.
js
import { setTimeout as sleep } from'node:timers/promises';
const meta = new WeakMap();
let user = { name: 'Asha' };
meta.set(user, { lastSeen: Date.now() });
const ref = new WeakRef(user);
const registry = new FinalizationRegistry((label) => {
console.log('finalizer ran for', label);
});
registry.register(user, 'user Asha');
console.log('before: meta has user:', meta.has(user),
' ref.deref() is', typeof ref.deref());
user = null;
await sleep(0);
global.gc();
await sleep(50);
console.log('after gc: ref.deref() is', typeof ref.deref());
text
before: meta has user: true ref.deref() is object
finalizer ran for user Asha
after gc: ref.deref() is undefined
Run with --expose-gc.
Before the collection, deref() returned the object. After it, deref() returned undefined, and the finalizer ran with the label we registered. The WeakMap entry is gone as well, since its key is gone, although a WeakMap offers no way to look. Without --expose-gc, the call global.gc() throws a TypeError, because the function does not exist.
Rules for using them
Do not use weak references to make a leak disappear. If a cache grows without bound, give it a size limit. A weak reference gives the collector permission to free the object, not a promise that it will do so soon.
Do not rely on finalizers for correctness. Close files, sockets and locks explicitly, with try and finally. A finalizer is a last-resort safety net at best.
Check deref() every time. Its result can be undefined on any call after the target loses its last strong reference.
Keep --expose-gc for experiments. Calling gc() by hand in production pauses your program for no gain, because V8 already collects when it needs to.
The most useful of the three is the WeakMap. It fixes a common leak, a Map keyed by an object, with one change of class and no cleanup code. WeakRef and FinalizationRegistry are rare in application code and more at home in libraries.
Term
Meaning
Garbage collector
the part of V8 that frees objects nothing can reach
Scavenge
a minor collection of the young generation
Old generation
where long-lived objects are kept, cleaned by mark-sweep-compact
Retainer
the chain of references from a GC root that keeps an object alive
Weak reference
a reference that does not stop the collector freeing its target
Why is a WeakMap not iterable?
Its contents would change whenever the garbage collector ran, so a loop over it could give different results at different times. The language hides that.
A Map keyed by request objects grows forever. What is the smallest change that stops the leak?
Switch to a WeakMap. Entries are then eligible for collection as soon as the request object is unreachable, with no cleanup code.
After user = null and a forced collection, ref.deref() returned undefined in the run. Is that guaranteed in general?
No. A collection may not happen when you expect. The language only says a weak target may be freed once it is unreachable, so always check the result of deref().