#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 53 of 62hard

How to detect and fix memory leaks in Node.js?

Finding and resolving memory leaks.

What You'll Learn

  • Common causes of memory leaks
  • Detection tools
  • How to fix them

Common Causes

  1. Global variables
  2. Closures retaining references
  3. Event listeners not removed
  4. Growing arrays/objects
  5. Timers not cleared

Detection

code.jsJavaScript
// Monitor memory usage
setInterval(() => {
  const used = process.memoryUsage();
  console.log({
    heapTotal: Math.round(used.heapTotal / 1024 / 1024) + 'MB',
    heapUsed: Math.round(used.heapUsed / 1024 / 1024) + 'MB',
    external: Math.round(used.external / 1024 / 1024) + 'MB'
  });
}, 5000);

Using Heap Snapshots

$ terminalBash
node --inspect app.js

Open Chrome DevTools and take heap snapshots.

Common Fixes

code.jsJavaScript
// ❌ Memory leak: event listeners pile up
socket.on('data', handleData);

// ✅ Fix: remove listener when done
socket.on('data', handleData);
socket.on('close', () => {
  socket.removeListener('data', handleData);
});

// ❌ Memory leak: growing array
const cache = [];
function addToCache(item) {
  cache.push(item);
}

// ✅ Fix: limit size
function addToCache(item) {
  if (cache.length >= 1000) cache.shift();
  cache.push(item);
}

// ❌ Memory leak: timer not cleared
const interval = setInterval(doSomething, 1000);

// ✅ Fix: clear when done
clearInterval(interval);

Using clinic.js

$ terminalBash
npm install -g clinic
clinic doctor -- node app.js