Node ~ Clustering - rohit120582sharma/Documentation GitHub Wiki

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.

NodeJs has “Cluster” module to utilize multiple cores of CPU but through child processes.

The cluster module provides a way of creating child processes that runs simultaneously and share the same server port.

There is always going to be one parent process called the cluster manager. The cluster manager is not really responsible for handling incoming requests or fetching data from the database or doing anything like that. Instead the cluster manager is responsible for starting up worker processes/instances and monitoring the health of each of these individual instances. So the cluster manager can start instances, it can stop them and can restart them.

const os = require('os');
const cluster = require('cluster');
const express = require('express');

/**
 * Is file being executed in master mode?
 */
if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    // Count the machine's CPU
    const numCPUs = os.cpus().length;

    // Creates a new worker for each CPU, from a master
    // Cause index.js to be executed *again* in child mode
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    // Listen for dying workers
    cluster.on('exit', function(worker, code, signal) {
        console.log(`worker ${worker.process.pid} died`);
        cluster.fork();
    });
} else {
    /**
     * I am a child process and going to act like a server
     */
    console.log(`Worker ${process.pid} started`);

    const PORT = process.env.PORT || 3000;
    const server = express();

    server.get('/', (req, res) => {
        res.status(200).send('Hello world!');
    });
    server.get('/slow', (req, res) => {
        delay(5000);
        res.status(200).send('I am slow!');
    });
    server.get('/fast', (req, res) => {
        res.status(200).send('I am fast!');
    });
    server.listen(PORT, () => {
        console.log(`Server is listening on port ${PORT}`);
    });
}