Skip to content

How to Fix Node.js EventEmitter Memory Leak Warning

DodaTech 2 min read

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

The Problem

Node.js prints (node) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit to stderr. This warning triggers when more than 10 listeners are attached to a single event on any EventEmitter instance. It is a warning, not an error — the application continues running — but it almost always indicates a real memory leak where event listeners are being added repeatedly without being removed.

Quick Fix

1. Identify where the listeners are being added

// Run this to inspect your emitter
const emitter = require('./emitter');

console.log('Event names:', emitter.eventNames());
console.log('Listener count for data:', emitter.listenerCount('data'));
console.log('Listeners:', emitter.listeners('data'));

2. Remove listeners properly after use

const EventEmitter = require('events');
const emitter = new EventEmitter();

function handleData(data) {
    console.log('Processing:', data);
}

// Always save the reference so you can remove it
emitter.on('data', handleData);

// Later, when done:
emitter.removeListener('data', handleData);

// Or use once() for one-shot events
emitter.once('shutdown', () => {
    console.log('Cleaning up resources...');
});

3. Use a limit pattern to cap listeners

class SafeEmitter extends EventEmitter {
    on(event, listener) {
        if (this.listenerCount(event) >= 20) {
            console.warn(`Max listeners (20) reached for event: ${event}`);
            return this;
        }
        return super.on(event, listener);
    }
}

const safeEmitter = new SafeEmitter();
// Per-instance
const emitter = new EventEmitter();
emitter.setMaxListeners(50);

// Global default (affects all emitters)
require('events').EventEmitter.defaultMaxListeners = 50;

5. Use the --trace-warnings flag to find the source

node --trace-warnings app.js

Expected output:

(node:12345) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
    at Socket._onTimeout (_http_client.js:122:45)
    at listOnTimeout (internal/timers.js:549:17)
    at Timer.processTimers (internal/timers.js:492:7)

The stack trace pinpoints exactly where listeners are being added.

6. Verify the fix

node --trace-warnings app.js

Expected output (no warning):

Server listening on port 3000
# No MaxListenersExceededWarning

Check Node.js and npm Versions

node --version
# v18.17.0
npm --version
# 9.6.7

Verify your runtime versions before troubleshooting module resolution or compatibility issues. Outdated versions of Node.js or npm are a common source of mysterious errors. Use nvm to manage multiple Node versions side by side.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Prevention

  • Always call removeListener (or emitter.off) when adding temporary event handlers
  • Use emitter.once() for events that should fire only one time (like close, end)
  • Avoid anonymous arrow functions as listeners — they cannot be removed because you have no reference to them
  • Use a registry pattern that tracks all active listeners and cleans them up on shutdown
  • Set NODE_OPTIONS="--trace-warnings" in development to debug listener leaks early before they reach production

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro