Memory leaks in long-running Node.js services are sneaky because the app runs fine for hours, then slows down or crashes. The fix is a repeatable diagnostic process rather than guesswork.
First, reproduce the growth. Watch process memory with a simple script that logs process.memoryUsage().heapUsed every minute, or graph it in your monitoring tool. A healthy service plateaus; a leaking one climbs in a staircase pattern even when idle.
Second, take heap snapshots. Use the built-in inspector (node –inspect) and Chrome DevTools, or the heapdump package, and capture three snapshots over time. Compare them to see which object types keep growing. Look for retained arrays, ever-growing caches, or closures holding references.
Common culprits include unbounded caches with no eviction limit, event listeners added on every request but never removed, timers or intervals created per request, and global arrays that only append. Also check for listeners on EventEmitter objects that grow without limit.
Third, confirm the fix by re-running the same load test and verifying that heap usage returns to baseline after garbage collection. Tools like clinic.js and the –max-old-space-size flag help isolate and cap the problem. The key discipline is measuring before and after, never guessing.