ConcurrencyTypeScriptverifiedVerified

Thread Pool Pattern in TypeScript

Maintain a fixed set of reusable worker threads that pick up tasks from a queue, avoiding the overhead of spawning a new thread per task.

How to Implement the Thread Pool Pattern in TypeScript

1Step 1: Define the task type

type Task<T> = () => Promise<T>;

2Step 2: Implement the pool with queuing and dispatch

class ThreadPool {
  private queue: Array<{
    task: Task<unknown>;
    resolve: (v: unknown) => void;
    reject: (e: unknown) => void;
  }> = [];
  private activeCount = 0;

  constructor(private size: number) {}

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

  private dispatch(): void {
    while (this.activeCount < this.size && this.queue.length > 0) {
      const entry = this.queue.shift()!;
      this.activeCount++;

      entry.task()
        .then(entry.resolve)
        .catch(entry.reject)
        .finally(() => {
          this.activeCount--;
          this.dispatch();
        });
    }
  }

  get pending(): number { return this.queue.length; }
  get active(): number { return this.activeCount; }
}

3Step 3: Submit tasks and observe pooled execution

const pool = new ThreadPool(4);

const results = await Promise.all(
  Array.from({ length: 10 }, (_, i) =>
    pool.submit(async () => {
      await new Promise(r => setTimeout(r, Math.random() * 100));
      return `task-${i}-done`;
    })
  )
);

console.log(results);

Thread Pool Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Thread Pool Pattern in the Real World

A hotel concierge desk staffed by three concierges represents the thread pool. No matter how many guests check in, only three requests are handled simultaneously. Other guests wait in the lobby queue. When a concierge finishes, they immediately assist the next waiting guest — the staff are never created or dismissed per guest, they simply stay on duty.