How to Use All CPU Cores With cluster
Run one Node.js HTTP server per CPU core with node:cluster: fork workers, share a port, restart crashed workers and know when a process manager is simpler.

A Node.js process runs your JavaScript on one thread, so on a machine with eight cores a single server process leaves seven of them idle. The simplest way to use the rest is to run several copies of the server and let them share one port. The built-in [node:cluster](https://nodejs.org/api/cluster.html) module does that: one primary process forks a worker per core, and incoming connections are spread across the workers. This post shows how to fork workers, what the primary and workers each do, how connections are distributed, how to restart a worker that crashes, how to shut down cleanly and when a process manager or container platform is the better answer. The samples use ES modules on Node.js 26.
The idea
A cluster has two kinds of process.
The primary process does not serve requests. It forks the workers, watches them and restarts them.
The workers are full Node.js processes, each with its own memory and event loop, running the same server code. They all listen on the same port.
Because each worker is a separate process, they do not share variables. A counter in memory is a separate counter in each worker. That is the main thing to design around, and the section on state below covers it.
The module's older names appear in a lot of existing code: cluster.isMaster and cluster.isPrimary mean the same thing, and isPrimary is the current spelling. Use that one.
A minimal clustered server
One file serves as both primary and worker. It checks cluster.isPrimary to decide which role it plays.
import cluster from "node:cluster";
import http from "node:http";
import { availableParallelism } from "node:os";
import process from "node:process";
if (cluster.isPrimary) {
const count = availableParallelism();
console.log(`primary ${process.pid} starting ${count} workers`);
for (let i = 0; i < count; i++) {
cluster.fork();
}
} else {
http
.createServer((req, res) => {
res.end(`handled by worker ${cluster.worker.id} (pid ${process.pid})\n`);
})
.listen(3000, () => {
console.log(`worker ${cluster.worker.id} listening on 3000`);
});
}On a four-core machine, starting it prints something like this. The pids and the order of the worker lines differ on every run.
primary 51200 starting 4 workers
worker 1 listening on 3000
worker 3 listening on 3000
worker 2 listening on 3000
worker 4 listening on 3000cluster.fork() starts a new copy of the same script, and in that copy cluster.isPrimary is false, so it takes the else branch and starts the server. All four workers call listen(3000), and that works without an "address in use" error because the cluster module arranges for the primary to own the listening socket and hand connections to the workers. os.availableParallelism() is a better count than os.cpus().length, because it reflects the number of threads the process may actually use, including limits set by the container. It was added in Node.js 18.14.
Send a few requests and you see different workers answer:
curl http://localhost:3000/
curl http://localhost:3000/
curl http://localhost:3000/handled by worker 2 (pid 51203)
handled by worker 4 (pid 51205)
handled by worker 1 (pid 51201)The worker ids and pids are examples. Each request lands on whichever worker the distribution picks next.
How connections are distributed
The cluster documentation describes two approaches. On every platform except Windows, the default is round-robin: the primary accepts each connection and passes it to the next worker in turn. On Windows the default is to hand the listening socket to the workers and let the operating system decide, which can distribute very unevenly, with a few workers taking most of the connections.
You can choose explicitly before forking:
import cluster from "node:cluster";
cluster.schedulingPolicy = cluster.SCHED_RR;
console.log(cluster.schedulingPolicy === cluster.SCHED_RR);truecluster.SCHED_RR is round-robin and cluster.SCHED_NONE leaves it to the operating system. The setting must be applied before the first fork(). The NODE_CLUSTER_SCHED_POLICY environment variable, set to rr or none, does the same without code.
Round-robin balances the number of connections, not the amount of work. A worker that happens to receive several long-running requests will be busier than the rest. For HTTP with keep-alive, a connection stays on one worker for all its requests, so a client that holds a connection open sends all its traffic there.
Restart a worker that dies
A crash in one worker does not take the others down, but it does leave you with fewer workers. The primary should notice and replace it. The exit event on the cluster object fires whenever a worker ends.
import cluster from "node:cluster";
import http from "node:http";
import { availableParallelism } from "node:os";
if (cluster.isPrimary) {
for (let i = 0; i < availableParallelism(); i++) cluster.fork();
cluster.on("exit", (worker, code, signal) => {
console.log(`worker ${worker.id} died (${signal ?? code}), restarting`);
cluster.fork();
});
} else {
http
.createServer((req, res) => {
if (req.url === "/crash") {
throw new Error("simulated bug");
}
res.end("ok\n");
})
.listen(3000);
}Requesting /crash makes the handler throw. In a plain http server an uncaught exception in a request handler ends the process, so that worker exits with code 1 and the primary logs:
worker 2 died (1), restartingA new worker, with a new id, takes its place. The other workers kept serving throughout. This is the main practical benefit of a cluster beyond raw speed: a single bad request kills one worker, not the whole service.
Do not restart blindly in a tight loop. If a worker crashes on startup, for example because the port is taken or a config file is missing, the primary forks again, which crashes again, and the machine spins. Add a short delay and a cap.
import cluster from "node:cluster";
let restarts = 0;
cluster.on("exit", (worker) => {
restarts += 1;
if (restarts > 10) {
console.error("too many restarts, giving up");
process.exit(1);
}
setTimeout(() => cluster.fork(), 1000);
});This sample caps the total number of restarts and waits one second between them. A real supervisor would count restarts within a time window, so a long-lived service is not penalised for a crash a month ago.
Shut down cleanly
On a deploy the primary should stop the workers politely: stop accepting new connections, finish the requests in flight, then exit. worker.disconnect() does the first two steps. After it, the worker closes its servers and its IPC channel, and exits when its event loop is empty.
import cluster from "node:cluster";
if (cluster.isPrimary) {
process.on("SIGTERM", () => {
console.log("SIGTERM: asking workers to finish");
for (const worker of Object.values(cluster.workers)) {
worker.disconnect();
}
});
}cluster.workers is an object keyed by worker id, so Object.values() gives the list. When shutting down on purpose you must stop the exit handler from forking replacements, or it will undo your shutdown. Set a flag such as shuttingDown = true and check it in the handler. Combine this with a timeout that kills workers that do not finish in a reasonable time. The post on graceful shutdown in Node.js covers what a worker should do in its own signal handler.
Talking between primary and workers
Workers and the primary are connected by an IPC channel. process.send() in a worker and worker.send() in the primary pass JSON-like messages.
import cluster from "node:cluster";
if (cluster.isPrimary) {
const worker = cluster.fork();
worker.on("message", (msg) => {
console.log("primary received:", msg);
worker.send({ type: "ack", id: msg.id });
});
} else {
process.on("message", (msg) => {
console.log(`worker ${cluster.worker.id} received:`, msg);
process.exit(0);
});
process.send({ type: "ready", id: 1 });
}primary received: { type: 'ready', id: 1 }
worker 1 received: { type: 'ack', id: 1 }This is enough to collect metrics from workers or to tell them to reload configuration. It is not a way to share application state, because each message is serialised and copied.
State is per worker
Every worker has its own heap. These things therefore do not behave as they would in a single process:
In-memory caches are duplicated, and each worker has a different set of entries. A cache hit on worker 1 does not help worker 2.
Counters and rate limits held in a variable count only the requests that one worker saw. Move them to Redis or another shared store.
WebSocket connections and sessions held in memory are tied to one worker. A user whose next request lands on a different worker loses the session unless it is stored outside the process.
Scheduled jobs run in every worker that registers them. Run a schedule in the primary or in a single dedicated process.
If your app keeps important state in memory, clustering changes its behaviour, and you should fix that first. A stateless service scales across workers without change.
Cluster, worker threads and a process manager
cluster is often confused with worker threads, and they solve different problems. A cluster runs several whole server processes to serve more connections in parallel. Worker threads run pieces of computation on other threads inside one process, which suits CPU-heavy tasks inside a request. Use cluster for throughput of many ordinary requests, and worker threads, covered in How to Use Worker Threads for CPU-Bound Work, for the heavy computation.
In many deployments you do not need cluster at all:
PM2 has a cluster mode that wraps this module and adds restart policies, log handling and reloads.
systemd can run several instances of a unit on different ports behind a reverse proxy.
Containers usually run one process per container and scale by adding containers, often one per core or fewer, and an orchestrator restarts the failed ones. Running
clusterinside a container that is already CPU-limited can create more workers than the limit allows, so check whatavailableParallelism()reports there.
Choose cluster when you want one self-contained process tree with no extra tooling, and a process manager or orchestrator when you already have one.


