Sub topic 14
Observing GC Behavior in Node.js and DevTools
This chapter assumes you are comfortable with WeakRef, deref(), FinalizationRegistry, and the fact that a dereferenced target stays alive until the current job ends. You should also be able to run Node.js from a terminal and open Chrome DevTools. The goal is practical. You will learn how to see the collector at work while you experiment and debug, without writing code that depends on the collector's timing.
Why Observation Needs Special Tools
In normal code you cannot tell when garbage collection happens. The engine runs it when it decides memory pressure justifies the cost. A small script might exit before any collection runs at all. If you create an object, drop every strong reference to it, and immediately check a WeakRef, you will almost always find the target still there.
Collection being unobservable is a design property. To study weak references you need two things that ordinary programs lack:
- A way to ask for a collection, so you are not waiting on memory pressure.
- A way to see what is still in memory and why, so you can explain a target that refuses to die.
Node.js and Chromium both use the V8 engine, so they offer much the same tools behind different switches.
Requesting a Collection in Node.js
Starting Node with --expose-gc installs a global gc() function. Calling it asks V8 to run a full collection right away.
node --expose-gc observe.jsThere is a catch tied to the kept-alive rule from an earlier chapter. Any target you called deref() on during the current job is kept alive until that job finishes, and gc() will not collect it. Finalization callbacks also never run inside your synchronous code. The engine queues them as separate tasks after a collection. A useful experiment has to yield to the event loop before calling gc() and again afterwards.
A Reusable Helper
A single forced collection does not guarantee that finalizers run, so a well-behaved helper retries a few times and gives up after a limit. Save this as observe.js:
// Run with: node --expose-gc observe.js
const { setTimeout: sleep } = require('node:timers/promises');
if (typeof globalThis.gc !== 'function') {
throw new Error('Start Node with --expose-gc to run this experiment');
}
async function collectUntil(predicate, attempts = 10) {
for (let i = 0; i < attempts; i++) {
await sleep(0); // end the current job so kept-alive targets are released
globalThis.gc(); // request a full collection
await sleep(0); // give queued cleanup callbacks a chance to run
if (predicate()) return true;
}
return false;
}
let finalizedLabel = null;
const registry = new FinalizationRegistry((label) => {
finalizedLabel = label;
});
class Payload {
constructor() {
this.data = new Array(100_000).fill(0);
}
}
function makeRef() {
const payload = new Payload();
registry.register(payload, 'payload-1');
return new WeakRef(payload);
}
async function main() {
const ref = makeRef();
console.log('alive after creation:', ref.deref() !== undefined);
const collected = await collectUntil(
() => ref.deref() === undefined && finalizedLabel !== null
);
console.log('collected and finalized:', collected);
console.log('held value seen by callback:', finalizedLabel);
}
main();On current Node versions this usually prints true and payload-1. Look at the structure:
- The target is created inside
makeRef(), so no local variable inmain()keeps it reachable. - The first
deref()inmain()makes the target kept-alive for that job. The helper's firstawaitends the job. - The predicate calls
deref()again. If the target survived, it is kept alive only until the next loop iteration yields.
Using the Helper to Find a Leak
Observation tools pay off when a target does not disappear. Change makeRef() so it also stores the payload somewhere long-lived:
const listeners = [];
function makeRef() {
const payload = new Payload();
listeners.push(() => payload.data.length); // closure captures payload
registry.register(payload, 'payload-1');
return new WeakRef(payload);
}Now collectUntil returns false after ten attempts. The closure in listeners holds a strong reference, so the payload stays reachable. In a small file you can spot this by reading the code. In a large application you need a heap snapshot to find it.
Watching Collections with `--trace-gc`
To see when V8 collects without changing your code, use the --trace-gc flag:
node --trace-gc --expose-gc observe.jsEach collection prints one line. The line shows the collection type (Scavenge for the young generation, Mark-Compact or similar for a full collection), the heap size before and after, and the time it took. The exact format changes between V8 versions, so read it as a rough guide. It answers two questions quickly: did a collection happen at all, and did the heap shrink when you expected it to?
Heap Snapshots
A heap snapshot records every object in the heap and the references between them. In Node you can write one from code:
const v8 = require('node:v8');
const file = v8.writeHeapSnapshot();
console.log('snapshot written to', file);Open Chrome DevTools, go to the Memory panel, and load the .heapsnapshot file. Writing a snapshot blocks the process and can take a lot of memory and time on a large heap, so avoid doing it in production without care.
Useful habits when reading a snapshot:
- Give your objects class names. The snapshot groups objects by constructor. A
Payloadclass is much easier to find than many anonymousObjectentries. This is why the example uses a class. - Use the Retainers pane. Select an object instance and DevTools shows the chains of references that keep it alive. In the leak example the chain leads from
listenersthrough the closure's context topayload. - Compare two snapshots. Take one before an operation and one after. The Comparison view lists objects that were allocated and not freed in between.
DevTools takes a full collection before it records a snapshot. An object that appears in a snapshot is therefore strongly reachable from somewhere, not merely waiting for a collection.
Observing in the Browser
Pages cannot call gc(). Chrome DevTools gives you several ways to trigger and inspect collection:
- The Collect garbage button (a trash can icon) in the Memory or Performance panel requests a full collection.
- Taking a heap snapshot also forces one, as noted above.
- For automated experiments you can launch Chromium with
--js-flags="--expose-gc", andgc()becomes available to page scripts. Use a throwaway browser profile for this.
To debug a Node process in the same interface, start it with node --inspect --expose-gc app.js and open chrome://inspect. The Memory panel then works against the Node heap.
| Tool | Environment | What it tells you | Cost |
|---|---|---|---|
| `gc()` via `--expose-gc` | Node, flagged Chromium | Whether a target can be collected now | Low, test only |
| `--trace-gc` | Node | When collections run and how much they free | Noisy output |
| `v8.writeHeapSnapshot()` | Node | Every object and its retainers | Pauses process, large file |
| Memory panel snapshot | Chrome, Node via `--inspect` | Retainer chains, comparisons | Pauses, manual |
| Collect garbage button | Chrome DevTools | Forces a collection interactively | Manual |
Testing Code That Uses Weak References
Automated tests that assert "the finalizer ran" tend to be flaky. They pass on one Node version and fail on another, or fail under load. These guidelines keep tests stable:
- Test logic, not the collector. Pull the cleanup callback's body out into a named function, such as the stale-entry check in a weak cache, and call it directly with crafted inputs.
- Simulate collection. Inject a fake
WeakRef-like object whosederef()you control. That lets you test the "target is gone" branch on demand. - Keep real GC tests separate. If you want an end-to-end leak check, run it in its own suite with
--expose-gc, use a retry helper likecollectUntil, and treat a failure as "investigate" rather than as proof of a bug.
Exercise
In main(), you replace const collected = await collectUntil(...) with a synchronous call to globalThis.gc() followed immediately by console.log(ref.deref()). The output shows the Payload object instead of undefined. Explain why, naming both mechanisms involved.
Show answer
The earlier ref.deref() call in the same job added the target to the kept-alive list, so gc() cannot collect it until the job ends. Even if the target had been collected, the cleanup callback would not have run yet, because finalization callbacks are queued as separate tasks and only run after the current synchronous code returns to the event loop.
Exercise
A heap snapshot of a long-running service shows thousands of Session instances that your weak cache should have released. Describe the steps you would take in DevTools to find the cause.
Show answer
Load the snapshot in the Memory panel and filter the summary by the Session constructor. Select one instance and inspect the Retainers pane to see which reference chain keeps it alive. Common results are a closure, an event listener, a Map that stores the value directly, or a held value that refers to the session. Taking a second snapshot after more traffic and using the Comparison view confirms whether the count keeps growing.
Exercise
Why is it better to unit-test a weak cache's cleanup callback by calling its logic directly than by forcing garbage collection in the test?
Show answer
Forced collection is not guaranteed to collect the target or to run the callback at any particular time, so such tests are flaky across engine versions and system load. Calling the extracted logic with a controlled, fake dereferenced value tests the same branches deterministically.