Cluster Module
On this page
Why Cluster Exists
Node.js is single-threaded for JavaScript execution. On multi-core machines, a single process cannot fully utilize CPU capacity. Clustering allows you to spawn multiple worker processes behind a shared port.
Basic Cluster Pattern
import cluster from 'node:cluster';
import os from 'node:os';
if (cluster.isPrimary) {
const cpus = os.cpus().length;
for (let i = 0; i < cpus; i++) {
cluster.fork();
}
} else {
// start HTTP server here
}
Stateless Requirement
Each worker has its own memory space. Shared in-memory state does not synchronize automatically. Use external stores (Redis, database) for shared state.
Operational Considerations
- Handle worker crashes and auto-restart
- Monitor per-worker memory
- Gracefully restart during deployments
Cluster improves horizontal scaling on a single machine but does not replace proper load balancing across multiple instances.