The cluster module and multi-core scaling

Advanced · 14 min

Use every CPU core by forking server workers that share a port, how round-robin works, and when containers or a reverse proxy are the better route.

Before thisChild processesWorker threads

Software Developer Diaries · 14 min

The cluster module and multi-core scaling

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Software Developer DiariesReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • One Node process runs your JavaScript on one core. `cluster` starts several copies of the same server, so an N-core machine can serve about N times the CPU-bound load.
  • The primary process calls `cluster.fork()`; each worker is a separate process that runs the same file and calls `listen()` on the same port. The primary hands out incoming connections.
  • On Linux and macOS the default is round-robin by connection: the primary accepts and distributes. Connections, not requests, are balanced, so long keep-alive clients can stick to one worker.
  • Workers share nothing. In-memory caches, sessions, rate-limit counters and WebSocket rooms exist per worker, so shared state must live in Redis or a database.
  • Today most deployments scale with several single-process containers or instances behind a load balancer. `cluster` is for one machine without that infrastructure, and it needs restart logic you write yourself.

One thread, many cores

A Node process executes JavaScript on one thread, so a busy server uses at most one core’s worth of JavaScript. On a machine with 8 cores, that leaves 7 idle. Worker threads parallelise one task. The cluster module takes the other route: run several copies of the whole server, and let the operating system schedule them on different cores.

The trick is that they all listen on the same port. Normally a second listen(3000) fails with EADDRINUSE. With cluster, the workers ask the primary process for the socket instead of opening it themselves.

The shape of a clustered server

import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';

if (cluster.isPrimary) {
  for (let i = 0; i < availableParallelism(); i++) cluster.fork();
  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`, code, signal);
    cluster.fork(); // replace it
  });
} else {
  http.createServer((req, res) => res.end(String(process.pid))).listen(3000);
}

The same file runs in both roles. cluster.isPrimary is true in the original process, which only forks and supervises. Each fork() starts a new Node process (this is child_process.fork underneath, with an IPC channel) that re-executes the file with isPrimary false and runs the server. The exit handler is the restart logic, and notice it is yours to write: cluster does not respawn dead workers automatically.

In my test, three workers answered with three distinct PIDs and cluster.schedulingPolicy reported round-robin.

How connections are shared

By default (round-robin on Linux and macOS), the primary accepts every incoming connection and passes each to the next worker in turn. On Windows, and when NODE_CLUSTER_SCHED_POLICY=none, workers accept directly and the operating system picks, which can skew the balance.

What is balanced is the connection. A browser or HTTP client with keep-alive sends many requests down one connection, all to the same worker. When I sent 12 requests through Node’s fetch to a three-worker cluster, only 2 workers answered, because fetch reused a few pooled connections. Spread comes from many distinct clients.

What workers do not share

Each worker is a separate process, with its own heap. So:

  • An in-memory cache is duplicated and inconsistent across workers.
  • Session objects, rate-limit counters and any “global” variable exist per worker.
  • WebSocket rooms and connection lists cover only that worker’s clients (see WebSockets).
  • Scheduled jobs run once per worker, unless you restrict them to one.

Anything that must be consistent moves to an external store like Redis or a database. This is the same constraint as scaling out to several machines, so code written for cluster is ready for that too.

Cluster, containers, or a reverse proxy

Cluster was the standard answer before containers. Many deployments now run one Node process per container and let the platform start N copies behind a load balancer. That gives per-instance memory limits, health checks, rolling restarts and logs, without a hand-written supervisor in the primary. Process managers such as PM2 offer a cluster mode that does the forking and restarting for you.

Cluster still makes sense for a single VM or bare-metal box without an orchestrator, or when you want to avoid an extra proxy hop. Either way, plan for graceful shutdown: on SIGTERM, stop accepting, let in-flight requests finish, then exit. See deploying Node applications and stateless services and session affinity for the state constraint behind scaling out.

What the video covers

Software Developer Diaries’ February 2023 video is described as a tutorial on multi-processing, load balancing and better scalability with cluster, including how to use fork and some best practices; it follows a DigitalOcean article by Stanley Ulili. I could not read a transcript, so I can’t say how current its advice on containers and process managers is. The state-sharing section, the connection-versus-request note and the comparison with containers are this page’s. Codevolution’s episode in “go deeper” is a second beginner-level walkthrough.

Where this fits

This closes the concurrency group: child processes for isolation, workers for in-process parallelism, cluster for server replication. Next, the HTTP module is what each of those workers actually runs.

Check yourself

  1. 01A 8-core server runs one Node process at 100% of one core and 7 idle. Does adding `cluster` help?

    If the load is CPU-bound or mixed and the one core is the limit, yes: forking 8 workers lets requests run on all cores. If the process is idle waiting for a slow database, cluster will not help, because the bottleneck is not JavaScript execution.

  2. 02You store login sessions in a JavaScript object inside the server. What breaks under `cluster`?

    Each worker has its own copy of that object. A login handled by worker 1 is unknown to worker 2, so a user is randomly logged out on later requests. Move sessions to a shared store such as Redis, or use signed stateless tokens.

  3. 03In a test, 12 requests through `fetch` to a 3-worker cluster reached only 2 workers. Why?

    Round-robin balances accepted connections, and `fetch` reuses pooled keep-alive connections, so many requests ride the same few connections. Spread across workers appears with many distinct clients, not with one client that keeps its connection open.

  4. 04Why do many teams skip `cluster` in containerised deployments?

    An orchestrator already starts several containers and a load balancer spreads requests, health-checks them and restarts failures. Running one process per container fits that model, keeps memory limits and logs per instance, and avoids writing supervisor logic in the primary.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark