← Back to JavaScript, page 10

javascript-0198 · Hard senior

How would you build a worker pool that runs CPU-heavy tasks in parallel with a limit, a queue, and error handling?

Start a fixed number of workers, keep an idle list and a task queue, give each task an id, send it to an idle worker with postMessage, resolve the matching promise when the worker replies, and give the worker the next queued task. Handle task errors, worker crashes, timeouts, and a close method that waits for running tasks. The pool size should be close to the number of CPU cores.

Full answer

JavaScript runs one thread of code, so CPU-heavy work such as hashing, image processing, or parsing blocks the event loop. Workers (Worker in browsers, worker_threads in Node.js) run code in parallel threads and communicate by messages. Creating a worker is expensive, so a pool reuses a fixed set of them.

Pool design:

  1. Size: about the number of cores (navigator.hardwareConcurrency or os.availableParallelism()), leaving one core for the main thread when the main thread is busy. More workers than cores do not speed up CPU work.
  2. Queue: tasks wait in a FIFO queue when all workers are busy. Optionally add priorities and a maximum queue length that rejects new tasks for backpressure.
  3. Protocol: send { id, payload } and receive { id, result } or { id, error }. A map from id to { resolve, reject } links replies to promises. A worker handles one task at a time, so it is easy to track which task it is running.
  4. Errors: a task that throws returns an error message and the worker stays alive. An uncaught exception or exit kills the worker: reject its current task, replace the worker, and continue.
  5. Timeouts and cancellation: for runaway tasks, terminate the worker and start a new one, because a synchronous loop cannot be interrupted any other way. Support an AbortSignal for queued tasks.
  6. Data transfer: messages are copied with structured clone, which costs time for big data. Use transferables (ArrayBuffer) to move data without copying, or SharedArrayBuffer with care.
  7. Shutdown: close() stops accepting tasks, waits for running tasks, and terminates workers so the process or page can exit.
  8. When not to use it: I/O-bound work is already concurrent through the event loop, and small tasks may cost more in message passing than they save.

Measure: compare total time with and without the pool on a real workload, since startup and copying overhead can erase the gains.

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

const workerSource = `
  const { parentPort } = require('node:worker_threads');
  const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
  parentPort.on('message', ({ id, task }) => {
    try {
      if (task.type === 'fib') parentPort.postMessage({ id, result: fib(task.n) });
      else if (task.type === 'sleep') setTimeout(() => parentPort.postMessage({ id, result: 'slept ' + task.ms }), task.ms);
      else throw new RangeError('unknown task ' + task.type);
    } catch (error) {
      parentPort.postMessage({ id, error: error.name + ': ' + error.message });
    }
  });
`;

class WorkerPool {
  #workers = [];
  #idle = [];
  #queue = [];
  #pending = new Map();
  #nextId = 0;
  #closed = false;
  active = 0;
  maxActive = 0;

  constructor(size) {
    for (let i = 0; i < size; i++) this.#spawn();
  }

  #spawn() {
    const worker = new Worker(workerSource, { eval: true });
    worker.on('message', ({ id, result, error }) => {
      const entry = this.#pending.get(id);
      this.#pending.delete(id);
      this.active--;
      error ? entry.reject(new Error(error)) : entry.resolve(result);
      this.#release(worker);
    });
    worker.on('error', (error) => {
      const id = worker.currentId;
      if (id !== undefined && this.#pending.has(id)) {
        this.#pending.get(id).reject(error);
        this.#pending.delete(id);
        this.active--;
      }
    });
    this.#workers.push(worker);
    this.#idle.push(worker);
  }

  #release(worker) {
    worker.currentId = undefined;
    this.#idle.push(worker);
    this.#next();
  }

  #next() {
    while (this.#idle.length && this.#queue.length) {
      const worker = this.#idle.pop();
      const { id, task } = this.#queue.shift();
      worker.currentId = id;
      this.active++;
      this.maxActive = Math.max(this.maxActive, this.active);
      worker.postMessage({ id, task });
    }
  }

  run(task) {
    if (this.#closed) return Promise.reject(new Error('pool is closed'));
    return new Promise((resolve, reject) => {
      const id = this.#nextId++;
      this.#pending.set(id, { resolve, reject });
      this.#queue.push({ id, task });
      this.#next();
    });
  }

  async close() {
    this.#closed = true;
    while (this.#pending.size) await new Promise((resolve) => setTimeout(resolve, 5));
    await Promise.all(this.#workers.map((worker) => worker.terminate()));
  }
}

(async () => {
  const pool = new WorkerPool(2);
  const tasks = [20, 25, 10, 30, 15, 22].map((n) => pool.run({ type: 'fib', n }));
  console.log('results in submission order:', await Promise.all(tasks));

  const sleeps = await Promise.all([1, 2, 3, 4].map(() => pool.run({ type: 'sleep', ms: 30 })));
  console.log('sleep tasks:', sleeps.length, '| most tasks running at once:', pool.maxActive, '(pool size 2)');

  const settled = await Promise.allSettled([pool.run({ type: 'nope' }), pool.run({ type: 'fib', n: 5 })]);
  console.log('error does not stop the pool:', settled.map((r) => (r.status === 'fulfilled' ? r.value : r.reason.message)));

  await pool.close();
  console.log('after close:', await pool.run({ type: 'fib', n: 1 }).catch((e) => e.message));
})();

Run with Node.js v24.22.1 as js-198.js; two runs gave identical output. Output: results in submission order: [ 6765, 75025, 55, 832040, 610, 17711 ] sleep tasks: 4 | most tasks running at once: 2 (pool size 2) error does not stop the pool: [ 'RangeError: unknown task nope', 5 ] after close: pool is closed

Key points

  • Workers run CPU-heavy code in parallel; a pool reuses a fixed number of them.
  • Queue tasks; send each to an idle worker and match replies by id.
  • Task errors reject the promise; crashed workers are replaced; timeouts terminate the worker.
  • Use transferables for large data; close the pool to let the process exit.
  • Do not use workers for I/O-bound or tiny tasks.

Common mistakes

  • Creating a new worker for every task.
  • Starting more workers than CPU cores for CPU-bound work.
  • Sending huge data by copy instead of transferring it.
  • Forgetting to terminate workers, which keeps the process alive.

Follow-ups

  • How would you handle a task that runs forever?
  • When would a SharedArrayBuffer help?
  • How does this differ from the browser Web Worker API?

Tips

  • State the pool size rule and why more is not better.
  • Describe the id based message protocol.
  • Mention that I/O-bound work does not need workers.