Sub topic 15
Running Large Batches with a Concurrency Limit
This chapter assumes you have read the earlier chapters on sequential versus concurrent awaiting and on Promise.all and Promise.allSettled. You should be comfortable with async functions, closures, and try/catch. The examples use top-level await, so save them as .mjs files and run them with Node.js 18 or later.
The Problem with Both Extremes
Suppose you have 10,000 image URLs to download, or 5,000 user records to send to an API. You have two obvious options, and both are bad.
Awaiting each task in a for loop is safe, but slow. The total time is the sum of every task's time. With 5,000 requests at 200 ms each, that comes to more than 16 minutes.
Mapping everything into one Promise.all call is fast in theory, but every task starts at the same moment. That causes real failures:
- The remote API sees 5,000 simultaneous requests and responds with HTTP 429 (Too Many Requests), or blocks you.
- Your process opens thousands of sockets or file handles and hits operating system limits (
EMFILE,ECONNRESET). - Every pending request holds buffers in memory at once.
- Because
Promise.allfails fast, one early rejection hands you an error while thousands of requests are still running.
What you usually want sits between these: run at most N tasks at a time, and start the next task as soon as one finishes.
The Worker Pool Pattern
The most common way to do this without a library is to start a fixed number of "workers". Each worker is an async loop that takes the next unclaimed index from a shared counter, processes that item, and repeats until no items are left. Promise.all then 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;
}The pattern has four parts:
resultsis allocated up front, and each result is written to its own indexi. The output therefore keeps input order even though tasks finish in any order, which matches whatPromise.allguarantees.nextis the shared counter. Every worker reads it and increments it.Math.min(limit, items.length)avoids starting idle workers when there are fewer items than the limit.Promise.all(workers)fulfills when every worker's loop has ended, which happens after the last item is done.
Why the Shared Counter Is Safe
In a multithreaded language, const i = next++ run from several workers would be a race condition. In JavaScript it is safe because your code runs on a single thread and a function only gives up control at an await. The check next < items.length and the claim next++ happen together with no await between them, so two workers can never claim the same index.
This safety disappears if you put an await between the check and the claim. For example, while (next < items.length) { await something(); const i = next++; ... } lets several workers pass the check while only one item remains. They then claim indexes past the end of the array and call fn(undefined, ...).
Seeing the Limit in Action
The script below counts how many tasks are in flight at once and measures the total time.
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
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;
}
let inFlight = 0;
let maxInFlight = 0;
async function fakeFetch(id) {
inFlight++;
maxInFlight = Math.max(maxInFlight, inFlight);
await delay(50 + (id % 3) * 50); // 50, 100 or 150 ms
inFlight--;
return `item-${id}`;
}
const ids = Array.from({ length: 10 }, (_, i) => i);
const start = Date.now();
const results = await mapWithLimit(ids, 3, fakeFetch);
console.log(results); // ['item-0', ..., 'item-9'] in input order
console.log('max in flight:', maxInFlight); // 3
console.log('elapsed ms:', Date.now() - start); // roughly 350Run sequentially, these ten tasks would take about 950 ms. Unbounded, they would take about 150 ms, but with ten requests in flight at once. With a limit of 3 they take roughly 350 ms, and no more than three requests are ever in flight.
Worker Pool Versus Fixed Chunks
A common shortcut is to split the list into chunks and run Promise.all on one chunk at a time:
async function mapInChunks(items, size, fn) {
const results = [];
for (let i = 0; i < items.length; i += size) {
const chunk = items.slice(i, i + size);
results.push(...(await Promise.all(chunk.map((item, j) => fn(item, i + j)))));
}
return results;
}This code also caps concurrency, but it wastes time. Each chunk waits for its slowest task before the next chunk starts, so when one task in a chunk takes 150 ms and the others take 50 ms, two slots sit idle for 100 ms. The worker pool refills a slot as soon as a task finishes.
| Approach | Max in flight | Total time | Failure behavior |
|---|---|---|---|
| Sequential `for` + `await` | 1 | Sum of all tasks | Stops at the first error |
| `Promise.all(items.map(fn))` | All items | Slowest single task | Rejects fast; all other tasks keep running |
| Fixed chunks | Chunk size | Sum of each chunk's slowest task | Stops after the failing chunk |
| Worker pool | `limit` | Close to total work ÷ limit | Rejects fast; other workers keep pulling items |
Failure Modes and Gotchas
Workers Keep Going After a Rejection
If fn rejects, the worker that called it throws, and Promise.all(workers) rejects with that error. The other workers are still running and still claiming new items, so mapWithLimit has already returned an error while new requests keep starting. This is the fail-fast behavior from the earlier chapter, made worse because work keeps being added after the failure.
To stop claiming new items after the first failure, add a flag:
async function mapWithLimitFailFast(items, limit, fn) {
if (!Number.isInteger(limit) || limit < 1) {
throw new RangeError('limit must be a positive integer');
}
const results = new Array(items.length);
let next = 0;
let failed = false;
async function worker() {
while (!failed && next < items.length) {
const i = next++;
try {
results[i] = await fn(items[i], i);
} catch (err) {
failed = true;
throw err;
}
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
await Promise.all(workers);
return results;
}Tasks that were already in flight still finish. To abort them as well, pass a shared AbortController signal into fn and call controller.abort() in the catch block, as shown in the cancellation chapter.
Collecting Every Outcome Instead
For a batch job you usually want to process everything and report the failures at the end. Wrap fn so that it never rejects, and produce the same objects that Promise.allSettled returns:
function settle(fn) {
return (item, i) =>
Promise.resolve()
.then(() => fn(item, i))
.then(
(value) => ({ status: 'fulfilled', value }),
(reason) => ({ status: 'rejected', reason })
);
}
// Usage inside an async module:
// const outcomes = await mapWithLimit(urls, 5, settle(download));
// const failures = outcomes.filter((o) => o.status === 'rejected');Promise.resolve().then(() => fn(item, i)) also catches the case where fn throws synchronously before it returns a promise.
Invalid Limits
With limit set to 0, a negative number, or NaN, the original mapWithLimit creates zero workers. Promise.all([]) then fulfills immediately, and the function returns an array of empty slots without running any task. This produces no error, so the bug is easy to miss. Validate the limit, as mapWithLimitFailFast does.
Choosing the Limit
No single limit is correct. Start from the tightest external constraint: the API's documented rate limit, the database's connection pool size, or the number of CPU cores for CPU-heavy work handed to worker threads. A value between 4 and 16 is a reasonable starting point for HTTP calls. Measure throughput and error rates, then adjust. A concurrency limit caps how many requests are in flight at once, not how many you send per second. If the API limits requests per second, you need a rate limiter too.
Exercise
You run mapWithLimit over 6 tasks with limit 2. The tasks take 100, 300, 100, 100, 100 and 100 ms, in that order. Roughly how long does the batch take, and how long would mapInChunks with size 2 take?
Show answer
Worker pool: worker A runs task 0 (0–100), task 2 (100–200), task 3 (200–300), task 4 (300–400) and task 5 (400–500), while worker B runs task 1 (0–300). The total is about 500 ms. Chunks: [100, 300] takes 300 ms, [100, 100] takes 100 ms and [100, 100] takes 100 ms, for about 500 ms total. The two match here, but if the 300 ms task were in the last position, the pool would take 400 ms and the chunks would take 500 ms.
Exercise
A teammate rewrites the worker loop as while (next < items.length) { await rateLimiter.wait(); const i = next++; results[i] = await fn(items[i], i); }. What can go wrong, and how do you fix it?
Show answer
The await between the check and the claim lets several workers pass the check while only one item remains. The extra workers then claim indexes beyond the end of the array and call fn with undefined. Fix it by claiming the index first: const i = next++; if (i >= items.length) break; await rateLimiter.wait(); ..., or by re-checking the condition after the await.