Node.js Developer interview question · Most asked
What causes memory leaks in Node.js and how do you diagnose them?
Summary
Common causes: unbounded caches or global arrays, event listeners never removed, closures holding large objects, timers/intervals never cleared, and growing queues of unprocessed work. Diagnose with heap snapshots (Chrome DevTools via --inspect, v8.writeHeapSnapshot()), comparing snapshots over time, and monitoring process.memoryUsage().
Longer Answer
Use LRU caches with size limits, WeakMap for object metadata, remove listeners, and clear intervals on shutdown. Tools: clinic.js (heapprofiler), --heapsnapshot-near-heap-limit, APM memory metrics. Setting --max-old-space-size only delays a real leak.
Key Points
- Unbounded caches/listeners/timers
- Heap snapshot comparison
- LRU caches and WeakMaps
- Monitor RSS and heap usage
More most-asked Node.js Developer questions
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are streams in Node.js and what is backpressure?
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- What are the differences between CommonJS and ES modules in Node.js?