debugMajorpending
Memory leak detection in long-running Node.js applications
Viewed 0 times
heap snapshotmemory leakevent listener leakclinic.jsheapUsedmax-old-space-size
nodejslinux
Error Messages
Problem
Node.js process memory grows continuously over hours or days. Eventually crashes with heap out of memory. Restarting temporarily fixes it. The leak is slow and hard to reproduce in development.
Solution
(1) Generate heap snapshots: process.memoryUsage() for quick check. Use --inspect and Chrome DevTools for heap snapshots. (2) Compare two snapshots taken minutes apart — look for growing object counts. (3) Common leak sources: event listeners not removed (emitter.removeListener or AbortController), closures capturing large objects, global caches without eviction (use LRU cache with maxSize), timers not cleared (setInterval without clearInterval), streams not properly consumed or destroyed. (4) Use clinic.js (clinic heapprofiler) for automated leak detection. (5) Use --max-old-space-size to set explicit limit and crash early. (6) In production: monitor process.memoryUsage().heapUsed over time — alert on continuous growth.
Why
JavaScript's garbage collector frees unreachable objects. A memory leak means objects stay reachable (via closures, event listeners, global references) even when logically unused. V8's GC can't free them.
Revisions (0)
No revisions yet.