skip to content

In Node.js, what does a MaxListenersExceededWarning ('Possible EventEmitter memory leak detected') mean, and how should you respond to it?

level: juniorimportance: should knowfreq 45%

answer

  1. a warning, not an error
  2. more than ten per event
  3. a listener added on every request
  4. find the caller with --trace-warnings

basics

~20 s

Node prints it when one EventEmitter holds more than 10 listeners for a single event, a common sign that code adds a listener per request and never removes it. Find that code and remove the listener instead of raising the limit.

solid answer

~40 s

Every `EventEmitter` has a warning threshold, `events.defaultMaxListeners`, which is 10 listeners per event name. It is not a hard limit: the eleventh listener is still added, and Node emits a `MaxListenersExceededWarning` through `process.emitWarning()`, normally only once for that event on that emitter. The usual cause is a long-lived emitter, such as `process`, a pooled socket or a shared client, getting `.on()` inside a request handler, so every request leaves a closure behind along with everything it captures. Run with `--trace-warnings` to get the stack of the call that added the listener, or read `warning.emitter`, `warning.type` and `warning.count` in `process.on('warning')`. Fix it by removing the listener with `emitter.off()`, switching to `once()`, or registering it once at startup. Raise the limit with `emitter.setMaxListeners(n)` only when many listeners are genuinely part of the design.

code

javascript · 18 lines
javascript
import { EventEmitter } from 'node:events';
import { Buffer } from 'node:buffer';

const bus = new EventEmitter(); // lives as long as the process

function handleRequest(id) {
  const body = Buffer.alloc(1024 * 1024); // per-request state
  // Leak: one listener per request, never removed
  bus.on('shutdown', () => console.log(id, body.length));
}

process.on('warning', (w) => {
  if (w.name === 'MaxListenersExceededWarning') {
    console.error(w.type, w.count); // shutdown 11
  }
});

for (let i = 0; i < 11; i++) handleRequest(i);

go deeper

for a junior

Recall that the default is 10 listeners per event, that the eleventh is still added, and that the warning names the emitter and the event so you can find the code.

for a middle

Explain why a listener retains its closure, and show the fix with emitter.off() using the same function reference, or once() for a one-shot wait.

for a senior

Show how you trace the call site with --trace-warnings or the warning's emitter, type and count, and why the count keeps growing silently after the first warning.

for a principal

Argue when a team may raise a limit at all: only per instance, for a count bounded by design, never globally through events.defaultMaxListeners to quiet noisy logs.

## What the warning is An **`EventEmitter`** in Node keeps, for each event name, an array of listener functions. To catch a common class of leak early, Node compares the length of that array with a threshold every time a listener is added. The threshold comes from **`events.defaultMaxListeners`**, which is `10`, unless the instance overrides it with `emitter.setMaxListeners(n)`. When an eleventh listener is added for the same event, Node does **not** refuse it. The listener is added as normal, and Node builds a warning whose `name` is `'MaxListenersExceededWarning'` and whose message reads like `Possible EventEmitter memory leak detected. 11 shutdown listeners added to [EventEmitter]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit`. It is delivered through `process.emitWarning()`, so it lands on stderr by default and on any `process.on('warning')` handler. Two details surprise people: - The warning normally fires **only once per event name on an emitter**. Node marks that listener array as warned, so the count can keep climbing to thousands without another line. - It is a **heuristic**, not proof. Some designs legitimately attach many listeners to one event. ## Why it usually means a leak A listener is a function, and a function keeps its **closure** alive: the variables it captured, and everything they reference. An emitter that lives as long as the process (`process` itself, a module-level event bus, a pooled connection, a shared client) holds a strong reference to every listener in its arrays. So the chain is: 1. A request handler calls `longLived.on('event', () => { ... })`. 2. The arrow function captures the request, the response, a parsed body or a buffer. 3. The request finishes, but the emitter still references the listener, so none of that can be collected. 4. Memory and the listener count grow with traffic, and each emit runs every stale listener, so CPU grows too. That is why the warning appears in this branch's material on heap growth: it is often the first visible symptom, hours before the heap limit. ## Finding the code that adds the listener - Restart with **`--trace-warnings`**. Node then prints the stack trace with the warning, which points at the `.on()` or `.addListener()` call. - Or subscribe with `process.on('warning', (w) => { ... })` and read the extra properties the warning carries: **`w.emitter`** (the instance), **`w.type`** (the event name) and **`w.count`** (how many listeners it had). - After the first warning, watch growth with `emitter.listenerCount(eventName)`, because the warning will not repeat. - In a heap snapshot, a long array of closures retained from one emitter's event table is the same finding seen from the memory side. ## Fixing it | Response | Effect | |---|---| | Remove the listener with `emitter.off()` when the work ends | Fixes the leak: the closure becomes collectable | | Use `emitter.once()` for one-shot waits | Fixes it when the event really fires; still leaks if it never does | | Register one listener at startup and route inside it | Fixes it and keeps the count constant | | `emitter.setMaxListeners(0)` or `Infinity` | Silences the warning; the leak continues | | Raise `events.defaultMaxListeners` | Silences it for every emitter in the process, including ones created earlier | Keep a reference to the function you add, because `off()` needs the same function object: ```js const onShutdown = () => res.destroy(); bus.on('shutdown', onShutdown); res.on('close', () => bus.off('shutdown', onShutdown)); ``` Raising the limit with `emitter.setMaxListeners(n)` on one instance is right only when the count is bounded by design, for example one listener per configured plugin. Pair it with a reason in a comment, not with a guess at peak traffic. ## Edge cases worth knowing - **`AbortSignal`** is an `EventTarget`, and `events.defaultMaxListeners` has no effect on it: by default it does not warn at all. Adding an `'abort'` listener per operation to one long-lived signal leaks silently. Use `{ once: true }`, remove the listener when the operation completes, or set a per-signal threshold with `events.setMaxListeners(n, signal)`. - Silencing all warnings with `--no-warnings` hides this one together with deprecations, which removes a diagnostic rather than a problem. - The same pattern with `setInterval` or a timer that is never cleared keeps its callback, and its closure, alive in exactly the same way; the warning simply does not exist for timers. The response, then, is diagnostic first: find the call site, decide whether the count should be bounded, and remove listeners at the end of the unit of work that added them.

  • Why does the warning appear only once even though the listener count keeps growing?
    Node marks that event's listener array as warned after the first warning, so later additions to the same emitter and event are silent. A leak that keeps going after the first line is invisible unless you measure it, for example with `emitter.listenerCount(eventName)` exported as a metric, or by finding the growing listener array in a heap snapshot.
  • Does the same warning protect listeners added to an AbortSignal?
    No. `events.defaultMaxListeners` has no effect on `AbortSignal` instances, and by default they do not warn. Code that adds an `'abort'` listener per operation to one long-lived signal can leak without any message. Pass `{ once: true }`, remove the listener when the operation completes, or opt in to a threshold with `events.setMaxListeners(n, signal)`.

  • Node refuses to add the eleventh listener and throws an error.
  • Calling setMaxListeners(0) fixes the leak the warning reported.
  • The warning means the process is about to run out of heap.
  • Listeners on a shared emitter are released when the request ends.
  • Raising events.defaultMaxListeners is a safe, process-wide fix.