advanced
Cluster
Know process-based scaling, load distribution, crash isolation, sticky sessions, and why orchestration often replaces cluster.
The `cluster` module forks worker processes that share a server port via OS scheduling (primary accepts or distributes connections depending on setup). Each worker has its own V8 heap and event loop — crash isolation is per process.
import cluster from 'node:cluster';
import http from 'node:http';
if (cluster.isPrimary) {
for (let i = 0; i < cpus().length; i++) cluster.fork();
cluster.on('exit', (worker) => cluster.fork()); // respawn
} else {
http.createServer(handler).listen(3000);
}
Sticky sessions are required when in-memory session state lives per worker. In containers/Kubernetes, horizontal pod scaling plus a load balancer often replaces hand-rolled cluster — same idea, better ops tooling.
On interviews: explain process vs thread model, when cluster helps on bare metal, and why orchestration duplicated its role.
Common pitfalls: in-memory caches per worker causing inconsistency; no graceful drain on worker restart; assuming cluster fixes CPU-bound JS (each worker still single-threaded for JS).
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- One worker = one JS thread for user code.
- Plan session affinity or externalize state.
- Coordinate graceful shutdown across workers.
- Compare cluster to container replicas.