Node.js cluster: why always the last worker process the requests?

47 views
Skip to first unread message

Henry Cool

unread,
May 12, 2016, 8:56:26 AM5/12/16
to nodejs
hello, 

I am using the following codes to study node.js cluster:
const cluster = require('cluster');
const http = require('http');

if (cluster.isMaster) {

  const numCPUs = require('os').cpus().length;
  console.log(numCPUs);
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('online', function(worker) {
        console.log('Worker ' + worker.process.pid + ' is online');
    });

} else {

  // Worker processes have a http server.
  http.Server((req, res) => {
    res.writeHead(200);
for( var i = 0; i < 10000000000; i++ )
{
var j = i+1000;
}
    res.end('process ' + process.pid + ' says hello!');

  }).listen(8000);
}

After starting the node.js server, the console output is as below: 
Worker 19432 is online
Worker 13232 is online
Worker 14972 is online
Worker 8604 is online
Worker 20920 is online
Worker 13640 is online
Worker 19948 is online
Worker 21460 is online

it means that 8 workers have been started. 

I then opened three web browsers to access the http://localhost:8000 at the same time, each request took several minutes due to the loop in my codes. but all results as below: 
process 21460 says hello!

according to node.js documents, the requests should be processed using round-robin order, but why always the last worker process the request? 

Could you please help me on this? thanks for your help. 

Marek Jaskot

unread,
May 13, 2016, 9:52:58 AM5/13/16
to nodejs
Hey,
the code looks ok... What OS you using? If you using Windows... there is problem with distribute requests across cluster.
Reply all
Reply to author
Forward
0 new messages