How to handle memory leaks in Node.js
· Category: Node.js
Short answer
Memory leaks occur when objects are no longer needed but remain referenced. Detect them by monitoring heap usage and analyzing heap snapshots.
Steps
- Monitor memory usage with
--inspectand Chrome DevTools. - Take heap snapshots before and after suspected leak periods.
- Compare snapshots to identify retained objects.
- Look for common causes: global variables, unclosed event listeners, and closures holding large scopes.
- Fix by removing listeners, nullifying references, and using WeakMap where appropriate.
Tips
- Use monitoring tools like clinic.js or New Relic to track heap trends over time.
- Set
--max-old-space-sizecautiously; increasing it only delays the symptom without fixing the leak.
Common issues
- Adding event listeners in request handlers without removing them leaks memory per request.
- Recursive
setIntervaltimers accumulate if never cleared.