0
0
NodejsConceptBeginner · 3 min read

Node.js Cluster Module: What It Is and How It Works

The cluster module in Node.js allows you to create multiple worker processes that share the same server port, enabling your app to use multiple CPU cores for better performance. It helps scale Node.js applications by distributing incoming requests across these workers.
⚙️

How It Works

The cluster module works like a team of workers sharing the same job. Imagine a busy restaurant kitchen where one chef tries to cook all meals alone. It gets slow and overwhelmed. Instead, if you have several chefs (workers) working together, each can cook a meal simultaneously, speeding up service.

In Node.js, a single process runs on one CPU core. The cluster module creates multiple child processes (workers), each running the same server code. These workers listen on the same port, and the cluster module distributes incoming requests among them. This way, your app can handle more requests at the same time by using all CPU cores efficiently.

💻

Example

This example shows how to use the cluster module to create a simple HTTP server that runs on multiple CPU cores.

javascript
import cluster from 'cluster';
import http from 'http';
import os from 'os';

const numCPUs = os.cpus().length;

if (cluster.isPrimary) {
  console.log(`Primary process ${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`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP 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
Primary process 12345 is running Worker 12346 started Worker 12347 started Worker 12348 started Worker 12349 started
🎯

When to Use

Use the cluster module when your Node.js app needs to handle many requests at the same time and you want to use all CPU cores to improve performance. It is especially useful for CPU-bound tasks or high-traffic servers.

For example, a web server receiving thousands of requests per second can benefit from clustering to avoid bottlenecks. Also, if your app does heavy computations, clustering helps by running those tasks in parallel processes.

Key Points

  • The cluster module creates multiple worker processes to use all CPU cores.
  • Workers share the same server port and handle requests in parallel.
  • It improves app performance and scalability on multi-core systems.
  • Primary process manages workers and restarts them if they crash.

Key Takeaways

The cluster module enables Node.js apps to use multiple CPU cores by creating worker processes.
It helps improve performance by distributing incoming requests across workers.
Use clustering for high-traffic servers or CPU-intensive tasks.
The primary process manages worker lifecycles and restarts crashed workers.
Workers share the same port and run the same server code in parallel.