Course contentsShow
← Node.js
Lesson 675 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Memory Leak Detection

Profile server instances to identify objects that are not being garbage collected.

Memory Leak Detection

In this lesson, you will learn how to profile your running Node.js server instances to identify specific objects that are failing to be cleared by the Garbage Collector.

When your application consumes more memory over time without ever releasing it, you have a memory leak. In a busy production environment, this is usually caused by long-lived objects—like large arrays, cached data, or persistent event listeners—that are accidentally held in memory because they are still reachable via a global scope or a closure.

Taking a Heap Snapshot

To detect these "zombie" objects, we use Heap Snapshots. A snapshot is essentially a photograph of everything currently living in your server’s memory. By taking two snapshots at different times—usually after the server has warmed up and again after performing a specific task—we can compare them to see what objects were created but never deleted.

If you are using the Chrome DevTools to profile your server, you can trigger a snapshot programmatically during your request cycle:

const v8 = require('v8');
const fs = require('fs');

// Take a snapshot and save it to the disk
const snapshot = v8.getHeapSnapshot();
const stream = fs.createWriteStream('heap-dump.heapsnapshot');
snapshot.pipe(stream);

Analyzing the Diff

Once you have two files, you load them into the "Memory" tab in Chrome DevTools. You then use the Comparison view.

  1. Snapshot 1: Take this while the server is idle.
  2. Action: Perform a series of requests (e.g., hit an API endpoint that processes data).
  3. Snapshot 2: Take this after the requests finish.

When you compare these two, look for the "Delta" column. If an object type (like an Object, Array, or a custom UserSession class) shows a large positive number in the delta, that is your leak. The tool will show you the Retaining Path—a chain of references leading back to a global object that is preventing the Garbage Collector from cleaning up your data. If you see a UserSession that stays in memory even after the user logs out, you have found the exact spot where you failed to nullify a reference or clear a timer.

Key Takeaway: Use heap snapshot comparisons to identify objects that persist across requests, then trace their "Retaining Path" to find the lingering references causing your memory leak.