Node.js Reference ยท child_process, worker_threads and cluster
Node.js cluster.fork() method
Reference for cluster.fork() in Node.js: start worker processes from the primary, pass environment variables, the Worker object, events and restarting crashed workers.
cluster.fork([env]) starts a new worker process from the primary process. The worker runs the same entry script as the primary, so the usual pattern is one file with an if (cluster.isPrimary) branch that forks workers and an else branch that does the real work.
Each worker is a separate Node.js process with its own memory, event loop and V8 instance, connected to the primary by an IPC channel. Workers that listen on the same port share it through the primary, which lets one machine use all its CPU cores for a server.
import cluster from "node:cluster"; if (cluster.isPrimary) { const worker = cluster.fork({ ROLE: "web" }); } else { // runs in each worker }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
cluster.fork(env?: object): cluster.Worker cluster.setupPrimary(settings?: { exec?: string, args?: string[], silent?: boolean, execArgv?: string[], ... }): void
| Name | Description |
|---|---|
env |
Key/value pairs added to the worker's environment on top of the primary's process.env. |
cluster.setupPrimary() |
Optional. Changes the defaults for all later fork() calls: the script to run (exec), its args, whether output is piped (silent) and the Node execArgv. |
Returns: a cluster.Worker object. It has an id (counting from 1), a process (the underlying ChildProcess), send(), disconnect(), kill(), isConnected(), isDead() and the exitedAfterDisconnect flag.
Errors / edge cases: only the primary creates workers, so do not call fork() from the worker branch. Every worker re-runs the whole entry script, so code outside the isPrimary branch executes once per process.
Usage notes
- Events: the
clusterobject emitsfork,online,listening,disconnectandexit; eachWorkeremitsonline,message,disconnect,exitanderror.onlinemeans the worker process started running JavaScript, not that your server is ready; uselisteningfor that. - Workers share nothing. There are no shared variables, caches or in-memory sessions between workers. Keep state in a database, Redis or the primary.
- Restart logic belongs in the
exithandler. Distinguish deliberate stops (worker.exitedAfterDisconnect === true) from crashes, and protect against crash loops with a limit or back-off. worker.idis a cluster counter, not a process id. Useworker.process.pidfor the PID.- Environment passes by value.
envvalues are strings; objects must be serialized (for example withJSON.stringify()). - Choose the worker count deliberately.
os.availableParallelism()is a common default for CPU cores; containers with CPU quotas may need a lower number. - Not for CPU parallelism inside a single request. For that, use worker threads; cluster scales request handling across processes.
- Fork versus
child_process.fork():cluster.fork()adds worker bookkeeping, shared server handles and scheduling. Usechild_process.fork()for unrelated helper processes. - Process managers: PM2 and container orchestrators provide the same effect from outside the code; combine them with cluster only when you understand which layer restarts what.