---
title: "When should I use worker threads in Node.js?"
description: "Use worker threads for heavy CPU work like image processing, parsing or hashing that would block the event loop. They do not speed up I/O such as database or network calls."
url: https://www.danny.engineering/answer/nodejs/when-should-i-use-worker-threads-in-nodejs
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Node.js"]
---

# When should I use worker threads in Node.js?

## The short answer


Use worker threads when a piece of synchronous, CPU-heavy JavaScript blocks the event loop long enough to slow down other requests. Do not use them for I/O such as database queries, file reads or HTTP calls, because Node.js already handles those without blocking.


```javascript
import { Worker } from 'node:worker_threads';

const worker = new Worker(new URL('./resize.js', import.meta.url), {
  workerData: { path: 'photo.jpg' },
});

worker.once('message', (result) => console.log('Done', result));
worker.once('error', (err) => console.error(err));
```


## Why it happens


Node.js runs your JavaScript on a single thread with an event loop. While one callback runs, nothing else does. That is fine for I/O, because a call like `fetch` or `readFile` hands the work to the operating system or libuv's thread pool and returns straight away. Your thread is free to serve other requests while it waits.


CPU work is different. Parsing a 50 MB JSON file, resizing an image in pure JavaScript, compressing data synchronously or running a slow regular expression keeps the thread busy. Every other request waits until it finishes. If one request takes 2 seconds of CPU, every other user waits 2 seconds too.


A worker thread is a separate JavaScript environment with its own event loop and memory, running in parallel on another CPU core in the same process. Moving the heavy work there keeps the main thread responsive.


## How to fix it


### Move CPU work into a worker


The worker file receives input through `workerData` and replies with `postMessage`.


```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));
```


Wrap it in a promise so the rest of your code can `await` it:


```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);
    worker.once('exit', (code) => {
      if (code !== 0) reject(new Error(`Worker stopped with code ${code}`));
    });
  });
}

console.log(await runFib(40));
```


### Use a pool for repeated work


Starting a worker takes time and memory, since each one boots its own JavaScript engine instance. Creating one per request is wasteful. For a server, keep a fixed pool of workers, usually about one per CPU core, and send jobs to them. The [Piscina](https://github.com/piscinajs/piscina) library is a popular, well maintained pool, so you do not need to write the queueing yourself.


You can check how many cores are available with `os.availableParallelism()`.


### Share or transfer large data


Messages between threads are copied using the structured clone algorithm. For large binary data, transfer it instead of copying, so the worker takes ownership of the memory:


```javascript
const buffer = new ArrayBuffer(100 * 1024 * 1024);
worker.postMessage({ buffer }, [buffer]);
// buffer is now unusable on the main thread
```


If several threads need the same data at once, use a `SharedArrayBuffer` with `Atomics` for coordination.


### Know the alternatives

- **I/O-bound work:** stay on the main thread and use `async` code. Workers add overhead and no speed.
- **Running another program:** use `child_process`, for example to call `ffmpeg`.
- **Using every core for an HTTP server:** run several processes with the `cluster` module, a process manager, or more containers. Each process handles its own requests.
- **Built-in heavy tasks:** many APIs already run off the main thread, such as the async versions of `crypto.pbkdf2`, `crypto.scrypt` and `zlib` functions. Use those before reaching for a worker.

## Common pitfalls

- **Expecting faster database calls.** Workers do not make I/O quicker. Measure first: if the event loop is not blocked, workers will not help.
- **Sending functions or class instances.** Structured clone cannot copy functions, and class instances lose their methods. Send plain data.
- **Forgetting error handling.** An uncaught exception in a worker emits `error` on the `Worker` object. Listen for it, or the promise never settles.
- **One worker per request.** Under load this creates hundreds of threads and lots of memory use. Use a pool.
- **Assuming shared state.** Each worker has its own globals and module cache. A variable changed in a worker does not change in the main thread.

## Related reading

- [Node.js: Worker threads](https://nodejs.org/api/worker_threads.html)
- [Node.js: Don't block the event loop](https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop)
