Sub topic 9
Finding Leaks with Heap Snapshots and Allocation Profiling
This chapter assumes you know how reachability decides what the garbage collector keeps, and that you can recognize the common leak patterns from the previous chapter. You should also be able to open Chrome DevTools and run a script with Node.js.
Reading code can point you to a likely leak. To confirm it, you need measurements. A heap snapshot records every object on the heap and the references between those objects. An allocation profile records where in your code each object was created. You use both together: snapshots tell you what is piling up, and allocation profiles tell you which code created it.
Reading a Heap Snapshot
To take a snapshot, open DevTools, go to the Memory panel, choose Heap snapshot, and click Take snapshot. The summary view groups objects by constructor name. Each row has two size columns, and leak hunting depends on reading them correctly.
| Column | Meaning |
|---|---|
| Shallow size | Memory held by the object itself |
| Retained size | Memory that would be freed if this object were collected, including everything only it keeps alive |
| Distance | Number of references between this object and a GC root |
A small object can have a huge retained size. One array or Map can keep millions of bytes alive by itself. When you are looking for the cause of a leak, sort by retained size.
Select an object and the Retainers panel opens below it. This panel shows the chain of references from a GC root down to that object. That chain is your answer: it shows exactly which reference is keeping the object reachable.
The Three-Snapshot Technique
The most dependable workflow compares snapshots taken before and after a repeated action:
- Load the page and warm it up, so lazy initialization does not show up as noise.
- Take snapshot 1.
- Perform the suspect action several times, for example opening and closing a dialog.
- Take snapshot 2.
- Repeat the action the same number of times, then take snapshot 3.
- Select snapshot 3, switch to Comparison view, and compare against snapshot 1.
DevTools forces a garbage collection before each snapshot, so anything left is still reachable. Suppose some objects appear in snapshot 2, are still present in snapshot 3, and their count grew by the number of actions you performed. Those objects are leaking.
To find detached DOM nodes, type Detached in the class filter. These are elements that were removed from the document but are still referenced from JavaScript.
Doing the Same in Node.js
Node.js can write snapshots to disk. To analyze one, open the Memory panel in Chrome DevTools and use Load to open the .heapsnapshot file. The script below leaks on purpose, so you can practice on it:
const v8 = require("node:v8");
class SessionRecord {
constructor(id) {
this.id = id;
this.payload = "x".repeat(1024);
}
}
const sessions = []; // grows forever: the leak
function handleRequest(id) {
sessions.push(new SessionRecord(id));
}
const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(1);
for (let round = 1; round <= 3; round++) {
for (let i = 0; i < 10_000; i++) handleRequest(round * 10_000 + i);
console.log(`round ${round}: heapUsed ${toMB(process.memoryUsage().heapUsed)} MB`);
console.log(`snapshot: ${v8.writeHeapSnapshot()}`);
}Load the first and third files and compare them. SessionRecord grows by 20,000 instances between the two. Its retainers chain leads to the sessions array.
Allocation Profiling
Snapshots show what survived. They do not show which code keeps allocating. The Memory panel offers two allocation tools for that:
- Allocation instrumentation on timeline records every allocation over time. A blue bar means memory allocated in that interval is still alive. A gray bar means it was collected. Bars that stay blue after repeated actions point to a leak. Selecting a bar shows the stack trace of the allocations behind it.
- Allocation sampling records only a sample of allocations, so its overhead is low enough for long sessions. It attributes memory to functions, which helps you find hot spots that produce a lot of garbage even when nothing is leaking.
Common mistakes:
- Comparing snapshots taken without a warm-up.
- Treating normal cache growth as a leak.
- Reading shallow size when retained size is the column that matters.
Exercise
In a comparison view, an object type has a shallow size of 40 bytes but a retained size of 12 MB, and its count rises by exactly 5 after you open and close a modal 5 times. What do you do next, and what are you looking for?
Show answer
Select one instance and read the Retainers panel. Look for the reference chain from a GC root to that object, such as a listener on window, a module-level array, or a timer callback. Removing or breaking that reference when the modal closes fixes the leak.
Exercise
Why is allocation sampling a better first choice than allocation instrumentation when profiling a long-running session?
Show answer
Sampling records only a fraction of allocations, so its overhead is low and it can run for a long time. Full instrumentation records every allocation with a stack trace. That slows the page down and produces large recordings.