Sub topic 9
Finding Leaks with Heap Snapshots and Allocation Profiling
This chapter assumes you know what reachability and garbage collection roots are, and that you know the common leak patterns: forgotten timers, listeners, closures, detached DOM nodes, and unbounded caches. You should be able to run Node.js from a terminal and open Chrome DevTools. The goal is a repeatable way to confirm that a leak exists, find which objects are leaking, and trace them back to the reference that keeps them alive.
What a leak looks like from the outside
A leak in a garbage-collected language is memory that stays reachable after your program no longer needs it. The collector is not at fault, because it frees only what is unreachable. So the job is to find the unwanted reference.
Memory use always moves up and down. Allocation raises it and each collection lowers it, so the graph has a sawtooth shape. A healthy program's sawtooth returns to roughly the same floor after each major collection. A leaking program's floor rises over time. You need to watch that floor, the memory still in use after a full collection, and not the peaks.
The workflow
Leak hunting follows the same loop whether you are in a browser tab or a Node.js server:
- Reproduce one action that you suspect leaks, such as opening and closing a dialog or handling a request.
- Take a baseline measurement after forcing a collection.
- Repeat the action many times, force a collection, and measure again.
- If the floor grew, take heap snapshots and compare them.
- Find the object type whose count grew, then follow its retainers to a root.
- Fix the reference and measure again to confirm.
Measuring first with process.memoryUsage()
Before you open a snapshot, confirm the leak with numbers. In Node.js, process.memoryUsage().heapUsed reports bytes in use on the V8 heap. Run the script below with node --expose-gc leak.js. The --expose-gc flag adds a global gc() function so you can force a full collection before each measurement.
// leak.js
const v8 = require("node:v8");
const sessions = []; // grows forever: the leak
class Session {
constructor(id) {
this.id = id;
this.payload = "x".repeat(10_000);
}
}
function handleRequest(id) {
sessions.push(new Session(id));
}
function measure(label) {
if (typeof global.gc === "function") global.gc();
const { heapUsed } = process.memoryUsage();
console.log(`${label}: heapUsed ${(heapUsed / 1024 / 1024).toFixed(1)} MB`);
}
function snapshot(label) {
if (typeof global.gc === "function") global.gc();
const file = v8.writeHeapSnapshot(`${label}.heapsnapshot`);
console.log(`wrote ${file}`);
}
let nextId = 0;
function burst(count) {
for (let i = 0; i < count; i++) handleRequest(nextId++);
}
burst(100); // warm up so one-time allocations are not counted as growth
measure("baseline");
snapshot("s1");
burst(2000);
measure("after burst 1");
snapshot("s2");
burst(2000);
measure("after burst 2");
snapshot("s3");Each burst adds about 20 MB, and the floor does not come back down. That confirms the leak. The three .heapsnapshot files can be loaded in Chrome DevTools: open the Memory panel and use the Load button.
The three-snapshot technique
One snapshot shows everything alive at that moment, which is mostly legitimate data. Two snapshots show what changed, but some of that change is warm-up: caches filling, modules loading, JIT metadata. Three snapshots separate the two:
- Snapshot 1 is taken after warm-up.
- Snapshot 2 is taken after the suspect action is repeated N times.
- Snapshot 3 is taken after another N repetitions.
Objects allocated between snapshots 1 and 2 that are still alive in snapshot 3 are strong leak candidates. In DevTools, select snapshot 3, set the view to Summary, and use the filter dropdown "Objects allocated between Snapshot 1 and Snapshot 2". Alternatively, choose the Comparison view with snapshot 2 as the base and sort by "# Delta".
If an object count grows by about the same amount in each interval, such as 2,000 Session objects per burst in the example, you have found the leaking type. A delta that matches the number of times you repeated the action is the clearest signal you will get.
Reading a snapshot
The snapshot views group objects by constructor name. These are the columns you will use most:
| Column | Meaning | How to use it |
|---|---|---|
| Distance | Shortest number of references from a GC root | Large distances often point to objects buried deep in a cache or closure chain |
| Shallow Size | Bytes held by the object itself | Usually small; arrays and strings are the exceptions |
| Retained Size | Bytes that would be freed if this object were collected, including everything only it keeps alive | Sort by this to find the object that is responsible for the most memory |
| # New / # Deleted / # Delta | Comparison view counts between two snapshots | Positive delta that tracks your repeat count is the leak |
The difference between shallow and retained size matters. A Map used as a cache may have a shallow size of a few dozen bytes and a retained size of hundreds of megabytes. The retained size is the one that tells you what to fix.
The available views are:
- Summary groups by constructor. Start here.
- Comparison shows differences between two snapshots.
- Containment shows the heap as a tree from the roots (window, global object, and internal GC roots). It is useful when you want to see what a global holds.
- Statistics is a pie chart of memory by category: code, strings, arrays, typed arrays, system objects.
Names you will see
Some entries are not your classes:
(closure)is a function object. Expand it to find itscontext, which holds the captured variables.system / Contextis a closure scope. A large retained size here usually means a closure captured more than it needed.(string),(array),(concatenated string), and(sliced string)are engine internals. A sliced string can keep a much larger parent string alive.Detached HTMLDivElement(and otherDetachedelements) is a DOM node that has been removed from the document but is still referenced from JavaScript.
Following the retainer path
When you select an object, the Retainers pane at the bottom shows who references it. Read the path from the selected object outward until you reach something you recognize: a global variable, a module-level array, an event listener, a timer.
In the Node.js example, a Session instance's retainers read roughly like this:
Session @12345
[1503] in Array @6789
sessions in system / Context @2468
context in (closure) handleRequestEverything below the first line is the chain keeping the object alive. Your code appears in it as sessions. The fix is to bound that array, remove entries when a session ends, or key the data by an object and store it in a WeakMap.
Detached DOM nodes in the browser
Paste this into the console of any page to create a detached-node leak you can practice on:
const removedRows = [];
function addAndRemoveRow(i) {
const row = document.createElement("div");
row.textContent = `row ${i}`;
document.body.appendChild(row);
removedRows.push(row); // keeps the node alive after removal
row.remove();
}
for (let i = 0; i < 1000; i++) addAndRemoveRow(i);Open the Memory panel, take a heap snapshot, and type Detached in the class filter. You will see about 1,000 Detached HTMLDivElement entries. Select one and the Retainers pane shows removedRows as the array holding it. A detached node also retains its whole subtree and any data attached to it, so one forgotten reference to a container can keep thousands of nodes alive.
Allocation profiling: when a snapshot is not enough
A snapshot tells you what is alive, not where it was allocated. The Memory panel has two allocation-oriented profile types for that question.
Allocation instrumentation on timeline records each allocation with its stack trace while you interact with the page. The timeline shows bars for allocations over time. Blue marks objects that are still alive at the end of the recording, and gray marks objects that were collected. Blue bars that keep appearing every time you repeat an action point to a leak. Select a range on the timeline to list only the objects allocated during it, then open the allocation stack for any object. The overhead is high, so record short sessions.
Allocation sampling samples allocations at intervals and attributes memory to functions. The overhead is low enough to run for minutes, and the result is a list of functions sorted by how many bytes they allocated. Use it to find allocation-heavy code, the subject of the final chapter, as well as leaks.
| Tool | Answers | Overhead | Best for |
|---|---|---|---|
| Heap snapshot | What is alive and who retains it | Pause during capture | Confirming and tracing a leak |
| Allocation timeline | Which allocations survived, with stacks | High | Linking a leaked object to the code that created it |
| Allocation sampling | Which functions allocate the most | Low | Long sessions, allocation pressure |
| `performance.memory` / `process.memoryUsage()` | How big the heap is | Negligible | Detecting a rising floor |
Snapshots from a running Node.js process
You do not have to edit code to get a snapshot from a server. Two built-in flags help:
# Write a snapshot whenever the process receives SIGUSR2
node --heapsnapshot-signal=SIGUSR2 app.js
# In another terminal:
kill -USR2 <pid>
# Automatically write up to 2 snapshots as the heap approaches its limit
node --heapsnapshot-near-heap-limit=2 app.jsYou can also start Node.js with --inspect, open chrome://inspect in Chrome, and use the same Memory panel against the live process, including the allocation timeline. The next chapter on Node.js covers heap limits and ongoing monitoring in more detail.
Common mistakes
- Measuring without a full collection. The heap before a major GC contains garbage. Force a collection, or compare only the floors.
- Skipping warm-up. First-run caches, compiled code, and lazy modules look like growth. Discard the first iteration.
- Too few repetitions. If one leaked object per action is 200 bytes, ten repetitions are lost in the noise. Repeat hundreds or thousands of times so the delta stands out.
- Chasing shallow size. Sort by retained size and look for the object that owns the memory.
- Stopping at the first retainer. The nearest retainer is often an internal array or context. Keep reading outward until you reach a name from your own code.
Exercise
You repeat "open settings dialog, close it" 50 times between snapshots 1 and 2, and 50 more times before snapshot 3. In the Comparison view, SettingsPanel shows a delta of +50 in each interval, and (string) shows +3,000 in the first interval and +12 in the second. Which one is the likely leak, and why?
Show answer
SettingsPanel is the likely leak. Its delta matches the repetition count exactly and stays constant across intervals, which means each open/close cycle leaves one instance reachable. The (string) growth is large at first and then nearly stops, which is typical of warm-up such as caches filling or code being compiled.
Exercise
A cache Map shows a shallow size of 64 bytes but a retained size of 300 MB. A teammate says the Map is "tiny" and cannot be the problem. What is wrong with that reasoning, and what would you check next?
Show answer
Shallow size counts only the Map object itself. Retained size counts everything that would be freed if the Map were collected, which includes all its keys and values. A 300 MB retained size means the Map is the only path keeping that data alive. Next, check how many entries it has and whether entries are ever removed. Then add an eviction policy or size limit, or switch to a WeakMap if the keys are objects whose lifetime should control the entries.
Exercise
You take a snapshot in the browser and find 400 Detached HTMLLIElement objects. Their retainer path ends at $0 or at an entry in the console. Is this a leak in your application?
Show answer
Probably not. DevTools keeps the currently selected element ($0) and logged objects reachable. Clear the console, deselect elements, reload if needed, repeat the action, and take a new snapshot. If the detached nodes remain and are retained by your own variables, listeners, or closures, then the leak is in your application.