Skip to content

How to Fix Node.js Memory Leak Detection

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Node.js Memory Leak Detection. We cover key concepts, practical examples, and best practices.

The Problem

A Node.js process uses increasing memory over time and eventually crashes with FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - <a href="/programming-languages/javascript/">JavaScript</a> heap out of memory, caused by objects that are no longer needed but remain referenced.

Quick Fix

Step 1: Monitor memory usage

Track memory growth over time:

setInterval(() => {
    const usage = process.memoryUsage();
    console.log({
        rss: `${(usage.rss / 1024 / 1024).toFixed(1)} MB`,
        heapTotal: `${(usage.heapTotal / 1024 / 1024).toFixed(1)} MB`,
        heapUsed: `${(usage.heapUsed / 1024 / 1024).toFixed(1)} MB`
    });
}, 5000);

Step 2: Clean up event listeners

Accumulated event listeners prevent garbage collection:

function processItems(items) {
    items.forEach(item => {
        eventEmitter.on('data', (data) => {
            item.process(data);
        });
    });
}

Each call adds listeners that are never removed. Fix:

function processItems(items) {
    const handler = (data) => {
        items.forEach(item => item.process(data));
    };
    eventEmitter.on('data', handler);
    return () => eventEmitter.removeListener('data', handler);
}

Step 3: Clear timers and intervals

Uncleared intervals keep references alive:

let counter = 0;
setInterval(() => {
    counter++;
    doWork();
}, 1000);

If the interval is no longer needed, store and clear the reference:

const intervalId = setInterval(() => {
    if (!shouldRun) {
        clearInterval(intervalId);
        return;
    }
    doWork();
}, 1000);

Step 4: Avoid global caches without limits

Unbounded caches grow indefinitely:

const cache = {};
function getData(key) {
    if (cache[key]) return cache[key];
    cache[key] = fetchExpensiveData(key);
    return cache[key];
}

Add a size limit:

class LRUCache {
    constructor(maxSize = 100) {
        this.maxSize = maxSize;
        this.cache = new Map();
    }
    get(key) {
        if (!this.cache.has(key)) return undefined;
        const value = this.cache.get(key);
        this.cache.delete(key);
        this.cache.set(key, value);
        return value;
    }
    set(key, value) {
        if (this.cache.size >= this.maxSize) {
            const firstKey = this.cache.keys().next().value;
            this.cache.delete(firstKey);
        }
        this.cache.set(key, value);
    }
}

Step 5: Take and compare heap snapshots

node --inspect app.js

Open chrome://inspect in Chrome, take a heap snapshot, perform operations, take another snapshot, and compare to find retained objects.

Prevention

  • Always clean up event listeners, timers, and subscriptions.
  • Use WeakMap and WeakSet for caches that should not prevent GC.
  • Limit cache sizes with LRU or TTL expiration.
  • Monitor memory in production with tools like clinic.js or heapdump.
  • Use --max-old-space-size to set a heap limit and crash fast instead of swapping.

Common Mistakes with memory leak

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. Mixing let bindings with <- bindings in do notation, producing type errors

These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the most common cause of Node.js memory leaks?

The most common cause is registering event listeners or observers without removing them. Each listener holds a reference to its callback scope, which can reference entire object trees. Other common causes: unbounded caches, closures holding large objects, and dangling references from global variables.

How do I generate a heap dump for analysis?

const heapdump = require('heapdump');
heapdump.writeSnapshot(`/tmp/heap-${Date.now()}.heapsnapshot`);

Then open the .heapsnapshot file in Chrome DevTools Memory tab. For a production-like approach, send a signal: kill -USR2 <pid> with the heapdump module loaded.

Why does my memory usage grow but never decrease?

Node.js does not always return memory to the OS even after garbage collection. The heap may grow but unused pages are kept for future allocations. This is normal. A true leak is indicated by constantly rising heap usage that never plateaus. Monitor heapUsed rather than rss for leak detection.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro