Yousef AldabbasSystems & backend engineering
● ENGINEERING NOTESAMMAN, JORDAN
← back to posts

Node.js Internals #5: V8 Heap and Garbage Collection

2026-11-09 · nodejs

Part 5 of the Node.js Internals series, the last one. Part 1: event loop, Part 2: libuv, Part 3: streams, Part 4: workers. Every output below was run on Node v26.8.1.

Back in Part 1, the heap was "where values live". This part opens it up: how V8 organises memory, how it decides what to free, and how to tell when your code is leaking.

The heap has spaces

v8.getHeapSpaceStatistics() shows them. On a fresh process:

space                      used   available
new_space                   0.5 MB    0.5 MB
old_space                   2.9 MB    0.4 MB
code_space                  0.0 MB    0.2 MB
trusted_space               0.8 MB    0.5 MB
large_object_space          0.1 MB    0.0 MB

heap_size_limit: 4192.0 MB
type HeapSpaces = {
  new_space: "young generation: freshly allocated objects, tiny, collected often";
  old_space: "old generation: objects that stuck around, collected rarely";
  large_object_space: "very big objects get their own pages";
  code_space: "compiled machine code";
};

The design rests on the generational hypothesis: most objects die young. So V8 keeps newly allocated objects in a small area and collects it frequently and cheaply, and collects the large old area much less often.

Two collectors

Watching it happen

A loop that creates three million short-lived objects, run with node --trace-gc:

let sink; for (let i = 0; i < 3e6; i++) sink = { id: i, tag: "x" + i };
[...] 9 ms: Scavenge 4.5 (5.4) -> 3.8 (5.9) MB, ... allocation failure
[...] 9 ms: Scavenge 4.5 (6.4) -> 3.8 (6.6) MB, ... allocation failure
...
42 Scavenge lines, 0 Mark-Compact lines

Dozens of scavenges, each under a fifth of a millisecond, memory dropping from 4.5 to 3.8 MB each time, and no major GC at all. Lots of garbage is cheap when it dies young. (The exact count of 42 varies run to run.)

What a leak looks like

A leak in a GC language is not "forgotten to free". It is "still reachable, so cannot be freed". The classic version is a cache that never evicts:

const cache = new Map();
setInterval(() => {
  for (let k = 0; k < 20000; k++) cache.set("req-" + i++, Buffer.alloc(512, 1));
  console.log(`entries=${cache.size} heapUsed=... external=...`);
}, 100);
entries=20000   heapUsed=10 MB  external=11 MB
entries=60000   heapUsed=21 MB  external=31 MB
entries=120000  heapUsed=38 MB  external=60 MB
entries=220000  heapUsed=62 MB  external=109 MB

Both columns climb forever and never come back down, however many GCs run, because the Map keeps every entry reachable. Two details worth knowing: the Buffer bytes show up under external (memory outside the V8 heap) while the Map's own bookkeeping grows heapUsed, so check both numbers. And heapUsed can dip briefly (it went 58 to 56 MB at one point) because a scavenge ran; a leak is the trend, not any single sample.

What happens at the limit

With the limit forced down to 32 MB (--max-old-space-size=32) and a loop that keeps everything:

Mark-Compact 34.5 (42.2) -> 34.5 (42.2) MB ... allocation failure; GC in old space requested
Mark-Compact (reduce) 34.5 (42.2) -> 33.7 (37.2) MB ... last resort
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

V8 tried major GCs, they freed almost nothing (34.5 to 33.7 MB), and the process died. The default limit on my machine was about 4 GB, so a real leak takes longer, but it ends the same way. In containers, set the limit deliberately with --max-old-space-size (in MiB) so it fits under the container memory limit.

The fix pattern: let go of keys

When you attach data to objects you do not own, a Map keeps the key alive; a WeakMap does not. I checked with a WeakRef and a forced GC (--expose-gc, for experiments only):

Map      key still alive (leak)
WeakMap  key collected

For caches, the more common fix is simply a size or time limit (an LRU), so entries leave on purpose.

How to investigate a real leak

1) Watch process.memoryUsage() over time and confirm a trend after GCs, not a spike. 2) Run with --trace-gc to see whether major GCs are reclaiming anything. 3) Take heap snapshots (v8.writeHeapSnapshot() or --heap-snapshot-on-oom), open them in Chrome DevTools, and compare two snapshots to see which object type grew. 4) Follow the retaining path from the growing objects back to a root: that path is your leak. I did not demonstrate snapshots here; the Node diagnostics guide walks through them.

Cheatsheet

QuestionAnswer
Where do new objects go?new_space (young generation)
Cheap collectionScavenge: young generation only
Expensive collectionMark-Compact: whole heap
See GC activitynode --trace-gc app.js
See memory by spacev8.getHeapSpaceStatistics(), process.memoryUsage()
Raise or set the limit--max-old-space-size=MiB
Buffer memoryCounted under external, not heapUsed
Cache keyed by objectsWeakMap, or bound the size

Conclusion: the whole series in five lines

  1. JS runs on one thread, and the event loop serves queues in a fixed order (Part 1).
  2. Sockets are watched by the OS; fs, DNS lookup and crypto share a 4-thread pool (Part 2).
  3. Streams keep memory bounded, and write() returning false is the brake (Part 3).
  4. CPU-heavy JS belongs in worker threads, with data transferred or guarded by Atomics (Part 4).
  5. The heap is generational, and leaks are things you are still pointing at (Part 5).

References

Node.js Internals: Part 1 · Part 2 · Part 3 · Part 4 · Part 5