a blog for those who code

Wednesday, 30 July 2014

Use of cluster in Nodejs

In this post we will show you whats the use of cluster module in Nodejs. Node provides you with a module called cluster that allows you to delegate work to child processes. This module allows you to write Node programs that itself start many other Node programs and assign work to them for load balancing.

One thing to know that Node program which you have created will manage all the other Node programs but will not take part on each and every transaction. That means if a child Node program is interacting with a database they do it directly but not through the master Node program.

var cluster = require('cluster'); // This is how you can call the cluster module in Nodejs

You can check if the current process is master or worker using the below commands...

cluster.isMaster // returns true if the process is master
cluster.isWorker // returns true if the process is not master i.e. process that is created by master

Lets take an example to see how cluster works. The example taken from nodejs.org

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

if(cluster.isMaster) {
for(var i=0;i<numCPUs;i++) {

cluster.on('exit', function(worker, code, signal) {
   console.log('worker ' + worker.process.pid + ' died');
} else {
http.createServer(function(req, res) {
res.end("Hello World\n");

The process can be either a master or a worker. So at first we are checking that process is master or not using if(cluster.isMaster). cluster.fork() is used to create child process that is identical to master. So in the above example we are creating child processes for all CPUs available, to distribute the work across all of the CPUs.

for(var i=0;i<numCPUs;i++) {

The above code is nothing but creating child process using cluster.fork().

cluster.on('exit', function(worker, code, signal))

When any of the worker process die, the cluster module will emit the 'exit' event. So using the above command we are checking that if any worker process is dead or not, if dead do something.

There are many events attached with the child processes like...

1. fork // when a new worker is forked the cluster module will emit a 'fork' event
2. online // when master process receives an online message (emitted by woker process after it is forked), it will emit this event
3. listening // after calling listen() from a worker, 'listening' event is emitted on cluster
4. disconnect // this is emitted after the worker process is disconnected from the master
5. exit // when any of the worker process die, the cluster module will emit the 'exit' event.

For more Information about cluster you can check the documentation in nodejs.org

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us


Email *

Message *


CC License