← Back to JavaScript, page 6

javascript-0105 · Hard senior

How do you build an async task queue with a concurrency limit and task priorities?

Keep a pending list ordered by priority (first in, first out for equal priority), a counter of running tasks, and a pump function that starts tasks while the counter is below the limit. add returns a promise for the task result, a rejected task must not stop the queue, and a promise that resolves when the queue is idle is useful. Running tasks are never interrupted by a higher priority one.

Full answer

This is the scheduler behind many upload, crawler, and API clients. It combines three ideas: a concurrency limit, a priority order, and results returned through promises.

Design:

  • add(task, priority = 0) wraps the task in a promise and stores { task, priority, order, resolve, reject }. The return value is a promise for the result, so callers can await their own task.
  • The pending list is ordered by higher priority first. For equal priority, a growing order number keeps first in, first out. A sorted insert or a binary heap keeps this efficient. For small queues, a sorted array insert is fine and easier to read.
  • #pump() runs while running < concurrency and the pending list is not empty. It takes the first item, increments running, runs the task, and in finally decrements running and pumps again.
  • A failing task rejects its own promise only. The queue continues. Never let one task's error escape into the pump.
  • onIdle() returns a promise that resolves when nothing is running or pending. It is useful for tests and for shutdown.

Behaviors worth stating: priority only changes the order in which waiting tasks start. A task that is already running is not interrupted. Adding a high priority task when all slots are busy puts it at the front of the waiting list, so it starts as soon as a slot is free.

Production features that you can mention: cancellation with AbortSignal, timeouts per task, pause and resume, retries, and a limit on the pending list size for back pressure.

javascript
class PriorityQueue {
  #pending = [];
  #running = 0;
  #order = 0;
  #idleWaiters = [];
  constructor(concurrency = 2) {
    this.concurrency = concurrency;
  }

  add(task, priority = 0) {
    return new Promise((resolve, reject) => {
      const entry = { task, priority, order: this.#order++, resolve, reject };
      const index = this.#pending.findIndex((other) => other.priority < priority);
      if (index === -1) this.#pending.push(entry);
      else this.#pending.splice(index, 0, entry);
      this.#pump();
    });
  }

  #pump() {
    while (this.#running < this.concurrency && this.#pending.length > 0) {
      const { task, resolve, reject } = this.#pending.shift();
      this.#running++;
      Promise.resolve()
        .then(task)
        .then(resolve, reject)
        .finally(() => {
          this.#running--;
          this.#pump();
          this.#notifyIdle();
        });
    }
  }

  #notifyIdle() {
    if (this.#running === 0 && this.#pending.length === 0) {
      for (const done of this.#idleWaiters.splice(0)) done();
    }
  }

  onIdle() {
    if (this.#running === 0 && this.#pending.length === 0) return Promise.resolve();
    return new Promise((resolve) => this.#idleWaiters.push(resolve));
  }
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const started = [];
const queue = new PriorityQueue(2);
const job = (name, ms, fail = false) => async () => {
  started.push(name);
  await sleep(ms);
  if (fail) throw new Error(name + ' failed');
  return name + ' done';
};

const results = [
  queue.add(job('A', 60), 1),
  queue.add(job('B', 10), 1),
  queue.add(job('C', 10), 1),
  queue.add(job('D', 10), 5),
  queue.add(job('E', 10, true), 3),
  queue.add(job('F', 10), 1),
];

Promise.allSettled(results).then(async (settled) => {
  await queue.onIdle();
  console.log('start order:', started.join(' '));
  console.log(settled.map((r) => (r.status === 'fulfilled' ? r.value : r.reason.message)));
});

Run with Node.js v24.22.1 as js-105.js; two runs gave identical output. Output: start order: A B D E C F [ 'A done', 'B done', 'C done', 'D done', 'E failed', 'F done' ]

Key points

  • add returns a promise for the task's own result.
  • Pending list sorted by priority, with an order counter for FIFO among equals.
  • The pump starts tasks while running is below the limit and pumps again when one finishes.
  • A rejected task rejects only its own promise; the queue keeps going.
  • Priority does not interrupt running tasks; onIdle helps tests and shutdown.

Common mistakes

  • Letting a task error break the pump so queued tasks never start.
  • Sorting the whole list on each add and losing first in, first out order for equal priority.
  • Forgetting to call the pump again when a task finishes.
  • Expecting a new high priority task to cancel running tasks.

Follow-ups

  • How would you add cancellation with AbortSignal?
  • How would you replace the sorted array with a heap, and when does it matter?
  • How would you add a per-task timeout and retry?

Tips

  • State the three parts: limit, order, result promises.
  • Say clearly that running tasks are not preempted.
  • Mention onIdle for tests and graceful shutdown.