Worker threads

Topic 1 of 4 in Performance & scaling7 min readIntermediateFree course

Overview

You learned in How Node.js works that your JavaScript runs on one main thread. That’s perfect for I/O-heavy servers. But some tasks are CPU-heavy: resizing images in JavaScript, generating large reports, parsing huge files, compressing data, complex calculations. While they run, the event loop is blocked and every other request waits.

Worker threads let you run JavaScript on additional threads — and therefore additional CPU cores — while the main thread stays free to handle requests.

The main thread runs the event loop and handles requests, staying responsive. It sends jobs with postMessage to Worker 1, 2 and 3, which resize images, hash or parse, and receive results back through ‘message’ events. Each worker has its own event loop and memory; data is copied or transferred between them.

When to use them

Work Use worker threads?
Waiting for a database, API or file No — that’s already non-blocking
Hashing a password with crypto.scrypt No — the async version already runs in libuv’s pool
A JavaScript loop that takes 300 ms of CPU Yes
Parsing/transforming a large dataset in JS Yes
Image or PDF processing in pure JavaScript Yes (or a native library, or a job queue)

The first question is always: is my code actually busy computing, or just waiting? Only computing benefits from threads.

A first worker

A worker is a separate JavaScript file that runs in its own thread:

JavaScript
// fib-worker.js
import { parentPort, workerData } from 'node:worker_threads';

function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}

parentPort.postMessage(fib(workerData.n));
JavaScript
// main.js
import { Worker } from 'node:worker_threads';

function runFib(n) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL('./fib-worker.js', import.meta.url), {
      workerData: { n },
    });
    worker.once('message', resolve);
    worker.once('error', reject);
  });
}

console.log(await runFib(40)); // computed on another thread
  • workerData passes initial input.
  • parentPort.postMessage(value) sends a message from the worker to the main thread.
  • The main thread listens with worker.on('message', …), and can send messages back with worker.postMessage(…).
  • The worker exits when it has nothing left to do (or call worker.terminate()).

In an Express route

JavaScript
app.get('/reports/:year', async (req, res) => {
  const report = await runInWorker('./report-worker.js', { year: Number(req.params.year) });
  res.json(report);
});

The route still awaits, but the event loop is free while the worker computes — other users’ requests are served normally.

Isolation and messages

Workers are well isolated: each has its own event loop, memory and copy of every module. Variables aren’t shared. Messages are copied using the structured clone algorithm (the same one as structuredClone) — so you can send objects, arrays, Maps, Dates and Buffers, but not functions or class instances with their methods.

Copying a 200 MB buffer is slow. You can transfer it instead — ownership moves to the other thread, with no copy:

JavaScript
const pixels = new Uint8Array(1024 * 1024 * 50);
worker.postMessage({ pixels }, [pixels.buffer]); // pixels is now unusable in the main thread

For truly shared memory, SharedArrayBuffer with Atomics lets threads read and write the same bytes — powerful, but you then have to think about concurrent access, so reach for it rarely.

Use a pool

Starting a worker takes tens of milliseconds and several megabytes. Starting one per request would waste that. A worker pool creates a few workers once and hands them tasks from a queue. Piscina is the popular choice:

Terminal
npm install piscina
JavaScript
// thumbnail-task.js — export the work as a function
export default function makeThumbnail({ pixels, width }) {
  // …CPU-heavy work…
  return result;
}
JavaScript
// main.js
import { Piscina } from 'piscina';
import os from 'node:os';

const pool = new Piscina({
  filename: new URL('./thumbnail-task.js', import.meta.url).href,
  maxThreads: os.availableParallelism() - 1, // leave a core for the main thread
});

app.post('/thumbnails', async (req, res) => {
  res.json(await pool.run({ pixels: req.body.pixels, width: 200 }));
});

The pool queues tasks when all workers are busy, so a burst of requests can’t create a hundred threads.

Workers or a job queue?

Worker threads keep work inside the request: the user waits, but the server stays responsive. If the user doesn’t need the result immediately (sending a PDF by email, for example), a background job (see Background jobs) is often better — it survives restarts, can retry, and runs on separate machines.

Worker threads Background jobs
User waits for the result yes no
Survives a restart no yes
Runs on other machines no yes
Good for CPU work under a few seconds slow, retryable, not-urgent work

Measure first. Moving work to a worker adds complexity and message-passing overhead. Profile (see Profiling and performance) to confirm the event loop really is blocked before reaching for threads.

Exercise

Offload a heavy calculation

Write primes-worker.js that counts the primes below workerData.limit and posts the result back. Then write countPrimes(limit) in the main file that runs the worker and returns a promise of the count. Show that a setInterval tick keeps running while the worker computes.

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

export function countPrimes(limit) {
  // your code here
}

Summary

  • CPU-heavy JavaScript blocks the event loop; worker threads run it on other CPU cores.
  • Each worker has its own event loop and memory; communicate with postMessage and 'message' events.
  • Data is copied between threads (structured clone); large buffers can be transferred instead.
  • Starting a worker costs time and memory — reuse workers with a pool such as Piscina.
  • Don’t use workers for I/O: Node is already asynchronous for files and networking.