0
0
NodejsHow-ToBeginner · 4 min read

How to Use Cluster in Node.js for Better Performance

Use the cluster module in Node.js to create multiple worker processes that share the same server port, allowing your app to use multiple CPU cores. The master process forks workers, and each worker handles incoming requests independently. This improves performance and reliability by distributing load across cores.
📐

Syntax

The cluster module provides a way to create child processes (workers) that run simultaneously and share the same server port. The main parts are:

  • cluster.isMaster: Checks if the current process is the master.
  • cluster.fork(): Creates a new worker process.
  • cluster.isWorker: Checks if the current process is a worker.
  • Workers run the server code to handle requests.
nodejs
import cluster from 'cluster';
import os from 'os';

if (cluster.isMaster) {
  const cpuCount = os.cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }
  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork(); // restart worker
  });
} else {
  // Worker process code here
  // e.g., create HTTP server
}
💻

Example

This example shows a simple HTTP server using the cluster module. The master process forks workers equal to the number of CPU cores. Each worker runs the server and handles requests independently.

nodejs
import cluster from 'cluster';
import http from 'http';
import os from 'os';

const numCPUs = os.cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died. Restarting...`);
    cluster.fork();
  });
} else {
  // Workers share the TCP connection in this server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from worker ${process.pid}\n`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
Output
Master 12345 is running Worker 12346 started Worker 12347 started Worker 12348 started Worker 12349 started
⚠️

Common Pitfalls

Common mistakes when using cluster include:

  • Not handling worker exits and not restarting them, which can cause downtime.
  • Running server code in the master process instead of workers.
  • Sharing state or variables between workers incorrectly, since each worker is a separate process.
  • Not using cluster.isMaster and cluster.isWorker checks properly.
nodejs
/* Wrong: Running server in master process */
import cluster from 'cluster';
import http from 'http';

if (cluster.isMaster) {
  http.createServer((req, res) => {
    res.end('This should be in worker, not master');
  }).listen(8000);
} else {
  // workers do nothing
}

/* Right: Server runs only in workers */
if (cluster.isMaster) {
  cluster.fork();
} else {
  http.createServer((req, res) => {
    res.end('Correct worker server');
  }).listen(8000);
}
📊

Quick Reference

Tips for using cluster in Node.js:

  • Use os.cpus().length to fork one worker per CPU core.
  • Always restart workers on exit to keep your app running smoothly.
  • Keep master process logic separate from worker logic.
  • Do not share memory or variables directly between workers; use IPC if needed.

Key Takeaways

Use the cluster module to fork worker processes that share the same server port for better CPU utilization.
Master process manages workers and restarts them if they exit unexpectedly.
Run server code only inside worker processes, not in the master.
Avoid sharing state directly between workers; treat each as an independent process.
Use os.cpus().length to decide how many workers to fork for optimal performance.