Sub topic 15
Running Large Batches with a Concurrency Limit
This chapter assumes you know how Promise.all collects results in input order, and that you understand the difference between sequential awaiting and starting every task at once. Both topics were covered earlier in this tutorial.
The Problem with Unbounded Concurrency
Suppose you have 5,000 URLs to fetch. If you await each request one at a time, the total time is the sum of every request. If you call items.map(fetch) and pass the result to Promise.all, all 5,000 requests start in the same tick. That can exhaust sockets or file handles, trigger rate limits, or overload the server you are calling.
What you usually want sits between these two extremes. You run at most limit tasks at any moment and start a new one as soon as one finishes.
| Strategy | Tasks in flight | Total time | Risk |
|---|---|---|---|
| Sequential `await` | 1 | Sum of all tasks | Slow |
| `Promise.all` on everything | All of them | Slowest task | Resource exhaustion, rate limits |
| Limited concurrency | At most `limit` | Roughly total ÷ limit | You have to choose a good limit |
The Worker Pool Pattern
The idea is to create a fixed number of async "workers". Each worker repeatedly takes the next unclaimed index from a shared counter, runs the task, and stores the result at that index. Promise.all waits for the workers rather than for the individual tasks.
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i], i);
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
await Promise.all(workers);
return results;
}
// Demo: track how many tasks run at once
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let active = 0;
let peak = 0;
async function task(n) {
active++;
peak = Math.max(peak, active);
await delay(50 + Math.random() * 100);
active--;
return n * 2;
}
async function main() {
const items = Array.from({ length: 20 }, (_, i) => i);
const results = await mapWithLimit(items, 4, task);
console.log(results); // [0, 2, 4, ..., 38] in input order
console.log('peak concurrency:', peak); // 4
}
main();Why the Shared Counter Is Safe
JavaScript runs your code on a single thread. Between the next < items.length check and next++, nothing else can run, because no await separates them. Two workers therefore cannot claim the same index. A worker can only be interrupted at the await, and by that point it has already claimed its index.
Why Results Stay in Order
Tasks finish in whatever order they finish. Each result is written to results[i], though, so the output array matches the input order, just as it does with Promise.all.
Errors in a Limited Batch
If fn throws, the worker that called it rejects, and Promise.all(workers) rejects with that reason. This is the same fail-fast behavior covered earlier: the other workers keep claiming and running items in the background, and their results are thrown away.
Choosing the Limit
- For HTTP APIs, start from the provider's documented rate limit or connection limit.
- For local file or database work, a small number such as 4 to 16 usually saturates the resource.
- For CPU-bound work, a limit does not help on the main thread, because promises do not create parallel threads.
Exercise
With mapWithLimit(items, 3, fn), where items has 10 entries and every task takes exactly 100 ms, roughly how long does the batch take, and what is the peak number of tasks running at once?
Show answer
About 400 ms. Three workers handle 10 items in four rounds (3 + 3 + 3 + 1), and each round takes 100 ms. The peak concurrency is 3.
Exercise
What does mapWithLimit([], 5, fn) return, and why does it not hang?
Show answer
It returns an empty array. Math.min(5, 0) is 0, so no workers are created, and Promise.all([]) fulfills immediately with [].