Clustering & Scaling — Node.js

One Node process only uses one core (a part of the processor). The cluster module makes a primary (cluster.isPrimary, formerly isMaster), the process that…

Your server has 4 CPU cores (parts of the processor that can each work on their own), but when notes-api gets busy, only one of them works hard. The other three sit idle. The reason: one Node process runs your JavaScript on one thread, so that process only uses one core.

Clustering runs several copies of notes-api at the same time, one per core, all using the same port 3000. Think of a bank with four tellers. The guard at the door sends customers to them in turn: teller 1, 2, 3, 4, then back to 1. Each teller keeps their own notebook, and what teller 1 writes down, teller 2 never knows. In Node, the guard is the primary, the tellers are workers, the customers are the incoming connections, and the notebook is each process's memory. A worker here is a whole Node process, not a worker thread from the previous lesson.

One process, one core

You saw in the Event Loop and Worker Threads lessons that JavaScript code runs on one thread. Worker Threads moves heavy computation to another thread inside the same process. Clustering is different: it runs a whole Node process several times, each with its own event loop and its own memory. How many processes should you run? os.availableParallelism() (Node 18.14 and later) gives the number of cores you may use, for example 4. Older versions use os.cpus().length from the Built-in Modules lesson.

Making a cluster with the cluster module

app.js hardly changes: add one logger middleware at the top, which prints the pid (process number) of the worker that answers. Then make a file cluster.js:

// app.js: a logger at the very top, the rest stays the same
app.use((req, res, next) => {
  console.log(`[worker ${process.pid}] ${req.method} ${req.url}`);
  next();
});
// cluster.js
const cluster = require("node:cluster");
const os = require("node:os");

if (cluster.isPrimary) {
  const count = os.availableParallelism();
  console.log(`Primary ${process.pid} running, forking ${count} workers`);
  for (let i = 0; i < count; i++) {
    cluster.fork(); // run this file again as a worker
  }
  cluster.on("exit", (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died (${signal || code}), forking a replacement`);
    cluster.fork();
  });
} else {
  require("./app.js"); // worker: run the server as usual
}

What node cluster.js prints (the pids are only an example, they differ every run):

$ node cluster.js
Primary 4810 running, forking 4 workers
Server running at http://localhost:3000
Server running at http://localhost:3000
Server running at http://localhost:3000
Server running at http://localhost:3000

There are four "Server running" lines, one from each worker. The output of every worker appears in the primary's terminal.

Who answers a request: round-robin

The primary takes every new connection and hands it to the workers in turn (round-robin). Five runs of curl -s localhost:3000/notes print this in the server's terminal:

Request no. Worker that answers
1 [worker 4811] GET /notes
2 [worker 4812] GET /notes
3 [worker 4813] GET /notes
4 [worker 4814] GET /notes
5 [worker 4811] GET /notes, the turn comes back to the start

Turn i (counting from 0) goes to worker number i % workerCount. That remainder is what makes the order start again from the first worker. The work is divided per connection, not per request. A browser that keeps one connection open (keep-alive) sends its next requests to the same worker. On Windows, dividing the connections is left to the operating system.

Memory is not shared between workers

The notes array in app.js lives in each worker's memory, so there are four separate copies, each starting with 2 notes. Restart the cluster, then send POST /notes for "Workout" and get a 201. Before you look at the table, guess: how many notes does the next GET /notes return?

Step Request Worker notes in that worker Answer
1 POST /notes "Workout" 4811 3 201, id: 3
2 GET /notes 4812 2 2 notes, no "Workout"
3 GET /notes 4813 2 2 notes
4 GET /notes 4814 2 2 notes
5 GET /notes 4811 3 3 notes

The answer depends on whose turn it is. Only the worker that saved "Workout" gives 3, the other three give 2. Worse, the next POST that goes to worker 4812 also makes an id: 3, with different content. The cure: keep data outside the process, in a database (the Database Connection lesson) or Redis (a server that keeps data in memory, separate from the Node processes). This way every worker reads the same place. The same goes for sessions kept in memory and rate-limit counters (the limit on how many requests a client may send).

A worker dies, the primary replaces it

An uncaught error ends the process. Without a cluster, the whole server stops with it. With a cluster, only one worker stops. The (1) on the first line is the exit code of a process that ended because of an error:

Worker 4812 died (1), forking a replacement
Server running at http://localhost:3000

The next requests are divided among the workers still running, and the replacement with a new pid (for example 4815) joins the turns. Whatever was in the stopped worker's memory is lost with it.

PM2 cluster mode: what people use

In production, cluster.js is rarely written by hand. PM2 (a process manager, a program that manages processes for Node) does the same as cluster.js above, also with the cluster module. In addition, PM2 adds automatic restarts, logs and reloads without downtime (no time when the server can't be reached):

$ pm2 start app.js -i 4 --name notes-api
[PM2] Starting /home/budi/notes-api/app.js in cluster_mode (4 instances)
[PM2] Done.

🤔 Cluster, Worker Threads, or container replicas?

Situation Pick
API on a 4-core VPS, one core at 100% when busy cluster or PM2 cluster mode
One endpoint does heavy computing (makes a PDF, hashes) Worker Threads
Runs on Kubernetes or Docker Swarm (systems that manage many containers) 1 process per container, add replicas (copies of the same container)
A small API that mostly waits on the database Not needed, 1 process is enough

A cluster raises how many requests can be answered at the same time, not the speed of one request. A request that needs 3 seconds of CPU work still takes 3 seconds.

In the exercise: a stand-in cluster

The exercise simulator can't fork processes. So the starter code gives you a stand-in cluster object: fork() makes a worker with pid 101, 102, 103, and prints Forked worker pid=.... In the exercise, you:

  1. print Primary 1 forking 3 workers,
  2. fork 3 workers with for,
  3. divide 6 requests with cluster.workers[i % cluster.workers.length], printing "Request " + (i + 1) + " handled by worker " + worker.pid.

Request 4 goes back to worker 101.

⚠️ Wrong ideas about clusters

TL;DR: One Node process only uses one core (a part of the processor). The cluster module makes a primary (cluster.isPrimary, formerly isMaster), the process that forks (starts a new copy of) one worker per core (os.availableParallelism()). All the workers share port 3000. The primary hands out connections in turn (round-robin): turn i goes to worker i % count. Every worker has its own memory, so data must be stored in a database or Redis (a server that keeps data in memory), not in an array. When a worker stops, cluster.on("exit") forks a replacement. In production, use PM2 (a program that manages processes): pm2 start app.js -i max. A cluster adds capacity (how many requests are answered at the same time), not the speed of one request.

⚡ One copy per core

Write:

if (cluster.isPrimary) {
  const count = os.availableParallelism();
  for (let i = 0; i < count; i++) {
    cluster.fork();
  }
} else {
  require("./app.js");
}

Meaning: One Node process only uses one core (a part of the processor). Clustering runs several copies of the server on the same port. The process you start is the primary (cluster.isPrimary is true). The primary forks workers, which means it runs the same file as a new process, as many times as there are cores. In each worker, isPrimary is false, so the worker runs app.js as usual.

⚡ In turn: round-robin

Meaning: The primary takes every new connection and hands it to the workers in turn: worker 1, 2, 3, 4, then back to 1. If one worker stops, cluster.on("exit") can fork a replacement, so the server keeps answering.

⚡ Memory isn't shared

Guess first: notes-api runs with 4 workers, and the notes array starts with 2 notes. You send POST /notes "Workout" and get a 201. How many notes does the next GET /notes answer with?

It depends on whose turn it is. Only the worker that stored "Workout" gives 3, the other three give 2. The notes array lives in each worker's memory, separately.

Meaning: Keep data outside the process, in a database or Redis (a server that keeps data in memory), so every worker reads the same place.

What you will learn