Search code examples
node.jswebsocketsocket.iocluster-computingpm2

Does PM2 Cluster Mode handle WebSockets in one single process?


I'm building a simple chat application using Node.js and Socket.io. Started using PM2 to scale my application on different instances (currently for testing purposes I'm using 4 instances on a Windows OS).

During testing, I've noticed that all the websocket traffic is going thru the same instance ID, but if I force a WebSocket connection to another instance then all the messages I send to that one can't be viewed in other existing WebSocket connections, as they run on different instances.

Let's say I want to broadcast a chat message to all connected users, using PM2 Cluster Mode. How can I achieve that?

I have read this issue https://github.com/Unitech/pm2/issues/1510 pointing that as long I'm using only websocket transport in Socket.io there shouldn't be any problems. How does this work? Does PM2 handle all WebSocket connections internally to always point to the same process?


Solution

  • In order to use socket.io in cluster mode you need to use socket.io-redis as your socket adapter, so all users get back to their previous server each time they attempt to make a request, otherwise, they'll get 400 errors.