Run async tasks with a concurrency limit, retries and exponential backoff.
Problem
Upload 100 files or call an API for 1,000 ids without opening 1,000 connections at once (browsers allow about 6 connections per host over HTTP/1.1, and servers rate-limit). Run at most limit tasks at a time, keep results in input order, and retry transient failures.
Concurrency pool
Start limit workers. Each worker takes the next index from a shared counter, awaits the task, stores the result at that index and repeats until no tasks remain. Promise.all(workers) resolves when all are done. This is how p-limit and p-map work.
Retry with exponential backoff and jitter
On failure, wait base * 2^attempt ms (100, 200, 400, ...), plus random jitter so many clients do not retry in lockstep, up to a maximum number of attempts. Retry only errors that can succeed later (network errors, 429, 503), not 400 or 404, and honour a Retry-After header.
async function runWithLimit(tasks, limit) {
const results = new Array(tasks.length);
let next = 0;
async function worker() {
while (next < tasks.length) {
const i = next++; // claim an index (safe: JS is single-threaded)
results[i] = await tasks[i]();
}
}
await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker));
return results;
}
async function retry(fn, { retries = 3, base = 100, shouldRetry = () => true } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await fn(attempt);
} catch (err) {
if (attempt >= retries || !shouldRetry(err)) throw err;
const delay = base * 2 ** attempt * (0.5 + Math.random() / 2); // backoff with jitter
await new Promise(r => setTimeout(r, delay));
}
}
}
// Demo: 8 tasks, at most 3 at a time
const sleep = ms => new Promise(r => setTimeout(r, ms));
let running = 0, peak = 0;
const tasks = Array.from({ length: 8 }, (_, i) => async () => {
running++; peak = Math.max(peak, running);
await sleep(10 + (i % 3) * 10);
running--;
return i * i;
});
const results = await runWithLimit(tasks, 3);
assert.deepEqual(results, [0, 1, 4, 9, 16, 25, 36, 49]); // input order kept
assert.equal(peak, 3);
// Demo: a flaky call that succeeds on the third attempt
let attempts = 0;
const value = await retry(async () => {
attempts++;
if (attempts < 3) throw Object.assign(new Error('503'), { status: 503 });
return 'ok';
}, { base: 5, shouldRetry: e => e.status >= 500 || e.status === 429 });
assert.equal(value, 'ok');
assert.equal(attempts, 3);
await assert.rejects(retry(async () => { throw Object.assign(new Error('404'), { status: 404 }); }, { base: 5, shouldRetry: e => e.status >= 500 }), /404/);
console.log('results:', results, 'peak concurrency:', peak, 'attempts:', attempts);Example
Combining both for a batch upload in the UI:
async function uploadAll(files, onProgress) {
let done = 0;
const tasks = files.map(file => () =>
retry(() => fetch('/upload', { method: 'POST', body: file }).then(r => {
if (!r.ok) throw Object.assign(new Error(r.statusText), { status: r.status });
return r.json();
}), { shouldRetry: e => !e.status || e.status >= 500 || e.status === 429 })
.finally(() => onProgress(++done / files.length)));
return runWithLimit(tasks, 4);
}A network failure in fetch has no status, so it is retried; a 4xx response is not.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you add cancellation?
Pass an AbortSignal into the pool: workers stop taking new tasks when signal.aborted, the signal is forwarded to each fetch, and the backoff sleep listens for abort to reject early. On component unmount, call controller.abort().