Node Worker Threads Pool for CPU Tasks

Offload CPU-bound work to a pool of worker threads with Piscina-style sizing, transferable buffers, and graceful pool shutdown.

JavascriptNodeResilience

Code

javascriptsnippet
56 lines
import { Worker } from 'node:worker_threads';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
parentPort.postMessage({ input: workerData.n, result: fib(workerData.n) });
`;

class WorkerPool {
  constructor(size) {
    this.size = size;
    this.workers = [];
    this.queue = [];
    this.busy = new Set();
  }

  async init() {
    const dir = await mkdtemp(join(tmpdir(), 'pool-'));
    this.file = join(dir, 'worker.js');
    await writeFile(this.file, WORKER_SOURCE, 'utf8');
    for (let i = 0; i < this.size; i++) this.workers.push(new Worker(this.file));
  }

  run(n) {
    return new Promise((resolve, reject) => {
      this.queue.push({ n, resolve, reject });
      this.dispatch();
    });
  }

  dispatch() {
    while (this.queue.length > 0 && this.busy.size < this.size) {
      const job = this.queue.shift();
      const worker = this.workers.find((w) => !this.busy.has(w));
      this.busy.add(worker);
      worker.once('message', (msg) => {
        this.busy.delete(worker);
        job.resolve(msg.result);
        this.dispatch();
      });
      worker.postMessage({ n: job.n });
    }
  }

  async destroy() {
    await Promise.all(this.workers.map((w) => w.terminate()));
  }
}

const pool = new WorkerPool(4);
await pool.init();
console.log(await pool.run(35));
await pool.destroy();

Inside the snippet

Structurally, expect the class WorkerPool and the function fib and nothing else.

The nesting pairs for (let i = 0; i < this.size; i++) this.workers.push(new Worker(this.file)); with while (this.queue.length > 0 && this.busy.size < this.size) — the inner runs once per outer step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:worker_threads, node:fs/promises, node:os, a Node.js built-in, exposing Worker, mkdtemp, writeFile, tmpdir, join.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • node:worker_threads is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

The main signature reads function fib(n)

Key statements

await Promise.all(this.workers.map((w) => w.terminate()));
return new Promise((resolve, reject) => {
  this.queue.push({ n, resolve, reject });
  this.dispatch();
});
function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

Interactive Tools for This Topic

FAQ

Does `fib` modify its input?
No mutation happens — the function reads its input and returns a new value.
Is the imported module an npm package?
No — `node:worker_threads` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.