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).
// 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);
perf_hooksconst { 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);
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Understand V8 Heap and Call Stack memory layout.
Prevent CPU blocking.
Log memory usage metrics over time.