AdvancedLesson 11 of 126 min read

Worker Threads: Using All the CPU Without Freezing the Server

Move CPU-heavy work off the main thread with worker_threads, split a prime-counting job across four workers, show that the main thread stays responsive, and verify the count with a known mathematical value and an independent NumPy sieve.

In this lesson you will

  • Explain why heavy computation blocks Node
  • Run work in worker threads
  • Split a job and combine the results
  • Check that the main thread stays responsive

About 28 minutes

The report that froze the server

Mara added a feature to the web service: a “forecast” that does a heavy calculation. Whenever someone asked for it, the whole service stopped answering for a second, because JavaScript runs on one thread, as lesson 1 showed, and the calculation held it. Waiting for input and output is cheap in Node, and computing is not. The cure is to give CPU work to another thread. The worker_threads module starts a worker, which runs a JavaScript file on its own thread with its own event loop, and talks to the main thread by messages, using postMessage and the message event. Workers do not share variables with the main thread, which avoids data races, and for big numeric arrays they can share memory explicitly with SharedArrayBuffer.

To use several cores, you split the job into independent parts, give one to each worker, and combine the answers. The example counts the prime numbers below fifty million, a classic CPU-heavy task, with a segmented sieve: each worker takes a range of numbers, finds its own primes with a small list of base primes up to the square root of the limit, and sends back a count. The number of primes below 50,000,000 is a known mathematical constant, 3,001,134, which makes a strong check, since there is no room for a plausible wrong answer. Workers have a start-up cost, so they pay off for work that takes tens of milliseconds or more.

Tool Use
new Worker(file, { workerData }) Start a thread with input
parentPort.postMessage(x) Send a result back
worker.on(“message”, f) Receive it
isMainThread Tell the roles apart in one file
SharedArrayBuffer Share memory between threads
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
function countPrimes(lo, hi, base) {
  const size = hi - lo, seg = new Uint8Array(size);
  for (const p of base) { if (p * p >= hi) break; let s = Math.max(p * p, Math.ceil(lo / p) * p); for (let m = s; m < hi; m += p) seg[m - lo] = 1; }
  let c = 0; for (let i = 0; i < size; i++) if (!seg[i] && lo + i >= 2) c++; return c;
}
function basePrimes(limit) { const s = new Uint8Array(limit + 1), out = []; for (let i = 2; i <= limit; i++) { if (!s[i]) { out.push(i); for (let j = i * i; j <= limit; j += i) s[j] = 1; } } return out; }
if (isMainThread) {
  const N = 50000000, parts = 4, base = basePrimes(Math.ceil(Math.sqrt(N)));
  const ranges = Array.from({ length: parts }, (_, i) => [Math.floor(N * i / parts), Math.floor(N * (i + 1) / parts)]);
  const tickWhile = async (fn) => { let ticks = 0; const t = setInterval(() => ticks++, 10); const r = await fn(); clearInterval(t); return [r, ticks]; };
  (async () => {
    const [blocked, ticksBlocked] = await tickWhile(async () => { await new Promise(r => setTimeout(r, 15)); return ranges.reduce((s, [a, b]) => s + countPrimes(a, b, base), 0); });
    const [par, ticksWorkers] = await tickWhile(() => Promise.all(ranges.map(([a, b]) => new Promise((res, rej) => { const w = new Worker(__filename, { workerData: { lo: a, hi: b, base } }); w.on('message', res); w.on('error', rej); }))).then(c => c.reduce((a, b) => a + b, 0)));
    console.log('primes below', N.toLocaleString('en-US'), ':', blocked, '(main thread) and', par, '(4 workers)');
    console.log('timer ticks while the main thread computed:', ticksBlocked <= 2 ? 'almost none (<= 2)' : ticksBlocked);
    console.log('timer ticks while 4 workers computed:', ticksWorkers >= 5 ? 'many (>= 5)' : ticksWorkers);
    console.log('segments:', ranges.map(r => r.join('-')).join(', '));
    console.log('DATA ' + JSON.stringify({ blocked, par, tb: ticksBlocked, tw: ticksWorkers }));
  })();
} else {
  parentPort.postMessage(countPrimes(workerData.lo, workerData.hi, workerData.base));
}
primes below 50,000,000 : 3001134 (main thread) and 3001134 (4 workers)
timer ticks while the main thread computed: almost none (<= 2)
timer ticks while 4 workers computed: many (>= 5)
segments: 0-12500000, 12500000-25000000, 25000000-37500000, 37500000-50000000

Both ways found 3,001,134 primes below 50,000,000: first on the main thread, then split into four ranges of 12.5 million numbers and run by four workers, whose counts were added. The two answers are identical, and equal to 3,001,134, the number that NumPy’s sieve found independently, and to the published value of the prime counting function for 50 million. If the segmenting had a one-off error at a boundary, the sum would be off by a few, so an exact match is meaningful.

The more important result is the responsiveness. A timer ticking every 10 milliseconds ran while each version worked. While the main thread computed, it could not tick: the count was 1 (the first tick can slip in before the computation starts), because the single thread was busy until it finished. While the four workers computed, the main thread was free and the timer ticked 21 times, so a web server doing the same job in workers would keep answering requests while the calculation went on. That is the point of workers. They may also finish sooner, by using several cores, though that depends on the number of cores of the machine, which is why this lesson measures responsiveness and correctness, not speed.

Look at how the data moves. The worker receives its input, the range and the list of base primes, as workerData, which is copied into the new thread, and sends one number back with postMessage. Nothing is shared, so the workers cannot disturb each other or the main thread. For large results, such as an array of a million numbers, copying costs time, and transferable objects or a SharedArrayBuffer avoid it, with the price that shared memory needs careful synchronisation. Pools of long-lived workers, handled by libraries, avoid the cost of starting a thread for every task.

Independent check: the answer was computed in a different language with a different algorithm, the full sieve of Eratosthenes in NumPy over the whole range at once, and it matches the Node.js result exactly. The responsiveness claim is a measurement taken in the script itself, with thresholds that leave a generous margin, since exact tick counts depend on the machine.

Check by hand with a small case: the primes below 30 are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29, ten of them. The four ranges here are 0 to 12.5 million, 12.5 to 25 million, 25 to 37.5 million and 37.5 to 50 million, and each worker marks the multiples of the base primes up to 7,072, the square root of 50 million, in its own range.

Workers are not free

Starting a worker takes tens of milliseconds and some memory. Use them for work that takes long enough to repay that, and reuse workers for many small tasks.

Measure responsiveness, not only speed

The aim of a worker is often to keep the main thread free for requests. Check that with a timer, as the lesson does, and measure request latency under load.

About this course

Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation. The number of cores and the speed differ between machines, so the lesson asserts correctness and responsiveness only. For several processes instead of threads, see the child_process and cluster modules.

Practice

Count the primes below 10 million with 2, 4 and 8 workers and compare the times on your machine. Send progress messages from a worker every million numbers. Move the prime counting of the web service from lesson 7 into a worker.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Why does CPU-heavy code hurt a Node server?

  1. Node cannot compute
  2. It uses the network
  3. It closes the port
  4. It blocks the single JavaScript thread

Other requests wait.

How do threads communicate in worker_threads?

  1. By global variables
  2. By files only
  3. By messages with postMessage
  4. By the DOM

Data is copied unless shared explicitly.

Why compare with NumPy?

  1. NumPy is faster
  2. Node cannot count
  3. An independent algorithm confirms the count
  4. It is required

Known answer: 3,001,134.

Why did the timer tick during the workers’ run?

  1. Workers are timers
  2. The main thread was free
  3. The timer ran in a worker
  4. Ticks are random

That is the purpose.

When are workers worthwhile?

  1. For every function
  2. For work that takes long enough to repay their start-up cost
  3. For tiny tasks
  4. Never

Tens of milliseconds or more.

Summary

  • Heavy computation blocks the single thread; workers move it elsewhere.
  • Split a job, run the parts in workers, and combine the results.
  • Workers communicate by messages and do not share variables.
  • Verify with a known value and an independent algorithm.

Next lesson

Lesson 12 is the capstone: a complete Node.js project.

Questions

Are worker threads the same as child processes?

No. Threads share the process and can share memory buffers, and child processes are separate programs with their own memory and communicate by pipes or messages. Both can use more cores.

Can workers access the same variables?

No, each has its own copy. Only a SharedArrayBuffer is shared, and it needs synchronisation, for example with Atomics.

Does Node use threads internally?

Yes, for file system and some crypto and DNS work, in a hidden pool, and your JavaScript still runs on one thread.

Progress is saved in this browser.