Node.js › Advanced Node.js
What is a memory leak in the context of a long-running Node.js server, and what are the most common causes?
AdvancedAnswer
A memory leak occurs when objects that are no longer needed remain reachable from a GC root, preventing the garbage collector from reclaiming them, causing memory usage to climb steadily over time until the process crashes or is killed. Common causes in Node.js include: event listeners added repeatedly without removal (especially on long-lived EventEmitters), closures capturing large objects unintentionally, unbounded caches or arrays that grow without eviction, and timers/intervals that are never cleared.
// Leak: a new listener is added on every request, never removed
app.get('/data', (req, res) => {
eventEmitter.on('update', () => res.json(getData())); // accumulates forever
});
// Fixed: use .once(), or explicitly remove the listener afterward
app.get('/data', (req, res) => {
eventEmitter.once('update', () => res.json(getData()));
});Real-world example A service's memory grows steadily over several days until it's killed by the OS; heap snapshot comparison in Chrome DevTools reveals thousands of accumulated 'update' listeners on a singleton EventEmitter, traced back to a route handler that added a new listener on every request without ever removing it.