Node.js Cluster Module: What It Is and How It Works
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.
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`); }
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
clustermodule 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.