Node.js Cluster Module: Scaling Applications with Workers

The Cluster module in Node.js enables running multiple Node.js processes that share server ports and distribute workloads across CPU cores. This is especially useful for scaling applications on multi-core systems. Each worker is an independent process, while the primary process manages workers and distributes incoming connections.

cluster.isPrimary / cluster.isWorkercluster.fork()Worker classIPC communicationschedulingPolicy (SCHED_RR / SCHED_NONE)

~2 min read · Updated Dec 26, 2025

1. Introduction


The Cluster module allows developers to run multiple Node.js processes that share server ports. This improves performance and resource utilization by leveraging multiple CPU cores.

2. How It Works


  • Workers are created using child_process.fork().
  • Communication between primary and workers happens via IPC.
  • Two distribution methods:
    • Round-robin (default): Primary accepts connections and distributes them across workers.
    • Direct accept: Primary creates the socket and passes it to workers, which accept connections directly.

3. Basic Example


const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();

if (cluster.isPrimary) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\\n');
  }).listen(8000);
}

4. Worker Class


  • Each worker is represented by a Worker object extending EventEmitter.
  • Key events:
    • 'disconnect': IPC channel disconnected.
    • 'error': Worker error.
    • 'exit': Worker terminated.
    • 'listening': Worker is ready to accept requests.
    • 'message': Message received from worker.
    • 'online': Worker is running after fork.

5. Worker Management


  • worker.disconnect(): Disconnect worker gracefully.
  • worker.exitedAfterDisconnect: Distinguish voluntary vs accidental exit.
  • worker.isConnected() / worker.isDead(): Check worker status.
  • worker.kill(): Terminate worker immediately.

6. Cluster Settings


  • cluster.settings: Includes execArgv, exec, args, cwd, serialization, silent, stdio, uid, gid, inspectPort, windowsHide.
  • cluster.setupPrimary(): Configure default fork behavior.
  • cluster.schedulingPolicy: Choose between round-robin or OS scheduling.

7. Important Notes


  • Node.js does not provide routing logic; sessions should not rely on in-memory data.
  • Workers can be killed or respawned without affecting others.
  • Managing the number of workers is the application’s responsibility.

Conclusion


The Cluster module is a powerful tool for scaling Node.js applications. By distributing workloads across multiple processes and leveraging IPC communication, developers can build scalable and efficient systems. Proper worker management and design are essential for success.

Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue