Search This Blog


Node Js Cluster

A cluster is a pool of similar workers running under a parent Node process. Workers are spawned using the fork() method of the child_processes module. This means workers can share server handles and use IPC (Inter-process communication) to communicate with the parent Node process.

The master process is in charge of initiating workers and controlling them. You can create an arbitrary number of workers in your master process. Moreover, remember that by default incoming connections are distributed in a round-robin approach among workers (except in Windows).

A cluster module contains several events. Two common events related to the moments of start and termination of workers are the online and the exit events. online is emitted when the worker is forked and sends the online message. exit is emitted when a worker process dies.


  "name": "democluster",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [],
  "author": "",
  "license": "ISC",


var cluster = require('cluster');
if(cluster.isMaster) {
    var numWorkers = require('os').cpus().length;
    console.log('Master cluster setting up ' + numWorkers + ' workers...');
    for(var i = 0; i < numWorkers; i++) {
    cluster.on('fork', function(worker) {
        console.log('worker:' + + " is forked");
    cluster.on('online', function(worker) {
        console.log('worker:' + + " is online");
    cluster.on('listening', function(worker) {
        console.log('worker:' + + " is listening");
    cluster.on('disconnect', function(worker) {
        console.log('worker:' + + " is disconnected");
    cluster.on('exit', function(worker) {
        console.log('worker:' + + " is dead");
        console.log('Starting a new worker');

} else {
    var app = require('express')();
    app.all('/*', function(req, res) {res.send('process ' + + ' says hello!').end();})
    var server = app.listen(8000, function() {
        console.log('Process ' + + ' is listening to all incoming requests');


Master cluster setting up 4 workers...
worker:1 is forked
worker:2 is forked
worker:3 is forked
worker:4 is forked
worker:1 is online
worker:4 is online
worker:2 is online
worker:3 is online
Process 8892 is listening to all incoming requests
worker:1 is listening
Process 16192 is listening to all incoming requests
worker:4 is listening
Process 9412 is listening to all incoming requests
Process 15596 is listening to all incoming requests
worker:3 is listening
worker:2 is listening


No comments: