Worker Threads — Node.js

JavaScript in Node runs on one thread, so heavy computing work (CPU-bound, slow because the processor is busy) blocks the event loop: other requests, such as…

A new route in notes-api, GET /stats, counts how many primes there are up to 3 million. That count takes about 0.45 seconds. It sounds short, but while that count runs, the server serves no other request at all. Siti, who only asks for the list of notes, waits too.

The way out is a worker thread: an extra thread inside the Node process that runs its own JavaScript. With a worker thread, heavy computing work doesn't stop the server. Think of a shop cashier who sends a helper to the storeroom to count the stock, while the cashier keeps serving customers. The cashier is the main thread (the first thread, where the event loop runs). The customers are the requests. The storeroom helper is a worker. postMessage is how the helper brings the result back to the cashier.

The problem: one thread for every request

You saw in the event loop lesson that JavaScript in Node runs on one thread. Reading a file or querying a database is fine, because Node hands the waiting to libuv and the operating system, then goes on serving other requests. But computing work (CPU-bound: slow because the processor is busy calculating) is done by the JavaScript thread itself. While that thread computes, no other code runs.

The route below counts primes right inside its handler. 3_000_000 is the same as 3000000: the underscores only make the number easier to read:

function countPrimes(limit) {
  let count = 0;
  for (let n = 2; n <= limit; n++) {
    let isPrime = true;
    for (let d = 2; d * d <= n; d++) {
      if (n % d === 0) { isPrime = false; break; }
    }
    if (isPrime) count++;
  }
  return count;
}

app.get("/stats", (req, res) => {
  res.json({ primes: countPrimes(3_000_000) }); // {"primes":216816}
});

These are measurements with curl, on the same laptop:

Siti's request Time
GET /notes, the server idle 0.001 seconds
GET /notes, while /stats is computing 0.38 seconds

Siti waits until the counting is done, about 0.4 seconds, though the route she opens only needs 1 millisecond. If ten people open /stats at the same time, everyone waits 4 seconds.

worker_threads: the helper in the storeroom

The built-in worker_threads module runs a JavaScript file on another thread. The heavy work moves to that file:

// count-primes.js (runs in the worker)
const { parentPort, workerData } = require("node:worker_threads");

function countPrimes(limit) { /* same as above */ }

parentPort.postMessage(countPrimes(workerData.limit));

Then the route on the main thread starts a worker that runs that file:

// app.js (main thread)
const path = require("node:path");
const { Worker } = require("node:worker_threads");

app.get("/stats", (req, res) => {
  const worker = new Worker(path.join(__dirname, "count-primes.js"), {
    workerData: { limit: 3_000_000 },
  });
  worker.on("message", (count) => res.json({ primes: count }));
  worker.on("error", (err) => res.status(500).json({ error: err.message }));
});

The result is still {"primes":216816} after about 0.45 seconds. The difference: Siti's GET /notes now finishes in 0.001 seconds, because the main thread is free.

Talking both ways

This table sums up how the main thread and a worker send data to each other:

Direction The sender writes The receiver writes
main to worker, at the start new Worker(file, { workerData }) workerData
main to worker, any time worker.postMessage(data) parentPort.on("message", ...)
worker to main parentPort.postMessage(data) worker.on("message", ...)

Data sent is copied, not shared, because a worker has its own memory. Numbers, text, arrays and plain objects can be copied. Functions can't: worker.postMessage({ compute: () => 1 }) throws DataCloneError: () => 1 could not be cloned. (For memory that really is shared there is SharedArrayBuffer, but you rarely need it.)

In the browser: Web Workers

The Lab on this page runs in the browser, so the Lab uses a Web Worker, the browser's version of a worker. The idea is exactly the same. The browser also has one main thread, and a heavy loop there freezes the page: animations stop, and clicks get no response. Only the names differ:

Node worker_threads Browser Web Worker
Create new Worker("count-primes.js", { workerData }) new Worker(url)
Send from the worker parentPort.postMessage(x) postMessage(x)
Receive in the worker parentPort.on("message", fn) self.onmessage = fn
Receive the result worker.on("message", fn) worker.onmessage = (e) => e.data

When you need it, and when you don't

In the exercise: splitting work into 4 parts

The exercise simulator has no worker_threads. So what you practise is how to split the work: adding up 1 to 1,000 is divided among 4 "workers", 250 numbers each, then the results are combined. computeSum(start, end) adds the numbers from start to end, and end is included. In the exercise, the four parts still take turns on one thread. With worker_threads, the four could run at the same time. The expected output:

Worker 1: sum(1..250) = 31375
Worker 2: sum(251..500) = 93875
Worker 3: sum(501..750) = 156375
Worker 4: sum(751..1000) = 218875
Total result: 500500
Check (n*(n+1)/2): 500500

⚠️ A stuck server, wasteful workers, or a crash

TL;DR: JavaScript in Node runs on one thread, so heavy computing work (CPU-bound, slow because the processor is busy) blocks the event loop: other requests, such as a GET /notes that normally takes 1 ms, wait 0.4 seconds too. The built-in worker_threads module moves that work to another thread, called a worker. new Worker(file, { workerData }) starts a worker from the main thread (the first thread) and gives it its starting data, parentPort.postMessage(result) sends the result from the worker, then worker.on("message") and worker.on("error") receive the result or the error on the main thread. Data sent is copied, so functions can't be sent. In the browser, a Web Worker does the same with postMessage and onmessage. Use workers for computing, not for I/O, and use a pool (a set of workers that are reused) when there are many requests.

⚡ Heavy computing blocks everyone

Write:

app.get("/stats", (req, res) => {
  res.json({ primes: countPrimes(3_000_000) });
});
Guess first: countPrimes counts the primes up to 3 million, in about 0.45 seconds. This route works fine on your laptop. Why does it become a problem when many people use it?

The route blocks the event loop. While the count runs, about 0.45 seconds, the server serves no other request at all.

Meaning: JavaScript in Node runs on one thread. Work that is slow because of the CPU (the processor), not because it waits for I/O, makes every other request wait in line.

⚡ Move it to a worker

Write:

const worker = new Worker(path.join(__dirname, "count-primes.js"), {
  workerData: { limit: 3_000_000 },
});
worker.on("message", (count) => res.json({ primes: count }));

Meaning: new Worker starts a worker: a new thread with its own JavaScript, here the file count-primes.js. workerData is the starting data for that worker. When the worker sends its result, worker.on("message") answers the request. The result is the same, but other requests, such as GET /notes, now finish in 0.001 seconds, because the main thread (the first thread, where the event loop runs) is free.

⚡ Send it back with postMessage

Write:

parentPort.postMessage(countPrimes(workerData.limit));

Meaning: This code is in the worker (count-primes.js). parentPort.postMessage sends the result to the main thread. Data sent is copied, not shared, so a function can't be sent along.

What you will learn