Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Promise pool with a concurrency limit in JavaScript

87 An async pool with a concurrency ceiling

hard

Run a list of async jobs with at most n in flight at once, and return the results in input order rather than completion order. Prove the ceiling held by watching how many were running at the peak. Then find out what happens to the jobs already in flight when one of them rejects.

Stuck? Three hints, smallest first
  1. 1. Start exactly n workers. Each one pulls the next index off a shared counter until the list runs out.
  2. 2. Write the result into results[i], so ordering comes from the index and not from who finished first.
  3. 3. Promise.all of the workers is what tells you the pool is drained.

The answer

async function pool(jobs, limit) {
  const results = new Array(jobs.length);
  let next = 0;
  const worker = async () => {
    while (next < jobs.length) {
      const index = next++;                 // claim it before awaiting, or two workers take it
      results[index] = await jobs[index]();
    }
  };
  const workers = Array.from({ length: Math.min(limit, jobs.length) }, worker);
  await Promise.all(workers);
  return results;
}

// Jobs that record when they start and finish, and how many overlapped.
function traced(names, holds = 2) {
  const log = { started: [], finished: [], peak: 0 };
  let running = 0;
  const jobs = names.map((name) => async () => {
    running++;
    log.peak = Math.max(log.peak, running);
    log.started.push(name);
    for (let i = 0; i < holds; i++) await Promise.resolve();
    running--;
    log.finished.push(name);
    return name.toUpperCase();
  });
  return { jobs, log };
}

const branches = ['ikeja', 'yaba', 'surulere', 'lekki', 'ojota', 'apapa'];

const twoAtATime = traced(branches);
const results = await pool(twoAtATime.jobs, 2);

const serial = traced(branches);
await pool(serial.jobs, 1);

const wideOpen = traced(['ikeja', 'yaba', 'surulere']);
await pool(wideOpen.jobs, 10);

const nothing = await pool([], 4);

// One job rejects while others are already in flight.
const flaky = traced(['ikeja', 'yaba', 'surulere']);
flaky.jobs[1] = async () => { throw new Error('upload failed for yaba'); };
const outcome = await pool(flaky.jobs, 2).then(() => 'resolved', (err) => err.message);
for (let drain = 0; drain < 40; drain++) await Promise.resolve();
const finishedAnyway = flaky.log.finished;

console.log('results        :', results);
console.log('peak of 2      :', twoAtATime.peak, twoAtATime.log.peak);
console.log('serial started :', serial.log.started);
console.log('after a failure:', outcome, '| still finished:', finishedAnyway);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('results come back in input order, whoever finished first', results, ['IKEJA', 'YABA', 'SURULERE', 'LEKKI', 'OJOTA', 'APAPA']);
test('with a ceiling of two, two ran at the peak and never three', twoAtATime.log.peak, 2);
test('and the first two started before either of them finished', twoAtATime.log.started.slice(0, 2), ['ikeja', 'yaba']);
test('a ceiling of one serialises it completely', [serial.log.peak, serial.log.finished], [1, branches]);
test('a ceiling above the list size starts everything and creates no idle workers', [wideOpen.log.peak, wideOpen.log.started], [3, ['ikeja', 'yaba', 'surulere']]);
test('an empty list resolves to an empty array instead of hanging', nothing, []);
test('one rejection is what the pool reports, and it reports the first one', outcome, 'upload failed for yaba');
test('but the work already claimed carried on regardless: rejecting is not cancelling', finishedAnyway, ['ikeja', 'surulere']);

Promise.all(jobs.map(run)) starts everything at once, which is fine for six jobs and fatal for six thousand. The fix is not to chunk the list — chunking makes every batch wait for its slowest member — but to start a fixed number of workers that each pull from a shared cursor. Throughput stays at the ceiling instead of sagging at every batch boundary.

const index = next++ before the await is the line that makes it correct. Read the counter, then increment, then await: two workers resuming in the same turn would otherwise claim the same index, and one job would run twice while another never ran at all.

The last two assertions are the trap. Promise.all rejects as soon as one worker rejects, so await pool(...) throws while the other worker is still mid-job — and it keeps going, because nothing in JavaScript cancels a promise. The started work finishes, its results are written into an array nobody is holding, and any side effects it has still happen. If that matters, thread an AbortSignal through the jobs, or collect settled outcomes per job instead of letting the first failure speak for the whole batch.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.