Node.js Developer interview question
How do you investigate a Node.js memory leak?
Reproduce growth under stable load, compare heap snapshots and allocation profiles, inspect retained-object paths, timers, listeners and caches, fix the owning lifecycle, then verify heap returns to a steady state.
Direct answer
What a strong answer covers
How it works
A leak in Node is usually a reference that outlives its purpose: an ever-growing Map used as a cache, event listeners added per request and never removed, closures captured by timers that are never cleared, or a promise chain that keeps request objects alive. The investigation reproduces steady growth under constant load, takes heap snapshots minutes apart, and compares them by retained size to see which constructor is accumulating; the retainer tree then shows who holds the objects. An allocation timeline profile shows where the growing objects are created. The fix changes the owning lifecycle, and the proof is a heap that plateaus after the same test.
Example
A service grew 50 MB per hour; two snapshots showed thousands of retained Socket objects reachable from an array in a metrics plugin that pushed each connection and never spliced it out on close. Removing the entry on the close event fixed it, and a soak test in staging with a heap chart now runs before each release.
Common mistakes
- Restarting the service nightly as the permanent fix.
- Comparing snapshots taken seconds apart and chasing garbage that has not been collected yet.
- Adding process listeners inside a request handler.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.