How-To Guide

How to Implement a Worker Pool

Build a worker pool: spawn a fixed set, distribute tasks, collect results in order or as they finish, and handle a worker that crashes.

On this page

  1. Introduction
  2. Fix the pool size to the limiting resource
  3. Distribute tasks and collect results
  4. Handle a worker that fails
  5. Backpressure and shutdown
  6. Test the cap, ordering, and failures
  7. Common pitfalls
  8. Conclusion

Introduction

A worker pool runs a fixed set of workers and feeds them tasks from a queue, so concurrency is bounded and the cost of starting a worker is paid once rather than per task. It is the right shape for CPU-bound work that would otherwise block the event loop, and for any work whose concurrency must be capped to protect a downstream. Spawning per task is simple but pays the startup cost each time and offers no ceiling, so a burst spawns unbounded workers or goroutines.

This tutorial builds a worker pool: a fixed set of workers, a queue of tasks, a way to collect results in the order the caller needs, and recovery when a worker exits. It uses worker threads for CPU work, but the queue-and-fixed-set structure applies to a pool of goroutines, threads, or processes.

Fix the pool size to the limiting resource

The pool size is the maximum concurrency, so choose it from the resource that limits throughput. For CPU-bound work, that is the number of cores; more workers add context switching without adding throughput. For IO-bound work, the limit is often a downstream’s capacity or an external rate limit, so the pool size is the number of concurrent calls that resource can accept.

Keep the size fixed rather than growing with the load. A fixed pool bounds the concurrency and the memory, and it makes the load on the downstream predictable. If the queue grows, that is a signal that the pool is saturated, and the caller can shed, wait, or scale the pool deliberately rather than spawning workers under pressure.

import { Worker } from 'node:worker_threads';
import os from 'node:os';

const POOL_SIZE = Math.max(1, os.cpus().length - 1);   // leave a core for the loop

function createPool(size) {
  const idle = [];
  const queue = [];
  for (let i = 0; i < size; i++) idle.push(new Worker('./worker.js'));
  return { idle, queue };
}

Distribute tasks and collect results

A task carries its payload and a callback or a promise resolver. When a worker is free and the queue is non-empty, dequeue the next task and hand it to the worker; when the worker finishes, return it to the idle set and hand it the next task. This keeps every worker busy while the queue holds the excess, bounded by the pool size.

Collect results either in submission order or as they complete. For ordered results, tag each task with its index and store the result at that index, so the caller receives an array in the original order even though the workers finished out of order. For completion order, resolve each task’s promise as it finishes, so the caller processes results as they arrive, which is faster when the order does not matter.

class Pool {
  private idle: Worker[] = [];
  private queue: { input: unknown; resolve: (v: unknown) => void; reject: (e: unknown) => void }[] = [];
  constructor(size: number) { for (let i = 0; i < size; i++) this.idle.push(new Worker('./worker.js')); }

  run<T>(input: unknown): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.queue.push({ input, resolve: resolve as (v: unknown) => void, reject });
      this.dispatch();
    });
  }

  private dispatch() {
    while (this.idle.length > 0 && this.queue.length > 0) {
      const worker = this.idle.pop()!;
      const job = this.queue.shift()!;
      const onMessage = (out: unknown) => { worker.off('message', onMessage); this.idle.push(worker); job.resolve(out); this.dispatch(); };
      worker.once('message', onMessage);
      worker.postMessage(job.input);
    }
  }
}

Handle a worker that fails

A worker can exit unexpectedly, throw, or hang. Listen for the exit and error events so a dead worker is noticed, remove it from the pool, and either replace it with a fresh one or reduce the pool size and surface the failure. A worker that dies silently would leave its task’s promise unresolved, so the pool must fail that task rather than hang.

Decide whether to retry the failed task. A worker crash may be deterministic for a bad input, so an unbounded retry loops forever. Retry once or twice with a fresh worker, and if it fails again, reject the task so the caller sees the error. Also bound the task duration with a timeout, because a hung worker holds a pool slot forever; on timeout, terminate the worker and reject the task.

function trackWorker(worker, pool, currentJob) {
  worker.on('exit', (code) => {
    if (code !== 0) {
      currentJob?.reject(new Error('worker exited with ' + code));
      const idx = pool.idle.indexOf(worker);
      if (idx >= 0) pool.idle.splice(idx, 1);
      pool.idle.push(new Worker('./worker.js'));   // replace the dead worker
    }
  });
  worker.on('error', (err) => currentJob?.reject(err));
}

Backpressure and shutdown

A queue that grows without bound under a burst is a memory leak. Bound the queue and apply backpressure: when it is full, the submitter waits or the pool rejects with a clear error, so the caller decides whether to slow or shed. This is the same backpressure principle as for streams, applied to the pool’s input.

On shutdown, stop accepting new tasks, drain the queue, and terminate the workers once the current tasks finish. A hard terminate mid-task loses the work and can leave a partial side effect, so drain first and wait for the in-flight tasks, then close. Keep the shutdown path in the pool so every caller stops consistently.

Test the cap, ordering, and failures

Submit more tasks than the pool size and assert that no more than the pool size run concurrently, by instrumenting the workers to report start and end. Test that ordered results come back in submission order. Test that a worker killed mid-task fails that task and the pool replaces the worker and continues with the rest. Test that a hung worker is timed out and its slot is freed.

node -e '
const { Pool } = require("./pool");
const p = new Pool(4);
const tasks = Array.from({ length: 100 }, (_, i) => p.run({ i }));
// instrument worker start/end; assert max concurrency <= 4 and all 100 resolve in order
Promise.all(tasks).then((r) => console.log("ordered:", r[0].i === 0 && r.length === 100));
'

Common pitfalls

Spawning a worker per task so the startup cost is paid each time, a pool larger than the limiting resource, an unbounded queue that leaks memory under a burst, no listener for a worker that exits so a task hangs, and a hard terminate that loses in-flight work are the recurring mistakes. A fixed pool sized to the resource, a bounded queue with backpressure, exit and error handling with replacement, task timeouts, and a draining shutdown address them.

Conclusion

A worker pool bounds concurrency with a fixed set of workers feeding from a queue. Size the pool to the limiting resource, distribute and collect in the order the caller needs, replace and fail tasks when a worker dies, bound the queue with backpressure, and drain on shutdown. Self-check by submitting more tasks than workers and asserting the concurrency cap and ordered results. Then CPU-bound work runs off the main loop with predictable load.

Sources: Node.js: Worker threads, MDN: Web Workers API, Go: Worker pools with goroutines.

FAQ

How many workers should a pool have?
For CPU-bound work, about the number of cores, so the pool uses the machine without excessive context switching. For IO-bound work, more, because each worker waits often. Tie the size to the resource that limits throughput, not to a guess.
Ordered results or completion order?
If a caller submits an array and expects results positionally, preserve submission order by tagging each result and reassembling. If the caller processes each result as it is ready, use completion order and skip the reassembly, which finishes sooner.

Related Examples