How I Tracked Down a Node.js Memory Leak (Heap Snapshot)

Our internal batch server was crashing with OOM every few days, so I looked into the cause. At first I thought it was a library issue, but it ultimately turned out to be a leak from not cleaning up event listeners. Here's a brief summary of the process.

1. Confirming symptoms: PM2 logs showed "JavaScript heap out of memory," and the restart interval kept getting shorter.

2. Comparing heap snapshots: I attached via node --inspect and took three snapshots with Chrome DevTools to track objects whose retained size kept growing.

3. Finding the cause: We were registering listeners on an EventEmitter on every request but never calling removeListener. As requests piled up, listeners and closures stayed in memory.

4. Fix: I changed it to register/unregister listeners per request and switched to once. After that, the memory graph stayed flat for two weeks.

The lesson is... don't assume "the framework will handle it for me." If you run into similar symptoms, start by taking a heap snapshot.

by 클라우드러버854

3 answers