What does Node's cluster module do, and how does one entry script know whether it is running as the primary or a worker?
answer
- same script, two roles
- child_process.fork under the hood
- an environment variable decides
- cluster.isPrimary vs cluster.isWorker
basics
~20 sNode's cluster module runs one script as a primary that calls cluster.fork() and as worker processes that share its server ports. cluster.isPrimary, derived from an environment variable the primary sets for each worker, tells the script which role it has.
solid answer
~40 s`node:cluster` lets one Node program use several cores by running several processes. The primary calls `cluster.fork()`, which uses `child_process.fork()` to start the same entry script again (`cluster.settings.exec` defaults to `process.argv[1]`) with an IPC channel and a `NODE_UNIQUE_ID` environment variable. That variable is how `cluster.isPrimary` and `cluster.isWorker` get their values, so the script branches on them: the primary forks and supervises, workers create their servers and call `listen()`, and the primary arranges for them to share the port. Each worker is a full process with its own V8 heap and event loop, so nothing in memory is shared. Node does not size or maintain the pool: the primary picks a count, often `os.availableParallelism()`, and forks replacements itself.
code
javascript · 14 linesimport cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
import process from 'node:process';
if (cluster.isPrimary) {
console.log(`primary ${process.pid}`);
for (let i = 0; i < availableParallelism(); i++) cluster.fork();
} else {
http
.createServer((req, res) => res.end(`worker ${cluster.worker.id}\n`))
.listen(8000);
console.log(`worker ${cluster.worker.id} is pid ${process.pid}`);
}go deeper
Recall the two roles, that cluster.fork() starts the same script again, and that cluster.isPrimary is how the script branches between them.
Explain that workers are child_process.fork() processes with their own heap and event loop, and that the primary owns the shared port.
Point out what Node leaves to you: worker count, respawning on exit and retiring workers are all primary code you write and test.
Frame cluster as a per-host supervisor with a single primary, and say when a platform's process supervisor or more replicas would own that job instead.
## Why the cluster module exists A Node.js process runs your JavaScript on **one main thread** with one event loop. However many cores the machine has, that main thread keeps at most one of them busy with your JavaScript. The `node:cluster` module is Node's built-in answer for network servers: it starts **several Node processes from the same program** and lets them share a listening port, so a server can use every core without a separate proxy in front of each process. Two words matter from here on: - **Primary**: the first process you start. It forks workers, supervises them and, under the default scheduling policy, accepts incoming connections on their behalf. - **Worker**: a process the primary started with `cluster.fork()`. Workers run your server code and handle requests. ## Two roles, one script `cluster.fork()` is built on `child_process.fork()`. It starts a new Node process running the file in `cluster.settings.exec`, which defaults to `process.argv[1]`, the script you launched. So the **same entry file runs in every process**, and the file has to branch on its role. The branch uses `cluster.isPrimary` (or its negation, `cluster.isWorker`). The value comes from the environment: when the primary forks a worker it adds a `NODE_UNIQUE_ID` variable holding the worker's id. While a process boots, before your code runs, Node checks for that variable: if it is absent, the process is the primary; if it is present, it is a worker. Node then deletes the variable from the worker's `process.env`, so a child process the worker spawns later does not mistake itself for a cluster worker. | | Primary | Worker | |---|---|---| | `cluster.isPrimary` | `true` | `false` | | Can call `cluster.fork()` | yes | no | | Sees `cluster.workers` | yes, keyed by id | no | | Sees `cluster.worker` | no | yes, its own `Worker` object | | Usually runs | the fork loop and restart logic | `http.createServer(...).listen(port)` | Older code uses `cluster.isMaster` and `cluster.setupMaster()`. Both have been deprecated aliases since Node 16 for `cluster.isPrimary` and `cluster.setupPrimary()`; they still work in Node 24, but new code should use the new names. ## What a worker is, and is not A cluster worker is a **full operating-system process**, not a thread: - it has its **own V8 heap**, its own event loop and its own copy of every module-level variable; - it reruns all of the entry script's top-level code, including imports and startup work, so expensive initialisation belongs behind the role check; - it talks to the primary through the **IPC channel** that `child_process.fork()` opened, using `process.send()` and `process.on('message')` in the worker and `worker.send()` in the primary; - if it crashes, the other workers keep serving. When process isolation is not needed and the goal is to move CPU-heavy work off the main thread inside one process, the Node docs point to `worker_threads` instead; that module is covered in its own lesson. ## Sharing a port In a worker, `server.listen(8000)` does not simply bind port 8000. The worker sends a message to the primary, and the primary owns the listening socket. Under the default policy on every platform except Windows, the primary accepts each connection and hands it to a worker in turn; on Windows the workers accept from a socket the primary shares with them. The details of that choice are a separate question; for the basics, the point is that **many workers can call `listen()` on the same port** without an `EADDRINUSE` error, because the primary arranges the sharing. ## What the primary must do itself Node deliberately does very little management. The docs are explicit that **Node.js does not automatically manage the number of workers**: 1. The primary decides how many to fork. `os.availableParallelism()` is the usual starting point for one worker per core. 2. The primary listens for the `'exit'` event and calls `cluster.fork()` again if it wants a replacement; nothing respawns a dead worker for you. 3. The primary decides when to retire workers, for example with `worker.disconnect()` during a deploy. If every worker dies, existing connections are dropped and new ones are refused, even though the primary is still running. ## Common misconceptions - Treating workers as threads that share memory: a `Map` filled in one worker is invisible to the others. - Expecting Node to fork one worker per core on its own: nothing is forked until the primary calls `cluster.fork()`. - Writing a separate worker file because "the primary and workers must differ": the default is one file with a role branch, although `cluster.setupPrimary({ exec })` can point workers at another file. - Assuming a crashed worker comes back by itself.
- Why does expensive startup work at the top of the entry script run once per worker?`cluster.fork()` starts a brand-new Node process on the same entry file, so every top-level import and statement runs again in each worker. The primary's loaded modules and variables are not copied across. Put work only the primary needs inside the `cluster.isPrimary` branch, and work each worker needs (database pools, caches, the HTTP server) in the worker branch, remembering it is repeated N times.
- What are cluster.isMaster and cluster.setupMaster(), and should new code use them?They are the original names, deprecated since Node 16 in favour of `cluster.isPrimary` and `cluster.setupPrimary()`. In Node 24 they remain aliases that behave identically, so old code keeps running, but new code and reviews should use the primary names.
- How does a worker learn its own identity, and how does the primary find every worker?In a worker, `cluster.worker` is its own `Worker` object and `cluster.worker.id` its unique id. In the primary, `cluster.workers` maps each live worker's id to its `Worker` object, so `Object.values(cluster.workers)` iterates them. A worker is removed from that map once it has both disconnected and exited.
- Cluster workers are threads sharing one heap with the primary.
- Importing node:cluster forks one worker per CPU core automatically.
- The primary and workers must live in separate script files.
- Node restarts a crashed cluster worker without code in the primary.
- Each cluster worker must listen on its own port behind a proxy.