Steve Bennett
Steve Bennett

Reputation: 126295

Can this NodeJS cluster master crash?

We have been using forever to launch our Express app, which uses cluster to spawn workers that do all the work. That means the master is only running this code:

if (cluster.isMaster) {

    // ...
    // ... check arguments and do some initial prep 
    // ...

    // Create a worker for each CPU
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }

    // Listen for dying workers
    cluster.on('exit', function (worker) {
        if (!worker.suicide) {
            // Replace the dead worker if not a startup error like port in use.
            console.log('Worker ' + worker.id + ' died. Replacing it.');
            cluster.fork();
        }
    });
    return;
}

Given that the master isn't really doing anything, is there any need to "protect" it with forever, supervisor, etc? Is there any situation in which the master could crash and there would be value in automatically restarting it?

Upvotes: 1

Views: 1477

Answers (1)

zangw
zangw

Reputation: 48436

In my opinion, it is no need to monitor the master process in your cluster, because you won't be able to handle SIGKILL.

Refer to PM2 implementation as below, which is master actually.

var cluster = require('cluster');  
var http    = require('http');  
var os      = require('os');

var numCPUs = os.cpus().length;

if (cluster.isMaster) {  
  // Master:
  // Let's fork as many workers as you have CPU cores

  for (var i = 0; i < numCPUs; ++i) {
    cluster.fork();
  }
} else {
  // Worker:
  // Let's spawn a HTTP server
  // (Workers can share any TCP connection.
  //  In this case its a HTTP server)

  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world");
  }).listen(8080);
}

Upvotes: 1

Related Questions