6

I am using websockets/ws on single machine. Its working fine. I want to scale it horizontally on multi-core and on multiple instances. For mutli-core I tried with pm2 and it seems working great.

First Q: Is this the best approach or suitable approach? Here is my testing code with pm2

// ws-server.js
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 3131 });

var pid = process.pid + ''
console.log('process pid: '+ pid)

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    if (message === 'get-pid') {
      ws.send('pid-' + pid)
    } else {
      var matched = pid === message ? 'old friends' : 'strangers' 
      ws.send([pid, message, 'we are ' + matched].join(', '))
    }
  });
  ws.send('first time')
});

and client websocket instances

// ws-cient.js
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:3131/');

var pid
ws.on('open', function open() {
  ws.send('get-pid');
  setInterval(function() {
    ws.send(pid)
  }, 1000)
});

ws.on('message', function incoming(data) {
  if (/^pid/.test(data)) {
    pid = data.match(/\d+/)[0]
    console.log('got pid: ' + pid) 
  } else {
    console.log(data)
  }
});

Just run the server and client with pm2

   $ pm2 start ws-server.js -i 50
   $ pm2 start ws-client.js -i 50

And if you see now the log pm2 logs ws-client each client hits the same connection (at server) every second. So for multi core ws works well with PM2.

Second Q: how to scale with multiple instances? I just saw SocketCluster for horizontal scaling, but can it be used along with websockets/ws as I have already developed code with ws. What could be other solution for horizontal scaling.

Gagan
  • 1,267
  • 3
  • 18
  • 28

2 Answers2

2

Unfortunately, it is going to be hard to scale Websocket across different processes, i would suggest you use this library:

https://github.com/ClusterWS/ClusterWS

The main purpose of this library is to scale WebSocket across processes and machines. Also, good thing is that the library is small and fast.

Dmitrii Goriunov
  • 178
  • 2
  • 17
1

Redis pub/sub can be used. The message from one instance will be pushed to redis and all other instances will be the subscribers. In this way websockets can be scaled without using any third party packages

SB Praveen
  • 49
  • 6