Simple REST Server

Multithreading in Node.js: Worker Threads vs Cluster Module vs Child Processes

Deconstructing the Single-Threaded Myth

A widespread misconception among junior developers is that “Node.js cannot do multithreading.” While it is true that your JavaScript code executes sequentially on a single thread (the main event loop thread), modern Node.js possesses sophisticated multi-core and multithreading capabilities.

The challenge is choosing the right concurrency model for your specific problem domain. Using worker threads to scale HTTP servers is an anti-pattern. Conversely, using the cluster module to process heavy image compression duplicates entire process runtimes and wastes system RAM.

In this guide, we evaluate Worker Threads, the Cluster Module, and Child Processes, examine memory sharing mechanics, and provide real-world production code for CPU-intensive parallel processing.


Concurrency Models Comparison Matrix

Metric / FeatureWorker Threads (worker_threads)Cluster Module (cluster)Child Processes (child_process)
Execution UnitTrue OS Threads within 1 ProcessIndependent OS ProcessesIndependent OS Processes
Memory ModelShared memory (SharedArrayBuffer)Completely isolated memoryCompletely isolated memory
Startup OverheadLow (~10-30 ms)High (~100-200 ms per process)High (~100-200 ms per process)
Inter-Process Comm (IPC)In-memory postMessage / SharedArrayIPC Socket / Process serializationstdin, stdout, IPC pipes
Primary Production PurposeCPU-intensive calculations (crypto, AI)Multi-core HTTP server scaleRunning external CLI tools (ffmpeg, git)

1. Worker Threads: Parallel CPU Execution with Shared Memory

Worker threads run separate V8 instances inside the same operating system process. They are the premier solution for CPU-heavy tasks like cryptographic hashing, large JSON transformations, and image transcoding.

// main.js
import { Worker } from 'node:worker_threads';
import os from 'node:os';

function executeParallelTask(workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL('./worker.js', import.meta.url), {
      workerData,
    });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
}

async function run() {
  console.log('Dispatching heavy CPU task to Worker Thread...');
  const result = await executeParallelTask({ iterations: 10_000_000 });
  console.log('Result from worker:', result);
}

run();
// worker.js
import { parentPort, workerData } from 'node:worker_threads';

// Heavy CPU computation running isolated from main event loop
let sum = 0;
for (let i = 0; i < workerData.iterations; i++) {
  sum += Math.sqrt(i);
}

// Send result back without blocking main HTTP thread
parentPort.postMessage({ total: sum, status: 'complete' });

2. Cluster Module: Horizontal Multi-Core HTTP Scaling

The cluster module forks the main process into multiple worker processes that all share the exact same server port. The master process distributes incoming TCP connections among workers using a round-robin algorithm:

// cluster-server.js
import cluster from 'node:cluster';
import http from 'node:http';
import os from 'node:os';

const numCPUs = os.cpus().length;

if (cluster.isPrimary) {
  console.log(`Primary master process ${process.pid} is running.`);
  console.log(`Forking HTTP workers across ${numCPUs} CPU cores...`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.warn(`Worker ${worker.process.pid} died. Forking replacement...`);
    cluster.fork();
  });
} else {
  // Workers share the TCP connection on port 8080
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Handled by worker ${process.pid}\n`);
  }).listen(8080);
}

Frequently Asked Questions (FAQ)

Should I use the Cluster Module or PM2 in production?

In modern containerized production (Docker / Kubernetes), you typically run a single Node.js process per container and let Kubernetes scale pods horizontally. If deploying to standalone VPS instances without container orchestrators, PM2 in cluster mode is superior because it handles automated restarts, zero-downtime reloads, and log aggregation out of the box.

Can Worker Threads share memory without copying?

Yes. By utilizing SharedArrayBuffer and Atomics, multiple worker threads can read and write to the exact same physical memory addresses without serializing data through postMessage(), achieving zero-copy concurrency.


Continue expanding your technical depth with our related engineering guides:

Published by Mohit Kumar under NodeJS Mastery. Learn more in our deep-dive on The Node.js Event Loop Architecture.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top