Lesson 192 of 296
Worker threads and the cluster module
What you will learn
- Running CPU-heavy JavaScript on another thread
- Passing messages to and from workers
- Worker pools
- The cluster module and using all CPU cores
- Which to choose
On this page
Worker threads
The node:worker_threads module runs JavaScript on separate threads, each with its own event loop and V8 instance. The main thread stays free to handle requests while the worker does the heavy work.
Workers communicate with the main thread by messages (data is copied, or transferred for some binary types; SharedArrayBuffer allows real shared memory).
import { Worker } from "node:worker_threads";
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
parentPort.postMessage(fib(workerData.n));
`;
export function fibInWorker(n: number): Promise<number> {
return new Promise((resolve, reject) => {
const worker = new Worker(workerCode, { eval: true, workerData: { n } });
worker.once("message", (value: number) => resolve(value));
worker.once("error", reject);
worker.once("exit", (code) => {
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}In a real project the worker code lives in its own file: new Worker(new URL("./fib-worker.js", import.meta.url), { workerData }). The inline eval version keeps this example in one place.
Now the /fib endpoint from Lesson 190 can await fibInWorker(40) and other requests keep being served.
Worker pools
Creating a worker costs time and memory (tens of milliseconds). For many tasks, keep a pool of workers (usually about one per CPU core) and send tasks to free workers. Libraries such as Piscina do this.
The cluster module and multiple processes
A Node.js process uses one main thread, so on an 8-core server one process uses roughly one core for your JavaScript. To use all cores for handling requests, run several processes:
| Option | How |
|---|---|
node:cluster | A primary process forks worker processes that share the same port |
| PM2 | A process manager that runs N copies, restarts crashed ones, and does zero-downtime reloads |
| Containers (most common today) | Run several containers or pods behind a load balancer (Lessons 233 and 249); each runs one Node.js process |
Threads vs processes
| Worker threads | Multiple processes (cluster, containers) | |
|---|---|---|
| Purpose | Offload CPU-heavy tasks from the request thread | Handle more requests using all cores and machines |
| Memory | Same process, can share memory | Separate memory |
| Crash isolation | A crash can affect the process | One crashing process does not kill the others |
| Communication | Messages, shared buffers | Network, a queue or a shared database |
How to say it in an interview
"Worker threads run JavaScript on separate threads with their own event loop, communicating by messages, so I use them for CPU-heavy tasks like image processing or big calculations without blocking requests, usually through a pool such as Piscina. To use all CPU cores for request handling I run multiple processes, with the cluster module or PM2 on a single server, or more commonly several containers behind a load balancer. Threads are for offloading CPU work; processes are for scaling throughput and isolating crashes."
Key words
| Word | Meaning |
|---|---|
| Worker thread | A separate JavaScript thread in the same process |
| Worker pool | A reusable set of workers that take tasks |
| Process | A running program with its own memory |
| Cluster | Several Node.js processes sharing one port |
| PM2 | A Node.js process manager |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.