0
0
Node.jsframework~5 mins

Common memory leak patterns in Node.js

Choose your learning style9 modes available
Introduction
Memory leaks make your Node.js app slow or crash by using too much memory over time.
When your app gets slower after running for a while.
When your server crashes with 'out of memory' errors.
When you want to keep your app stable and fast.
When debugging performance issues in long-running Node.js processes.
Syntax
Node.js
No specific syntax, but common patterns include:

1. Global variables holding large data.
2. Closures capturing large objects.
3. Event listeners not removed.
4. Caches growing without limits.
5. Timers or intervals not cleared.
Memory leaks happen when your code keeps references to data you no longer need.
Node.js does automatic memory cleanup, but your code can stop it by holding references.
Examples
This global array keeps growing and never frees memory.
Node.js
// 1. Global variable holding data
const bigData = [];
function addData(item) {
  bigData.push(item); // keeps growing forever
}
The inner function keeps the large object alive even if not needed.
Node.js
// 2. Closure capturing large object
function createHandler() {
  const largeObject = { data: new Array(1000000).fill('x') };
  return function() {
    console.log(largeObject.data.length);
  };
}
const handler = createHandler();
Listeners stay attached and keep references, causing leaks.
Node.js
// 3. Event listener not removed
const EventEmitter = require('events');
const emitter = new EventEmitter();
function onData() {
  // do something
}
emitter.on('data', onData);
// never call emitter.removeListener('data', onData);
Cache grows forever if you don't remove old entries.
Node.js
// 4. Cache growing without limit
const cache = new Map();
function cacheData(key, value) {
  cache.set(key, value); // no limit or cleanup
}
Sample Program
This program adds a new event listener every second but never removes them. The listener count grows, causing a memory leak.
Node.js
const EventEmitter = require('events');

// Memory leak example: event listeners not removed
const emitter = new EventEmitter();

function leakListener() {
  console.log('Event received');
}

// Add listener every second without removing
setInterval(() => {
  emitter.on('data', leakListener);
  emitter.emit('data');
  console.log('Listener count:', emitter.listenerCount('data'));
}, 1000);
OutputSuccess
Important Notes
Use tools like Node.js built-in --inspect flag and Chrome DevTools to find leaks.
Always remove event listeners when no longer needed with removeListener or off.
Limit cache size or use weak references to avoid leaks.
Summary
Memory leaks happen when your code keeps data it no longer needs.
Common leaks include global variables, closures, event listeners, and caches.
Fix leaks by removing listeners, clearing caches, and avoiding unnecessary references.