cluster — Multi-core
Using all CPU cores in Node.js — the cluster module, worker processes, load balancing, and when to use cluster vs worker_threads.
What it is, in plain English: Node.js runs on a single thread by default — it can only use one CPU core. The cluster module lets you spawn multiple worker processes that all share the same port. The primary process manages the workers; workers handle incoming requests. The OS distributes connections across workers (round-robin on Linux/Mac). For CPU-bound work, use worker_threads. For I/O-bound servers, use cluster.
Using all CPU cores
Node.js uses one CPU core by default. If your server has 8 cores, 7 are idle. The cluster module creates multiple worker processes, each handling requests independently. The OS distributes incoming connections between them.
import cluster from "cluster";
import { cpus } from "os";
import { createServer } from "http";
const numCPUs = cpus().length; // 4, 8, 16 — depends on hardware
if (cluster.isPrimary) {
// This code runs in the primary (manager) process:
console.log(`Forking ${numCPUs} workers`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork(); // spawn one worker per CPU
}
cluster.on("exit", (worker, code) => {
console.log(`Worker ${worker.process.pid} died. Restarting...`);
cluster.fork(); // auto-restart crashed workers
});
} else {
// This code runs in EACH worker process:
createServer((req, res) => {
res.end(`Hello from worker ${process.pid}!`);
}).listen(3000);
// All workers share port 3000 — OS routes connections between them
}Cluster vs worker_threads
cluster
worker_threads
Isolation
Separate processes
Same process
Memory
Separate heaps
Shared memory possible
Crash impact
One worker only
Whole process
Port sharing
Yes — OS distributes
No
Best for
HTTP servers, I/O-bound
CPU-heavy computation
Try It Yourself
Official Sources
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.