Warning: MaxListenersExceededWarning: Possible EventEmitter memory leak detected
Quick answer
You've attached more than the default 10 listeners for the same event on one EventEmitter — usually because a listener gets added inside a function that runs repeatedly (a request handler, a retry loop) instead of once at startup. Fix the leak; only raise the limit with `setMaxListeners()` if the count is genuinely expected.
What causes this error
Every EventEmitter (including HTTP requests/responses, streams, and many database clients) defaults to a limit of 10 listeners per event as a leak-detection heuristic. Crossing that limit almost always means a listener is being registered somewhere that runs more than once, rather than the limit being genuinely too low.
The Fix
// Wrong — adds a fresh listener on every call
function handleRequest(req, res) {
someSharedEmitter.on('data', (chunk) => process(chunk)); // leak!
// ...
}
// Fix — attach the listener once, outside the hot path
someSharedEmitter.on('data', (chunk) => process(chunk));
function handleRequest(req, res) {
// ...
}
// If the count really is expected and bounded, raise the limit explicitly
someSharedEmitter.setMaxListeners(20);Common causes / variations
- Registering a listener inside a request handler, loop, or component that re-runs
- Forgetting to call `.off()`/`.removeListener()` when a resource (a socket, a watched file) is torn down
- A shared singleton emitter being listened to by many short-lived consumers that never clean up
Related errors
See also: listen EADDRINUSE, EventEmitter async iteration errors.
Was this fix helpful?
Comments
Loading comments...