Keep two things: a list of waiting tasks and a count of running ones. add(task) puts the task in the list and calls next(), which starts tasks while running < concurrency. When a task settles, decrease the count and call next() again, so a freed slot is reused at once. Tasks must be functions that return a promise, not promises, or they've already started before the queue sees them. Return a promise from add so each caller gets its own result. For the follow-up, send failures to an onError(error, task) handler and keep the queue running: one failed task must never block the tasks behind it. From there the usual extras are onIdle(), priorities, pause and start, and retries.
Implement an async process queue with concurrency control. Follow-up: handle async-task failures by accepting an error callback handler.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
add wraps the task in a promise and stores its resolve and reject beside it. next is a loop: while a slot is free and something is waiting, take the first task, count it as running, run it, and settle the caller's promise with its outcome. Whatever the outcome, the last step frees the slot and calls next again. A failure rejects only that task's promise; the queue carries on. The timing check uses durations 50, 10, 10, 10 with two slots: starts at 0, 0, 10 and 20 ms.
// Tasks are functions that return a promise. At most `concurrency` run at once; the rest wait// in line. add() returns a promise for that task's own result.class AsyncQueue {constructor(concurrency = 1) {this.concurrency = concurrency;this.running = 0;this.waiting = [];}add(task) {return new Promise((resolve, reject) => {this.waiting.push({ task, resolve, reject });this.next();});}next() {while (this.running < this.concurrency && this.waiting.length) {const job = this.waiting.shift();this.running++;// The extra then() turns a synchronous throw inside the task into a rejection.Promise.resolve().then(() => job.task()).then(job.resolve, job.reject).then(() => {this.running--;this.next();});}}}
passes 5 checks run on every build, against the native method where there is one
- concurrency 1 runs tasks one after another, in order
- never more than `concurrency` at once, and a free slot is reused at once
- tasks can be added later, while others run
- a failed task rejects its own promise and the queue keeps going
- a task that throws synchronously is a rejection, not a crash
With onError, a failure is reported to the handler with the error and the task that failed, and the queue moves on. The task's own promise still rejects for a caller who awaits it, and it is marked as handled so a caller who ignores it doesn't cause an unhandled-rejection error. The slot is freed before the handler runs, so a handler that throws can't jam the queue. onIdle() returns a promise that resolves when nothing is running or waiting: the way to say "wait for all uploads".
// The follow-up: failures go to an error handler and the queue keeps going. Also onIdle(),// to wait until everything added so far has finished.class AsyncQueue {constructor({ concurrency = 1, onError } = {}) {if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer');this.concurrency = concurrency;this.onError = onError;this.running = 0;this.waiting = [];this.idlers = [];}get size() {return this.waiting.length;}add(task) {const promise = new Promise((resolve, reject) => {this.waiting.push({ task, resolve, reject });});// The failure is reported through onError, so a caller may safely ignore this promise.if (this.onError) promise.catch(() => {});this.next();return promise;}// Resolves once nothing is running and nothing is waiting.onIdle() {if (this.running === 0 && this.waiting.length === 0) return Promise.resolve();return new Promise((resolve) => this.idlers.push(resolve));}next() {while (this.running < this.concurrency && this.waiting.length) {const job = this.waiting.shift();this.running++;Promise.resolve().then(() => job.task()).then((value) => {job.resolve(value);this.release();},(error) => {job.reject(error);this.release(); // free the slot first, so a handler that throws can't jam the queueif (this.onError) this.onError(error, job.task);},);}}release() {this.running--;this.next();if (this.running === 0 && this.waiting.length === 0) {for (const resolve of this.idlers.splice(0)) resolve();}}}
passes 11 checks run on every build, against the native method where there is one
- concurrency 1 runs tasks one after another, in order
- never more than `concurrency` at once, and a free slot is reused at once
- tasks can be added later, while others run
- a failed task rejects its own promise and the queue keeps going
- a task that throws synchronously is a rejection, not a crash
- onError gets the error and the task, and later tasks still run
- the task's own promise still rejects for a caller who awaits it
- a handler that throws doesn't jam the queue
- onIdle resolves when everything has finished
- onIdle on an empty queue resolves at once
- a bad concurrency throws
add(task, { priority }) inserts the task into a line kept sorted by priority, first in first out among equals. pause() stops new tasks from starting while running ones finish; start() resumes. With retries, a failed task goes back to the front of the line and runs again (it receives the attempt number), and only its last failure rejects the promise and reaches onError.
// What a production queue adds: priorities, pause and start, and retries before a task is// reported as failed.class AsyncQueue {constructor({ concurrency = 1, retries = 0, onError, autoStart = true } = {}) {if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer');this.concurrency = concurrency;this.retries = retries;this.onError = onError;this.paused = !autoStart;this.running = 0;this.waiting = [];this.idlers = [];}get size() {return this.waiting.length;}add(task, { priority = 0 } = {}) {const promise = new Promise((resolve, reject) => {// Keep the line sorted: higher priority first, first in first out among equals.let at = this.waiting.length;while (at > 0 && this.waiting[at - 1].priority < priority) at--;this.waiting.splice(at, 0, { task, resolve, reject, priority, attempts: 0 });});if (this.onError) promise.catch(() => {});this.next();return promise;}// Tasks already running finish; nothing new starts until start().pause() {this.paused = true;}start() {this.paused = false;this.next();}onIdle() {if (this.running === 0 && this.waiting.length === 0) return Promise.resolve();return new Promise((resolve) => this.idlers.push(resolve));}next() {while (!this.paused && this.running < this.concurrency && this.waiting.length) {const job = this.waiting.shift();this.running++;Promise.resolve().then(() => job.task(job.attempts)).then((value) => {job.resolve(value);this.release();},(error) => {if (job.attempts++ < this.retries) {this.waiting.unshift(job); // try again before anything else in the linethis.release();return;}job.reject(error);this.release();if (this.onError) this.onError(error, job.task);},);}}release() {this.running--;this.next();if (this.running === 0 && this.waiting.length === 0) {for (const resolve of this.idlers.splice(0)) resolve();}}}
passes 16 checks run on every build, against the native method where there is one
- concurrency 1 runs tasks one after another, in order
- never more than `concurrency` at once, and a free slot is reused at once
- tasks can be added later, while others run
- a failed task rejects its own promise and the queue keeps going
- a task that throws synchronously is a rejection, not a crash
- onError gets the error and the task, and later tasks still run
- the task's own promise still rejects for a caller who awaits it
- a handler that throws doesn't jam the queue
- onIdle resolves when everything has finished
- onIdle on an empty queue resolves at once
- a bad concurrency throws
- higher priority goes first; equal priority keeps arrival order
- pause holds new tasks; running ones finish; start resumes
- autoStart: false waits for start()
- retries run the task again, before the rest of the line
- onError is called once, after the last retry
Upload and sync queues
A file uploader or an offline sync sends a few requests at a time, reports each failure, and keeps going. The user can keep adding files while earlier ones upload.
p-queue
The widely used promise queue: concurrency, add() returning the task's promise, priority, pause() / start() and onIdle(), the API of the later stages.
p-limit
The smallest form of the same idea: limit(() => fetchSomething()) returns a promise and runs at most N of the wrapped calls at once.
Accepting promises instead of functions: a promise has already started its work, so nothing is being limited.
Not freeing the slot when a task fails, so the queue stalls after enough failures.
Letting one failure reject or stop everything behind it.
Forgetting that a task can throw synchronously, before it returns a promise.
Calling the next task only from
add, so tasks left waiting never start when a slot frees up.An error handler that throws and leaves the running count wrong.
How is this different from concurrency-limited map?
The map takes a fixed list and returns one result list. A queue is open-ended: tasks arrive at any time, each caller gets its own promise, and the queue lives as long as the app does.
How would you add a timeout per task?
Race the task against a timer that rejects, and pass an AbortSignal into the task so the work itself stops. Without the signal the slot is freed but the request keeps running in the background.
What should retries wait for?
Usually a growing delay (exponential backoff with some randomness) so a struggling server isn't hit again at once by every failed task. Retry only errors that can succeed later, like a network failure or a 503, not a 400.
What's the cost of adding with a priority?
Inserting into a sorted array is O(n). For a queue with many thousands of waiting tasks, a binary heap makes it O(log n).