Why Websocket/ws is connecting socket on single core? (Nodejs/Cluster)

401 Views Asked by At

I am running node js and using cluster module. In child process I am creating a websocket server and on websocket connection I am doing console.log(process.pid) on each websocket connection. I even added a loop in worker thread to slow it down which apparently is the case but it is still assigning the same core to each web socket client. I have written a bash script to run my html file which opens concurrent N connections to test if cluster module is working fine. Is this the issue with cluster module or websocket server?

const os = require('os');
const cluster = require('cluster');

if (cluster.isMaster) {

    for (let i = 0; i < os.cpus().length; i++) {
        cluster.fork();
    }

} else {

    const server = require('http').createServer(app);
    const WebSocket = require('ws');
    let ws_clients = {};
    const wss = new WebSocket.Server({ server: server});    

    wss.on('connection', function connection(ws) {

      let h = 0;

      for (let i = 0; i < 2e10; i++) {
        h++;
      }

      console.log('handled by:', process.pid);

    });

}
1

There are 1 best solutions below

0
On

Your loop just pauses the process main thread that already accepted the connection and currently handles it. If I'm not mistaken connection requests under the hood and by node.js design are handled by separate threads.

If you wish to check the distribution of load on your local machine spawn 4 child processes and have 4 other child processes requesting connections. Then if you check core utilization you will see all of your cores working fine, assuming you have a 8 logical core machine (In windows -> task manager advanced view -> processor -> logical cores). You 'll see a bunch of process pids being logged.