nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.7k stars 7.63k forks source link

Socket gateway using ws accumulates connections (possible memory leak?) #10948

Closed jblyberg closed 1 year ago

jblyberg commented 1 year ago

Is there an existing issue for this?

Current behavior

When using ws as a socket server, disconnected sessions seem to accumulate and the listeners are not flushed after client disconnects, resulting in MaxListenersExceededWarning errors:

(node:66205) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added to [WebSocketServer]. Use emitter.setMaxListeners() to increase limit

Minimum reproduction code

https://stackblitz.com/edit/nestjs-typescript-starter-zu55y9

Steps to reproduce

  1. Run the reproduction code
  2. Use postman (or whatever) to repeatedly connect and disconnect to the socket server
  3. Observe console output. It should be something like this:
GW: Client disconnect
GW: Client connect
GW: Client disconnect
GW: Client connect
GW: Client connect
GW: Client disconnect
GW: Client connect
GW: Client connect
GW: Client connect
GW: Client disconnect
GW: Client connect
GW: Client connect
GW: Client connect
GW: Client connect
... etc ...
(node:66205) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added to [WebSocketServer]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
... etc ...

Expected behavior

  1. Client connect and disconnect should be the same
  2. No errors

Package

Other package

No response

NestJS version

9.2.1

Packages versions

    "@nestjs/common": "^9.2.1",
    "@nestjs/core": "^9.2.1",
    "@nestjs/platform-express": "^9.2.1",
    "@nestjs/platform-ws": "^9.2.1",
    "@nestjs/websockets": "^9.2.1",

Node.js version

19.3.0

In which operating systems have you tested?

Other

No response

SirReiva commented 1 year ago

image handleConnection method already caught socket connection, you dont need attach listener again in each socket connection and this listener you nerver remove manually

kamilmysliwiec commented 1 year ago

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.