|$ curl https://forge-ai.dev/api/markdown?path=docs/nodejs/cluster
$cat docs/cluster.md
updated Recently·18 min read·published
Cluster
Introduction
Node.js runs on a single thread by default. The cluster module lets you fork multiple worker processes that share the same server port, allowing your application to use all available CPU cores.
Basic Example
cluster.js
JavaScript
| 1 | const cluster = require("cluster"); |
| 2 | const http = require("http"); |
| 3 | const os = require("os"); |
| 4 | |
| 5 | if (cluster.isPrimary) { |
| 6 | const numCPUs = os.availableParallelism(); |
| 7 | console.log(`Primary ${process.pid} is running`); |
| 8 | |
| 9 | for (let i = 0; i < numCPUs; i++) { |
| 10 | cluster.fork(); |
| 11 | } |
| 12 | |
| 13 | cluster.on("exit", (worker) => { |
| 14 | console.log(`Worker ${worker.process.pid} died`); |
| 15 | cluster.fork(); |
| 16 | }); |
| 17 | } else { |
| 18 | http.createServer((req, res) => { |
| 19 | res.writeHead(200); |
| 20 | res.end(`Hello from worker ${process.pid}\n`); |
| 21 | }).listen(3000); |
| 22 | |
| 23 | console.log(`Worker ${process.pid} started`); |
| 24 | } |
How It Works
The primary process does not handle requests. It spawns worker processes and manages their lifecycle. On Linux, incoming connections are distributed among workers by the operating system using a round-robin strategy by default.
Considerations
- Each worker has its own memory space; do not rely on in-memory state shared between requests unless sticky sessions are used.
- Use a process manager like PM2 or a container orchestrator for production instead of hand-rolling cluster code.
- For CPU-bound tasks, consider worker threads instead of scaling processes.
ℹ
info
Modern deployments often use containers (Docker/Kubernetes) where each container runs a single Node.js process, and scaling is handled at the orchestrator level.