The Cluster Module
Node.js runs JavaScript on a single thread by default, meaning a CPU-heavy or busy process can't use multiple CPU cores directly. The `cluster` module solves this by forking multiple worker processes that share the same server port.
Each worker is a separate Node.js process with its own memory, but the OS load-balances incoming connections between them.
Forking workers
In the master process, `cluster.fork()` spawns worker processes, typically one per CPU core.
Handling worker crashes
Listening for the 'exit' event on workers lets you automatically restart crashed workers to keep the app resilient.
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
for (let i = 0; i < os.cpus().length; i++) cluster.fork();
} else {
require('./server.js');
}Worker 1 started
Worker 2 started
...The primary process forks one worker per CPU core; each runs the server independently.
cluster.on('exit', (worker) => {
console.log('Worker died, restarting...');
cluster.fork();
});Worker died, restarting...Listening for worker exits lets you automatically spawn a replacement.
Key points
- Node.js is single-threaded by default.
- cluster.fork() creates worker processes sharing one port.
- Workers utilize multiple CPU cores for better throughput.
- Restarting crashed workers improves resilience.
