Clustering and scaling

Topic 3 of 4 in Performance & scaling7 min readIntermediateFree course

Overview

A single Node.js process runs your JavaScript on one thread, so it can only keep one CPU core busy with application code. A server with 8 cores running one Node process leaves most of its power unused. And one machine — however big — eventually isn’t enough, or becomes a single point of failure.

Scaling a Node API means running several copies of it, and spreading requests between them.

On one machine, a primary process forks four workers, one per CPU core, using cluster or PM2. Across many machines, a load balancer with health checks spreads requests over several app containers, each running one Node process, all sharing PostgreSQL, Redis and object storage. Stateless processes are interchangeable, so copies can be added or removed at any time.

The cluster module

Node’s built-in cluster module starts several worker processes that share one port. The primary process distributes incoming connections between them:

JavaScript
// src/cluster.js
import cluster from 'node:cluster';
import os from 'node:os';

if (cluster.isPrimary) {
  const workers = Number(process.env.WEB_CONCURRENCY ?? os.availableParallelism());
  for (let i = 0; i < workers; i++) cluster.fork();

  cluster.on('exit', (worker, code, signal) => {
    if (!worker.exitedAfterDisconnect) {
      console.error(`Worker ${worker.process.pid} died (${signal ?? code}), restarting`);
      cluster.fork(); // self-healing
    }
  });
} else {
  await import('./server.js'); // each worker runs the normal app
}

Each worker is a full, separate Node process with its own memory and event loop. If one crashes, the others keep serving, and the primary starts a replacement.

Because workers don’t share memory, anything stored in a JavaScript variable — an in-memory cache, a rate-limit counter, a session map — exists separately in each worker. Requests from the same user may hit different workers. That’s the first hint of the most important scaling rule, below.

Process managers

Instead of writing cluster code, many teams use a process manager:

  • PM2 — pm2 start src/server.js -i max runs one instance per core, restarts crashed processes, and offers log management and zero-downtime reloads.
  • systemd — on a Linux server, a service unit restarts your app on failure and starts it at boot.

Containers: one process each

In Docker and Kubernetes, the usual approach is different: run one Node process per container, and let the platform run as many container replicas as you need. The platform already handles restarts, health checks and load balancing, and scales replicas up and down with traffic. Adding cluster inside a container just duplicates that work and makes memory limits harder to reason about.

Where you run How to use multiple cores
A single VM or bare-metal server cluster, PM2 or several systemd instances
Docker / Kubernetes / ECS / Cloud Run / Fly.io one process per container, several replicas
Serverless (Lambda, Cloud Functions) the platform runs many instances automatically

Stateless: the rule that makes scaling work

With several instances, any request may go to any instance. So no instance may keep important state to itself:

State ✗ Per-process ✓ Shared
Sessions a Map in memory Redis or the database
Cache a module-level object Redis
Uploaded files local disk object storage (S3, R2)
Rate limits in-memory counter Redis-backed store
Scheduled tasks setInterval in the app a job queue / scheduler, so it runs once
WebSocket broadcasts wss.clients only Redis pub/sub between instances

An app that follows these rules is stateless: instances are interchangeable, you can add or remove them at any time, and a crash only loses the requests that were in flight.

Vertical vs horizontal scaling

  • Vertical scaling — a bigger machine (more CPU, more RAM). Simple, no code changes, but has a ceiling and keeps a single point of failure.
  • Horizontal scaling — more instances behind a load balancer. Practically unlimited, and resilient, but requires statelessness.

Most apps start with two small instances (for resilience) and scale horizontally as traffic grows.

The database is usually the limit

Ten app instances each with a pool of 10 connections means 100 database connections — which may be all your database allows. When you scale out:

  • Size pools deliberately: instances × pool max must stay below the database limit.
  • Use a connection pooler such as PgBouncer in front of Postgres for many instances.
  • Cache hot reads in Redis, add indexes, and consider read replicas for read-heavy apps.

Scaling the app tier is easy once it’s stateless. Scaling the data tier is where real engineering effort goes — which is why measuring before scaling matters.

Load balancers and health checks

A load balancer (nginx, HAProxy, a cloud load balancer, or your platform’s built-in one) spreads requests over instances and stops sending traffic to unhealthy ones. For that it needs health-check endpoints — covered in Graceful shutdown and health checks.

Design for two from day one. Even if you run one instance today, building as if there were two — no in-memory sessions, no local files, no in-process schedulers — makes scaling a configuration change instead of a rewrite.

Exercise

A self-healing cluster

Write cluster.js that, in the primary, forks one worker per available CPU and replaces any worker that dies unexpectedly. Workers start the Express app from ./server.js. Log which process ID handles each request so you can see the load being shared.

JavaScript
import cluster from 'node:cluster';
import os from 'node:os';

// your code here

Summary

  • One Node process uses one main thread; to use all cores, run several processes.
  • The cluster module forks workers that share a port; a process manager (PM2, systemd) can do the same.
  • In containers, prefer one Node process per container and let the platform run several replicas.
  • Scaling out only works if instances are stateless — keep sessions, caches and files in shared stores.
  • Scale vertically (bigger machine) or horizontally (more instances) based on measurements.