Node.js ยท Chapter 34 of 43

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.

Example 1 (javascript)
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');
}
Output
Worker 1 started
Worker 2 started
...

The primary process forks one worker per CPU core; each runs the server independently.

Example 2 (javascript)
cluster.on('exit', (worker) => {
  console.log('Worker died, restarting...');
  cluster.fork();
});
Output
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.
๐Ÿ’ก Note: For most apps today, tools like PM2 manage clustering automatically without manual cluster module code.

๐Ÿ“ Quick Quiz

1. Why does the cluster module exist?

2. Which method spawns a worker process?

3. What tool is commonly used in production to manage clustering automatically?