Skip to content

Offloading CPU-Heavy Work With Node.js Worker Threads

A practical guide to Node.js worker threads for CPU-bound tasks, with a real example of moving image processing off the main event loop.

· · 8 min read

Updated: November 27, 2026

Table comparing worker threads, child processes and the libuv thread pool by memory, cost and use

Quick Take

Worker threads run JavaScript on a separate OS thread within the same Node.js process, sharing memory efficiently and freeing the main thread to keep handling requests. Use them for CPU-bound synchronous work, image processing, heavy parsing, cryptographic hashing, not for I/O, which the event loop already handles asynchronously via libuv. Reuse a pool of workers sized to your CPU core count instead of spawning one per task, per the Node.js docs.

Worker threads are Node.js's built-in mechanism for running JavaScript on a separate OS thread inside the same process, letting CPU-heavy code run in parallel with the main event loop instead of blocking it. The Node.js event loop is famously single-threaded, and that's fine for I/O, which was never actually blocking the thread to begin with. The order queued callbacks take on that one thread is its own topic: microtasks vs macrotasks. It stops being fine the moment you run something CPU-heavy: resizing an image, parsing a huge JSON payload, compressing a file. That work runs synchronously on the one thread handling every other request, and everything else waits.

Prove the problem first

Before reaching for worker threads, confirm you actually have a CPU-bound bottleneck. This synchronous function blocks the event loop for its entire duration, no other request gets processed until it returns:

function computeExpensiveHash(data: Buffer): string {
  let hash = 0;
  for (let i = 0; i < data.length; i++) {
    hash = (hash * 31 + data[i]) >>> 0; // deliberately synchronous, CPU-bound
  }
  return hash.toString(16);
}

// This blocks every other request on the server while it runs
app.post('/upload', (req, res) => {
  const hash = computeExpensiveHash(req.body);
  res.json({ hash });
});

If a health-check endpoint on the same server slows down under load whenever /upload is hit, that's the symptom. async/await doesn't fix this, the function itself is synchronous CPU work, wrapping it in a promise doesn't move it off the thread. The Node.js guide to not blocking the event loop says each callback should complete quickly. My own rule of thumb is that any single synchronous operation longer than about 10 milliseconds is worth investigating, since it directly adds to the latency of every other request queued behind it. A naive image resize of a full-resolution camera photo in plain JavaScript is the textbook case: it holds the thread for the whole operation, and every unrelated request that lands during that window waits for it, which is how a p99 latency budget gets blown by an endpoint nobody was looking at.

A quick way to confirm the block is real before you reach for worker threads:

  1. Run the endpoint under a fixed load of 50 requests per second using an HTTP load tool
  2. Watch a second, unrelated health-check endpoint on the same process for latency spikes
  3. Add console.time() around the suspect function to measure its synchronous duration directly
  4. If the health-check spikes line up with calls to the suspect function, you have a CPU-bound block, not a slow I/O call

Moving the work to a worker thread

// hash-worker.ts
import { parentPort, workerData } from 'node:worker_threads';

function computeExpensiveHash(data: Buffer): string {
  let hash = 0;
  for (let i = 0; i < data.length; i++) {
    hash = (hash * 31 + data[i]) >>> 0;
  }
  return hash.toString(16);
}

const result = computeExpensiveHash(workerData.buffer);
parentPort?.postMessage(result);
// main.ts
import { Worker } from 'node:worker_threads';
import path from 'node:path';

function hashInWorker(data: Buffer): Promise<string> {
  return new Promise((resolve, reject) => {
    const worker = new Worker(path.resolve(import.meta.dirname, 'hash-worker.js'), {
      workerData: { buffer: data },
    });
    worker.once('message', resolve);
    worker.once('error', reject);
  });
}

app.post('/upload', async (req, res) => {
  const hash = await hashInWorker(req.body);
  res.json({ hash });
});

The main thread now awaits a promise that resolves when the worker posts its result back, and every other request keeps flowing through the event loop while that computation runs on a separate thread entirely. A message channel is the communication path Node sets up automatically between a Worker instance and its parent, letting them exchange structured-cloned data through postMessage without sharing memory directly unless you opt into a SharedArrayBuffer. Structured cloning is the cost line to watch. Every message gets copied rather than passed by reference, so shipping a 50 MB buffer to a worker means serializing 50 MB on the way in and again on the way out. Per the Node.js documentation, transferList sidesteps that for ArrayBuffer payloads by moving ownership instead of copying, which turns an expensive clone into a near-free pointer handoff. Worth reaching for any time the payload is measured in megabytes rather than kilobytes.

The main thread awaits a promise that resolves once the worker posts its result back through the message channel, so every other request keeps flowing through the event loop while the CPU-heavy computation runs on a fully separate OS thread, entirely outside the main thread's control flow.

Share this Post on X Bluesky

A worker pool instead of a worker per request

Spawning a new Worker per request has real overhead, tens of milliseconds of startup cost per worker. Under load, that overhead compounds. A pool that reuses a fixed number of long-lived workers, dispatching tasks to whichever is free, avoids it. A pooled worker stays alive and takes its input from messages instead of workerData, so it needs its own small file:

// hash-pool-worker.ts
import { parentPort } from 'node:worker_threads';

function computeExpensiveHash(data: Uint8Array): string {
  let hash = 0;
  for (let i = 0; i < data.length; i++) {
    hash = (hash * 31 + data[i]) >>> 0;
  }
  return hash.toString(16);
}

parentPort?.on('message', (data: Uint8Array) => {
  parentPort?.postMessage(computeExpensiveHash(data));
});
import { Worker } from 'node:worker_threads';
import os from 'node:os';
import path from 'node:path';

class WorkerPool {
  #queue: Array<{ data: Buffer; resolve: (v: string) => void }> = [];
  #freeWorkers: Worker[] = [];
  #running = new Map<Worker, (v: string) => void>();

  constructor(workerFile: string, size = os.cpus().length) {
    for (let i = 0; i < size; i++) {
      const worker = new Worker(workerFile);
      worker.on('message', (result: string) => {
        this.#running.get(worker)?.(result); // resolve the task this worker was given
        this.#running.delete(worker);
        this.#freeWorkers.push(worker);
        this.#runNext();
      });
      this.#freeWorkers.push(worker);
    }
  }

  run(data: Buffer): Promise<string> {
    return new Promise(resolve => {
      this.#queue.push({ data, resolve });
      this.#runNext();
    });
  }

  #runNext() {
    if (this.#queue.length === 0 || this.#freeWorkers.length === 0) {return;}
    const worker = this.#freeWorkers.shift()!;
    const task = this.#queue.shift()!;
    this.#running.set(worker, task.resolve);
    worker.postMessage(task.data);
  }
}

const pool = new WorkerPool(path.resolve(import.meta.dirname, 'hash-pool-worker.js'));

Sizing the pool to os.cpus().length means every core stays busy under sustained load without oversubscribing the CPU with more threads than there are cores to run them. Check what that call actually returns in your deployment before trusting it. Inside a container limited to 2 CPUs, os.cpus().length still reports the host's core count on most Node versions, so a pool sized from it on a 32-core host will happily spawn 32 threads to share 2 cores worth of quota. The result is worse throughput than a single thread, plus memory pressure from 32 V8 isolates, each of which carries its own heap. Read the cgroup limit or set the pool size from an environment variable instead.

Worker threads vs child processes vs the libuv pool

ApproachShares memoryStartup costBest for
Worker threadsYes (SharedArrayBuffer)Moderate (tens of ms)CPU-bound JS computation
Child processesNo, serialized IPC onlyHighRunning external programs, isolation for crash safety
libuv thread pool (built-in)N/A, internal to NodeNone, already runningFile I/O, DNS lookups, some crypto (handled automatically)

Node already uses a thread pool internally for things like fs operations and crypto.pbkdf2, you don't manage that pool yourself. Worker threads are for the CPU-bound work you write, not the I/O Node already parallelizes for you.

The 3 options split cleanly by what they isolate. The libuv thread pool, 4 threads by default and tunable through UV_THREADPOOL_SIZE, handles Node's own async file and crypto work with no API for you to touch. Worker threads run your JavaScript on separate threads inside the same process, each with its own V8 isolate and heap but a shared address space, so startup costs tens of milliseconds and message passing is cheap. Child processes give you a whole separate Node process, which is slower to start than a thread and communicates over IPC, but survives a crash in isolation and can run a different binary entirely. Pick workers for CPU-bound JavaScript, child processes for running something that isn't your app.

What goes wrong in production

Under real traffic, three things tend to surface that a laptop test doesn't show.

Unhandled worker errors take the process down. A worker that throws emits an error event on the parent's Worker object, and if nothing is listening, Node treats it as an uncaught exception. Attach worker.on('error', ...) and worker.on('exit', ...) when you create each worker, and have the exit handler replace the dead worker in the pool. Otherwise a single malformed payload retires one thread permanently, and the pool silently degrades until nothing is left to hand work to.

Memory doesn't come back the way you expect. Each worker gets its own V8 isolate and its own heap, so eight workers means roughly eight times the baseline heap before you've processed anything. On a small container that adds up before the first task arrives. Set resourceLimits: { maxOldGenerationSizeMb } per worker and size the pool against the container limit rather than against os.cpus().length, which reports the host's core count, not your cgroup quota. That mismatch is an easy way for a pool that behaved in staging to get OOM-killed in production.

Structured clone isn't free either. Passing a large object through postMessage copies it, and for a big enough payload the copy costs more than the computation you moved off the main thread. If you're passing anything above a megabyte or so, transfer an ArrayBuffer instead so ownership moves without a copy.

If you run Node with --permission, there's one more catch: a worker created with execArgv: [] drops the parent's restrictions and can read files the parent can't, which I reproduced in a permission model test.

Frequently Asked Questions

What's the difference between worker threads and child processes in Node.js?
A worker thread shares memory with the main process through SharedArrayBuffer and runs in the same process, making startup faster and communication cheaper. A child process (spawned via child_process) runs as a fully separate OS process with its own memory space, communicating only through serialized messages or pipes. Use worker threads for CPU-bound JavaScript computation; use child processes for running a separate program, a shell command, a Python script, something outside Node's own runtime.
Do worker threads help with I/O-bound work?
No, and using them for it wastes resources. Node's event loop already handles I/O, file reads, network requests, database queries, asynchronously and efficiently without blocking, because those operations are handed off to the OS or libuv's thread pool under the hood. Worker threads solve a different problem: synchronous, CPU-heavy JavaScript that would otherwise block the single main thread. Adding a worker thread around a fetch() call adds overhead with no benefit.
How many worker threads should I create?
Match the number of CPU cores available, checked via os.cpus().length, and reuse them through a worker pool rather than spawning a new worker per request. Worker threads have real startup cost, tens of milliseconds, so spawning one per incoming request under load creates its own bottleneck. A pool of workers sized to your core count, with tasks queued and dispatched to whichever worker is free, is the pattern that scales.