0
0
Node.jsframework~5 mins

Master and worker processes in Node.js

Choose your learning style9 modes available
Introduction

Master and worker processes help your Node.js app use multiple CPU cores. This makes your app faster and able to handle more tasks at the same time.

When your app needs to handle many users or requests at once.
When you want to make your app faster by using all CPU cores.
When you want to keep your app running even if one part crashes.
When you want to split heavy tasks into smaller parts to run in parallel.
Syntax
Node.js
import cluster from 'node:cluster';
import { cpus } from 'node:os';

if (cluster.isPrimary) {
  // Master process code
  const cpuCount = cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork(); // Create worker processes
  }

  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died. Restarting...`);
    cluster.fork();
  });
} else {
  // Worker process code
  // Your server or task code here
}

The cluster.isPrimary property tells if the current process is the master.

Use cluster.fork() to create worker processes that run the same code.

Examples
Simple example: master creates one worker that prints a message.
Node.js
if (cluster.isPrimary) {
  cluster.fork();
} else {
  console.log('Worker running');
}
Create one worker per CPU core to use all cores.
Node.js
const cpuCount = cpus().length;
for (let i = 0; i < cpuCount; i++) {
  cluster.fork();
}
Restart a worker if it crashes to keep the app running smoothly.
Node.js
cluster.on('exit', (worker) => {
  console.log(`Worker ${worker.process.pid} died.`);
  cluster.fork();
});
Sample Program

This program uses the cluster module to create one worker per CPU core. Each worker runs a simple HTTP server that replies with its process ID. The master process manages workers and restarts any that crash.

Node.js
import cluster from 'node:cluster';
import http from 'node:http';
import { cpus } from 'node:os';

if (cluster.isPrimary) {
  const cpuCount = cpus().length;
  console.log(`Master ${process.pid} is running`);

  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died. Restarting...`);
    cluster.fork();
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from worker ${process.pid}\n`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
OutputSuccess
Important Notes

Each worker runs the same code but has its own process ID.

Workers share the same server port, so the OS balances incoming requests between them.

Use cluster to improve performance on multi-core machines.

Summary

Master process creates and manages worker processes.

Workers run the app code and handle tasks or requests.

Cluster module helps use all CPU cores for better performance.