← Back to Node.js, page 2

nodejs-0038 · Hard senior

How would you build a small worker pool for CPU-bound tasks?

Start a fixed number of workers (about the CPU count), keep a queue of tasks, and give each task to an idle worker. When a worker finishes, resolve that task's promise and take the next queued task. Handle worker errors by rejecting the task and replacing the worker, and terminate all workers on shutdown.

Full answer

Starting a worker for every task is slow and can use all the memory. A pool fixes both.

Design:

  1. Size: os.availableParallelism() for CPU-bound work (or one less, to leave a core for the main thread).
  2. Workers: created once, kept alive, waiting for messages.
  3. Queue: tasks that arrive when all workers are busy wait in a FIFO array. For protection, limit its length and reject new tasks when it is full. That gives the caller backpressure instead of unbounded memory growth.
  4. Dispatch: pool.run(data) returns a promise. If a worker is idle, send the task. If not, queue it. When a worker replies, resolve the matching promise, mark the worker idle, and start the next queued task.
  5. Failure: if a worker emits 'error' or exits, reject its current task and start a replacement. Add a timeout per task and terminate a stuck worker.
  6. Shutdown: stop accepting tasks, wait for running ones, then terminate all workers. Workers keep the process alive until they are terminated.

Matching replies to tasks is simple when each worker handles one task at a time. For several tasks per worker, add an id to each message.

Production libraries such as Piscina implement this with extras (task cancellation, resource limits, transferable support). In an interview, the structure above, with an explanation of the queue and failure handling, is the expected depth.

javascript
const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (isMainThread) {
  class Pool {
    constructor(size) {
      this.queue = [];
      this.idle = [];
      this.all = [];
      this.running = 0;
      this.maxRunning = 0;
      for (let i = 0; i < size; i++) {
        const worker = new Worker(__filename);
        this.all.push(worker);
        this.idle.push(worker);
      }
    }
    run(n) {
      return new Promise((resolve, reject) => {
        this.queue.push({ n, resolve, reject });
        this.#dispatch();
      });
    }
    #dispatch() {
      while (this.idle.length > 0 && this.queue.length > 0) {
        const worker = this.idle.pop();
        const job = this.queue.shift();
        this.running++;
        this.maxRunning = Math.max(this.maxRunning, this.running);
        const onMessage = (result) => {
          worker.off('error', onError);
          this.running--;
          this.idle.push(worker);
          job.resolve(result);
          this.#dispatch();
        };
        const onError = (err) => {
          worker.off('message', onMessage);
          this.running--;
          job.reject(err); // a real pool would also replace the dead worker here
        };
        worker.once('message', onMessage);
        worker.once('error', onError);
        worker.postMessage(job.n);
      }
    }
    close() {
      return Promise.all(this.all.map((w) => w.terminate()));
    }
  }

  const pool = new Pool(2);
  const sizes = [1000, 2000, 3000, 4000, 5000, 6000];
  Promise.all(sizes.map((n) => pool.run(n))).then(async (results) => {
    console.log('sum of 1..n for each task:', results);
    console.log('tasks:', sizes.length, '| most tasks running at once:', pool.maxRunning);
    await pool.close();
  });
} else {
  parentPort.on('message', (n) => {
    let sum = 0;
    for (let i = 1; i <= n; i++) sum += i;
    parentPort.postMessage(sum);
  });
}

Six tasks share two workers, so no more than two run at the same time. A production pool would also add a task timeout and replace crashed workers, as listed in the answer. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): sum of 1..n for each task: [ 500500, 2001000, 4501500, 8002000, 12502500, 18003000 ] tasks: 6 | most tasks running at once: 2

Key points

  • Fixed number of long-lived workers plus a FIFO queue.
  • A task is a promise resolved by the worker's reply.
  • Handle errors, timeouts and replacement of dead workers.
  • Bound the queue to apply backpressure.
  • Terminate workers on shutdown, or the process will not exit.

Common mistakes

  • Creating a new worker for each request.
  • Leaving idle workers alive so the process never exits.
  • Letting the queue grow without a limit.
  • Ignoring worker crashes, which silently reduces capacity.

Follow-ups

  • How would you add per-task timeouts?
  • How would you prioritise urgent tasks?
  • When would you pick Piscina instead of your own pool?

Tips

  • Say the queue limit out loud. It shows you think about overload.
  • Describe failure handling before the interviewer asks.
  • Mention that workers must be terminated for a clean exit.