Restarting Workers in a Nodejs Cluster

• 2 min read

We upgraded ForkJoy to Node.js v0.8 and decided to use the newly rewritten Cluster module. Cluster allows a parent Node process to manage multiple worker processes on a single port to better take advantage of multi-core machines.

Before this change, Forkjoy was using Forever to restart the main process if it died. When using Cluster, Forever does not know about the worker processes (only the parent process) and therefore will not restart workers if they fail. Eventually all the workers die off leaving nothing to handle server requests. This is bad!

Luckily, starting a new process when one dies only takes a few lines of code. This is the snippet we’re currently using.

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers. One per CPU for maximum effectiveness
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(deadWorker, code, signal) {
    // Restart the worker
    var worker = cluster.fork();

    // Note the process IDs
    var newPID = worker.process.pid;
    var oldPID = deadWorker.process.pid;

    // Log the event
    console.log('worker '+oldPID+' died.');
    console.log('worker '+newPID+' born.');
  });
} else {
  // All the regular app code goes here
}

That’s all there is to it.

If you enjoyed this tutorial, please consider sponsoring my work on GitHub 🤗

Be the first to cheers
Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 8 min read
🚜 A Simple Web Scraper in Go
Read Post »
• 2 min read
👨🏼‍💻 Going Indie, Again
Read Post »