Performance Profiling & Memory Leaks - Inspecting V8 Heaps & Event Loop Lag

Because Node.js servers run continuously for months without restarting, even a tiny memory leak of 500 KB per hour will eventually exhaust V8's default memory ceiling (~1.4 GB on 64-bit systems), causing a catastrophic process crash (FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory).

Programmatic Heap Snapshot Generation

// memoryProfiler.js
const v8 = require('v8');
const path = require('path');

function takeHeapSnapshot() {
  const fileName = path.join(process.cwd(), `snapshot-${Date.now()}.heapsnapshot`);
  const snapshotPath = v8.writeHeapSnapshot(fileName);
  console.log('[HEAP SNAPSHOT WRITTEN]:', snapshotPath);
}

// Take snapshot if memory exceeds threshold
setInterval(() => {
  const memory = process.memoryUsage();
  const heapUsedMB = memory.heapUsed / 1024 / 1024;

  if (heapUsedMB > 500) { // If heap exceeds 500 MB
    console.warn(`[WARNING] High Heap Usage: ${heapUsedMB.toFixed(2)} MB. Generating snapshot...`);
    takeHeapSnapshot();
  }
}, 30000);

Monitoring Event Loop Delay with perf_hooks

const { monitorEventLoopDelay } = require('perf_hooks');

// Monitor event loop delay histogram with 20ms resolution
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();

setInterval(() => {
  console.log({
    minDelayMs: (h.min / 1e6).toFixed(2),
    maxDelayMs: (h.max / 1e6).toFixed(2),
    meanDelayMs: (h.mean / 1e6).toFixed(2),
    p99DelayMs: (h.percentile(99) / 1e6).toFixed(2)
  });
  h.reset();
}, 5000);

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What causes memory leaks in Node.js applications?

Common causes of Node.js memory leaks include: 1) Accidental global variables, 2) Closures holding references to large objects after function execution completes, 3) Forgotten setInterval timers or event listeners that are never removed, and 4) Unbounded in-memory caching objects without size limits or TTL expiration.

Q2. How do you generate a V8 Heap Snapshot in Node.js?

Use the built-in 'v8' module: 'const v8 = require("v8"); v8.writeHeapSnapshot("heap.heapsnapshot");'. You can then open Google Chrome, navigate to Chrome DevTools > Memory tab, and load the snapshot to inspect retained object trees.

Q3. What is Event Loop Delay (Lag) and how do you monitor it?

Event Loop Delay measures the latency between when an event is scheduled and when the event loop actually executes it. The built-in 'perf_hooks.monitorEventLoopDelay()' monitors latency down to nanoseconds. If lag exceeds 50-100ms, the main thread is blocked.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Node.js Architecture & V8

Understand V8 Heap and Call Stack memory layout.

Worker Threads & CPU Offloading

Prevent CPU blocking.

Logging & Monitoring

Log memory usage metrics over time.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!