Clustering & Inter Process Communication (IPC) in Node.js

Manish Prasad
js@imaginea
Published in
4 min readJun 11, 2018

--

Introduction

A single instance of Node.js runs in a single thread. This does not allow to take advantage of multi-core systems automatically. However, by leveraging ‘cluster module’ one can take advantage of multiple CPU cores. Clustering improves your app’s performance and lets you achieve zero downtime (hot) deployments easily. Also keep in mind that number of workers that can be created is not limited by the number of CPU cores of the machine. Clustering is a must-have for any Node.js production app and there is no reason not to use it.

Clustering

'use strict';const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log('Master process is running with pid:', process.pid);
for (let i = 0; i < numCPUs; ++i) {
cluster.fork();
}
} else {
console.log('Worker started with pid:', process.pid);
}

Run the above code

$ node cluster.js
Master process is running with pid: 21559
Worker started with pid: 21570
Worker started with pid: 21571
Worker started with pid: 21565
Worker started with pid: 21577

--

--

Manish Prasad
js@imaginea

In character, in manner, in style, in all things, the supreme excellence is Simplicity..! | IIT Roorkee