CodePark/ questions / EventEmitter
START PRACTICINGPRACTICE
Backend question · Node.js › EventEmitter

What does MaxListenersExceededWarning: Possible EventEmitter memory leak detected mean, and how should you respond?

It means one event on one emitter has more than 10 listeners. Usually this is a real memory leak, so find the cause before you change the limit.

By default, an emitter warns when you add more than 10 listeners for the same event. It is only a warning. Node still adds the listeners. But it usually points to a real leak. The typical cause is code that calls on again and again, for example on every request or every reconnect, and never removes the listener. Each listener keeps its closure alive. A closure is the function plus the variables it can still reach. So memory grows forever, and each emit costs more CPU because it calls more listeners.

First, find the cause. Run Node with --trace-warnings. This prints the stack trace of the place that added the extra listener.

Then fix the listener's lifecycle. You can:

  • use once, so the listener removes itself after one call
  • call off when you no longer need the listener
  • register the listener only one time
  • use an AbortSignal to remove it

Raise the limit with emitter.setMaxListeners(n) only when you really expect many listeners.

  • The default limit is 10 listeners per event.
  • It is only a warning, but it often shows a real leak.
  • The typical cause is adding a listener on every request or reconnect.
  • Find the cause with --trace-warnings, then fix it with once, off or an AbortSignal.
  • Use setMaxListeners only when many listeners are really expected.