← Back to JavaScript, page 3

javascript-0042 · Hard senior

How would you run many async tasks while limiting how many run at the same time?

Start a fixed number of workers, and let each worker repeatedly take the next task from a shared index until none remain. Store each result at its task's index so the output stays in input order. This keeps at most N tasks in flight and avoids both the sequential slowdown and the overload of Promise.all over thousands of tasks.

Full answer

Running tasks one by one is slow, but starting thousands at once can exhaust sockets, memory, or an API's rate limit. A concurrency limit sits between the two.

A simple and correct design is a worker pool. Create limit async worker functions. All of them share one counter next. Each worker loops: take the current index, move the counter forward, and if the index is within the list, await that task and store the result at the same index. When the list is exhausted, the worker ends. Promise.all over the workers waits until all tasks are done. Because JavaScript runs one piece of code at a time, taking the index and incrementing it happens without any race, as no await sits between the two steps.

The tasks must be functions that return promises, not promises that already started. Starting a promise begins its work immediately, so passing started promises cannot be limited.

Design points for a senior answer: results come back in input order because of index storage. Decide the failure policy: in the sketch, the first rejection rejects the whole pool, but remaining workers still pick up new tasks unless they are stopped with a shared flag or AbortSignal. For per-task error tolerance, catch inside the task and store an error object. The time cost is roughly the total work divided by the limit.

Libraries such as p-limit and p-queue provide the same idea with more features.

javascript
async function runWithLimit(tasks, limit) {
  const results = new Array(tasks.length);
  let next = 0;

  async function worker() {
    while (true) {
      const index = next++;
      if (index >= tasks.length) return;
      results[index] = await tasks[index]();
    }
  }

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

let active = 0;
let maxActive = 0;
const order = [];

const makeTask = (id, ms) => async () => {
  active += 1;
  maxActive = Math.max(maxActive, active);
  order.push(`start ${id}`);
  await new Promise((resolve) => setTimeout(resolve, ms));
  active -= 1;
  order.push(`end ${id}`);
  return `result ${id}`;
};

const tasks = [makeTask(1, 100), makeTask(2, 10), makeTask(3, 10), makeTask(4, 10), makeTask(5, 10)];

runWithLimit(tasks, 2).then((results) => {
  console.log(results);
  console.log('max running at once:', maxActive);
  console.log(order.join(', '));
});

Run with Node.js v24.22.1 as js-42.js; two runs gave identical output. Output: [ 'result 1', 'result 2', 'result 3', 'result 4', 'result 5' ] max running at once: 2 start 1, start 2, end 2, start 3, end 3, start 4, end 4, start 5, end 5, end 1

Key points

  • Start N workers that pull from a shared index.
  • Tasks are functions returning promises, so they start only when a worker takes them.
  • Store results by index to keep input order.
  • Decide the failure policy: stop early or collect errors.
  • Total time is about the sum of task times divided by the limit.

Common mistakes

  • Passing already started promises and expecting a limit to apply.
  • Using Promise.all over chunks of N tasks, which waits for the slowest task in every chunk.
  • Collecting results in completion order instead of input order.
  • Ignoring the failure policy, so one rejection leaves orphaned workers running.

Follow-ups

  • How would you stop all workers after the first failure?
  • How would you add retry with exponential backoff for each task?
  • How would you handle a task list that arrives as a stream?

Tips

  • Explain why the pool beats chunking: no waiting for the slowest member of a batch.
  • Say aloud that the shared index is safe because JavaScript does not interleave code between statements without await.
  • Discuss the failure policy before the interviewer asks.