In this lesson, you will learn how to track heap growth over time to detect and isolate memory leaks using memory profiling data.
The Concept of Heap Growth
A memory leak in Node.js occurs when objects are no longer needed but are not garbage collected because they are still referenced by the application. In a healthy long-running process, the V8 heap should follow a "sawtooth" pattern: memory usage increases as objects are allocated and drops sharply after a garbage collection cycle. A memory leak appears as a "staircase" pattern, where the baseline memory usage at the bottom of each sawtooth continuously rises over time.
Capturing and Analyzing Profiles
To detect these patterns, you cannot rely on a single snapshot. Instead, you must capture multiple heap snapshots at consistent intervals—for example, every 30 minutes—under a steady production load.
Using the v8 module, you can trigger snapshots programmatically:
const v8 = require('v8');
const fs = require('fs');
function takeSnapshot(filename) {
const snapshot = v8.getHeapSnapshot();
const stream = fs.createWriteStream(filename);
snapshot.pipe(stream);
}
// Trigger periodically to track growth
setInterval(() => takeSnapshot(`heap-${Date.now()}.heapsnapshot`), 1800000);
Isolating the Leak
Once you have collected a series of snapshots, load them into the Chrome DevTools Memory tab. The "Comparison" view is your primary tool here. By comparing an early snapshot (T1) with a later snapshot (T2), you can isolate the objects that persist across cycles.
Focus on the "Delta" column; if a specific class or object type shows a consistently positive delta in every interval, you have identified the culprit. Look closely at the "Retainers" view for those objects—this shows you exactly which variables or closures are holding onto those references, preventing the garbage collector from reclaiming the memory. If these objects are growing proportional to the number of requests or active sessions, you have successfully isolated your leak.
Key Takeaway: A memory leak is confirmed when the baseline of your heap usage rises over time; by comparing sequential snapshots, you can identify the specific objects that remain uncollected and trace their retainers to find the root cause.