Last updated on November 21, 2022
You can increase the performance of your Express.js application by using clusters. Cluster is a native core library from node.js which allows you to implement a network of multiple processes. Usually, an node js process will only use one core process meaning we are not using all available CPU power, using clusters we can spin up multiple processes.
In node.js you can create an N-1 process to work with parallel processing, where the master process works on balancing the load among the other child salve process. Child processes communicate with the master process via IPC(Inter-Process Communication).
A cluster basically runs several instances of one single application, usually one instance in each core of the CPU, which distributes the overall task among many instances and shares the load. A cluster allows multiple processes to listen on the same master port, which means the master process receives the request and distributes it to child processes. Clusters add additional bandwidth to the application.
We can get the following benefits with clustering, better performance, lower cost, Greater reliability, and easy maintenance.
Start node server in cluster mode
Save the below code in the cluster.js file and update your server file(server.js).
const cluster = require('cluster');
const os = require('os');
// get cpu info
const CPUS = os.cpus();
if (cluster.isMaster) {
// create a worker for each cpu
CPUS.forEach(() => cluster.fork());
cluster.on("listening", worker => {
console.log("Cluster %d connected", worker.process.pid);
});
cluster.on("disconnect", worker => {
console.log("Cluster %d disconnected", worker.process.pid);
});
cluster.on("exit", worker => {
console.log("Cluster %d is dead", worker.process.pid);
// Ensure starts of a new cluster if an old one dies
cluster.fork();
});
} else {
require("./server.js"); // your server.js or index.js file.
}
Sample express server
const express = require('express');
const app = express();
app.get('/',function(req,res){
res.send('hello world');
});
app.listen(8080,function(){
console.log('project started');
});
You can run your cluster server and normal server with node cluster.js, and node server.js respectively.
My server output –