How-To Guide

How to Use Worker Threads for CPU-Bound Work

Move heavy computation off the event loop with worker threads so request latency stays low under load.

On this page

  1. Introduction
  2. Why the Event Loop Blocks
  3. Running Work in a Worker Thread
  4. Pooling Workers
  5. Transferring Data Without Copying
  6. Choosing Between Worker Threads and Processes
  7. Limits and Pitfalls
  8. Conclusion

Introduction

Node.js runs JavaScript on a single thread. That is a benefit for most workloads because there is no lock contention, but it is a liability for CPU-bound work: a function that hashes a large file or resizes an image blocks the event loop for its entire duration, and every request waiting for that loop stalls. Worker threads let you run such work on a separate thread with its own event loop, so the main thread keeps serving requests while the computation proceeds. This article shows how to offload CPU-bound work to a worker, pool workers so you do not pay thread startup per task, transfer data without copying it, and decide when a worker is worth the complexity.

Why the Event Loop Blocks

The event loop processes callbacks one at a time. A synchronous computation, however short it looks, occupies it for the whole computation; nothing else runs. Regular expressions with catastrophic backtracking, JSON serialization of a huge object, image encoding, cryptographic hashing and CSV parsing of a large file are all typical offenders. The symptom is a lag that grows with load: p99 latency rises, health checks time out, and the process looks hung even though no single request is slow in isolation.

Asynchronous APIs do not help, because the CPU work is synchronous off the network but still synchronous in the process. Awaiting a function that does synchronous work only yields before and after it, not during it. The only way to free the loop is to run the computation on another thread or in another process.

Running Work in a Worker Thread

A worker thread runs a separate JavaScript context with its own event loop and its own memory heap. You pass it a file to execute and communicate by message passing. The main thread sends the input, the worker does the synchronous computation, and the result comes back as a message. The main loop never blocks because the work ran elsewhere.

// worker.js
const { parentPort, workerData } = require('node:worker_threads');
const { createHash } = require('node:crypto');

function hashFile(buffer) {
  const hash = createHash('sha256');
  hash.update(buffer);
  return hash.digest('hex');
}

parentPort.postMessage(hashFile(workerData.buffer));

Pooling Workers

Spawning a worker per task pays thread startup, module loading and heap allocation on every call, which can dominate short tasks. A pool keeps a fixed number of workers alive and dispatches tasks to idle ones, exactly like a thread pool in other runtimes. Reuse also keeps the worker warm, so the JIT has already optimized the hot path.

const { Worker } = require('node:worker_threads');

class WorkerPool {
  constructor(size, workerPath) {
    this.workerPath = workerPath;
    this.idle = [];
    this.queue = [];
    for (let i = 0; i < size; i++) this.idle.push(this.#spawn());
  }
  #spawn() {
    const worker = new Worker(this.workerPath);
    worker.on('message', (result) => {
      const job = worker.current;
      worker.current = null;
      job.resolve(result);
      this.#release(worker);
    });
    worker.on('error', (err) => {
      if (worker.current) worker.current.reject(err);
      worker.current = null;
      this.#release(this.#spawn());
    });
    return worker;
  }
  #release(worker) {
    const next = this.queue.shift();
    if (next) this.#dispatch(worker, next);
    else this.idle.push(worker);
  }
  #dispatch(worker, job) {
    worker.current = job;
    worker.postMessage(job.payload);
  }
  run(payload) {
    return new Promise((resolve, reject) => {
      const job = { payload, resolve, reject };
      const worker = this.idle.pop();
      if (worker) this.#dispatch(worker, job);
      else this.queue.push(job);
    });
  }
}

Transferring Data Without Copying

By default, postMessage structured-clones the value, which copies it and costs memory and time proportional to its size. For large binary buffers, transfer the underlying ArrayBuffer instead: the ownership moves to the worker and no copy happens, but the sending side loses access, so it must not reuse that buffer. Alternatively use a SharedArrayBuffer when both sides need concurrent access, with the caveat that synchronization becomes your responsibility.

For very large inputs, avoid materializing the whole thing in memory. Pass a file path and let the worker stream the file, which keeps both threads’ memory bounded and lets the worker decide how to chunk the work. This is usually better than transferring hundreds of megabytes across the boundary.

Choosing Between Worker Threads and Processes

Worker threads share the process, so they share memory limits and crash together: an out-of-memory kill takes the whole process down. Child processes are isolated, so a crash is contained, but starting one is more expensive and communication goes through pipes. Use worker threads for CPU-bound computation inside a service that must stay responsive; use separate processes when isolation matters or the workload is a long-running job of its own.

For a service, a small pool sized to the number of CPU cores is a good default: more workers than cores only adds context switching, because the compute is CPU-bound. If the work is partly I/O, workers can be fewer than cores because each spends time waiting. Measure the throughput curve rather than guessing.

Limits and Pitfalls

Workers have real overhead, so offloading a ten-microsecond computation to one makes it slower, not faster. They are worth it only when the work is heavy enough to dominate the startup and messaging cost, typically milliseconds or more. Benchmark before and after; do not offload on principle.

Do not share mutable state across threads by accident. The main and worker heaps are separate, so a variable in one is not visible in the other; sharing requires SharedArrayBuffer and explicit synchronization, which reintroduces the concurrency hazards Node normally avoids. Keep the boundary simple: send input, get output. Finally, ensure workers are terminated on shutdown, or they keep the process alive and prevent a clean restart.

Conclusion

Worker threads move CPU-bound work off the main event loop so request latency stops depending on how heavy some other task is. Run the computation in a worker, keep a pool so thread startup is not paid per task, transfer large buffers instead of copying them, and choose threads versus processes based on whether you need isolation. Offload only work heavy enough to justify the boundary, keep the interface to input and output, and terminate workers on shutdown. The event loop stays free, and the service stays responsive under load.

Sources: Node.js: worker_threads, Node.js: don’t block the event loop, Node.js: child processes.

FAQ

When is a worker thread worth it?
When the work is synchronous and heavy enough that its cost dominates thread startup and message passing, typically milliseconds or more. Offloading a tiny computation makes it slower. Benchmark before adopting a worker.
Should I use a worker thread or a child process?
Worker threads share the process and are cheaper to start, but crash together with it. Child processes are isolated so a crash is contained, at higher startup and communication cost. Use threads for in-service computation, processes when isolation matters.

Related Examples