Skip to the content

Lesson 85 of 296

Promise pool with a concurrency limit

On this page

The task

"You have a list of async tasks (for example 500 image uploads). Run them with at most N at the same time, and return all results in the original order."

Why this matters

  • Promise.all(tasks.map(t => t())) starts all 500 at once. That can overload your server, hit API rate limits, run out of memory or open too many connections.
  • Running them one by one is safe but very slow.
  • A pool is the middle way: always keep N running. When one finishes, start the next.

This is a very realistic interview task for full stack roles.

Questions to ask first

  • "Are the tasks functions that return promises, or promises already started?" (They must be functions. A promise has already started its work, so it cannot be held back.)
  • "If one task fails, should everything stop, or should we collect all results?"
  • "Do results need to be in the original order?"

The idea: workers

Create N workers. Each worker is an async loop that:

  1. Takes the next task index that nobody has taken yet.
  2. Runs that task and waits for it.
  3. Saves the result at that task's index.
  4. Repeats until no tasks are left.

Then wait for all workers to finish.

Because JavaScript is single-threaded (Lesson 67), nextIndex++ cannot be run by two workers at the same moment, so no two workers ever take the same task.

The solution

async function promisePool(tasks, limit) {
  const results = new Array(tasks.length);
  let nextIndex = 0;

  async function worker() {
    while (nextIndex < tasks.length) {
      const index = nextIndex++;
      results[index] = await tasks[index]();
    }
  }

  const workerCount = Math.min(limit, tasks.length);
  const workers = Array.from({ length: workerCount }, () => worker());
  await Promise.all(workers);
  return results;
}

Walk through it

Tasks take 50, 10, 30, 20 and 40 ms. Limit 2.

Time (ms)Worker AWorker B
0Starts task 0 (50 ms)Starts task 1 (10 ms)
10still on task 0Task 1 done; starts task 2 (30 ms)
40still on task 0Task 2 done; starts task 3 (20 ms)
50Task 0 done; starts task 4 (40 ms)still on task 3
60still on task 4Task 3 done; no tasks left, stops
90Task 4 done; stops

At most 2 tasks ever run together, and the results array is [result0, result1, result2, result3, result4], in the original order.

Test it

let running = 0;
let maxRunning = 0;
const tasks = [50, 10, 30, 20, 40].map((ms, i) => async () => {
  running++;
  maxRunning = Math.max(maxRunning, running);
  await sleep(ms);
  running--;
  return i;
});

await promisePool(tasks, 2);      [0, 1, 2, 3, 4]
maxRunning                        2
await promisePool([], 3);         []

Error handling choices

Fail fast (current version): if any task throws, that worker's promise rejects and Promise.all rejects. Note: the other workers keep running their current tasks in the background.

Collect everything (like allSettled):

try {
  results[index] = { status: "fulfilled", value: await tasks[index]() };
} catch (reason) {
  results[index] = { status: "rejected", reason };
}

Usage

const uploads = files.map((file) => () => uploadFile(file));
const urls = await promisePool(uploads, 5);

Note the arrow function wrapper: () => uploadFile(file). Writing uploadFile(file) directly would start every upload immediately.

Follow-up questions

  • "How would you add a progress callback?" Count completed tasks in the worker and call onProgress(done, total).
  • "How would you add a delay between tasks to respect a rate limit?" Await a sleep in the worker loop, or use a token-bucket rate limiter (Part 11).
  • "Is there a library for this?" Yes, for example p-limit. Back end job queues such as BullMQ have concurrency settings too (Part 15). Interviewers want to see that you can build the idea yourself.

Common mistakes

  • Passing promises instead of functions.
  • Pushing results in finishing order.
  • Starting a fixed batch of N, waiting for all N, then the next N. This works, but is slower: one slow task holds back its whole batch. The worker pool always keeps N busy.
  • Creating more workers than tasks (handled by Math.min).

How to say it in an interview

"The tasks must be functions returning promises so nothing starts early. I create up to limit async workers that share a nextIndex counter. Each worker loops: takes the next index, awaits that task, stores the result at the same index, and stops when no tasks remain. Because JavaScript is single-threaded, incrementing the counter is safe. Awaiting Promise.all on the workers gives all results in input order with at most limit running at once. I can switch from fail-fast to settled results by catching per task."

Key words

WordMeaning
ConcurrencySeveral tasks in progress at the same time
Concurrency limitThe maximum number running at once
WorkerA loop that keeps taking and running tasks
PoolA fixed set of workers sharing a list of tasks
Rate limitA rule limiting how many requests are allowed per period
BatchingRunning tasks in fixed groups

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.