How to Implement Bounded Concurrency
Limit concurrency deliberately: run at most N tasks at once, queue the rest, preserve result order, and avoid overwhelming a downstream.
On this page
Introduction
Firing every task at once is the default and the easiest way to overload a downstream. A thousand-element array mapped with an async function opens a thousand concurrent requests, exhausting sockets, hitting rate limits, and making the downstream’s latency spike. Bounded concurrency runs at most N tasks at a time and queues the rest, so the load on the downstream is N and predictable, and the total time is the work divided by N rather than an unbounded stampede.
This tutorial implements bounded concurrency: choose N from the bottleneck, run at most N with a queue, preserve result order when needed, and test the cap. The examples use a promise limiter, and the structure applies to a semaphore in any runtime.
Choose N from the limiting resource
N should match the capacity of the resource being called. For an API with a rate limit, estimate N as the allowed requests per second times the average call duration in seconds, so the in-flight count stays under the rate. For a database with a connection pool, N is the pool size, so the tasks use the pool without waiting. For an external service with an unknown limit, start low and raise it as the latency stays flat.
If N is too high, the downstream is overwhelmed and its latency rises, which can make the total time worse than a lower N. If N is too low, the capacity is wasted and the total time is longer than necessary. The right N is empirical, found by measuring the downstream latency as N rises, and it changes when the downstream changes.
function createLimiter(limit) {
let active = 0;
const queue = [];
const next = () => {
if (active >= limit || queue.length === 0) return;
active++;
const { fn, resolve, reject } = queue.shift();
Promise.resolve(fn()).then(resolve, reject).finally(() => { active--; next(); });
};
return (fn) => new Promise((resolve, reject) => { queue.push({ fn, resolve, reject }); next(); });
}
Run at most N and queue the rest
The limiter keeps a count of active tasks. A new task starts only if the count is below N; otherwise it waits in a queue. When a task finishes, the count drops and the next queued task starts. This keeps the peak concurrency at N, no matter how many tasks are submitted, and the queue holds the excess in memory rather than as concurrent calls.
Bound the queue as well, so an enormous submission does not grow it without limit. If the queue is full, the submitter waits or the limiter rejects, applying backpressure. This is the same principle as a bounded stream buffer: the limiter bounds concurrency, and the queue bound prevents the memory from growing when the submission outpaces the capacity.
async function mapLimited<T, R>(items: T[], limit: number, fn: (t: T) => Promise<R>): Promise<R[]> {
const results: R[] = new Array(items.length);
let index = 0;
async function worker() {
while (index < items.length) {
const i = index++;
results[i] = await fn(items[i]); // position preserved by index
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
Preserve result order when the caller needs it
Tasks finish out of order, so results collected as they complete are in completion order. If the caller expects an array in submission order, tag each task with its index and store the result at that index, then return the array. The indices preserve the order regardless of which task finished first.
If the caller processes each result as it arrives, completion order is fine and finishes sooner, because it does not wait for the slow early task before using a fast later one. Choose based on the caller: array-in-order for a function that returns a collected result, callback-per-result for a stream of processing. Do not force an order the caller does not need, because the reassembly adds a wait.
Handle failures within the limit
A task that rejects must not stop the limiter from starting the next queued task, or the concurrency drops and the queue stalls. Decrement the active count in a finally, whether the task resolves or rejects, so the next task starts. Decide whether a failure fails the whole batch or is collected alongside the successes, and surface it accordingly.
For a fail-fast batch, cancel the remaining tasks when one fails, using a shared signal, so a doomed batch does not keep loading the downstream. For a collect-all batch, record each task’s outcome and continue. Either way, the limiter’s counter must be released on failure, which is the most common bug in a hand-written limiter.
function limited(limit, fn) {
let active = 0;
const queue = [];
const run = () => {
while (active < limit && queue.length) {
const job = queue.shift();
active++;
Promise.resolve()
.then(job.fn)
.then(job.resolve, job.reject)
.finally(() => { active--; run(); }); // release on success OR failure
}
};
return fn;
}
Test the cap and the order
Submit many tasks with an artificial delay and record how many are in flight at once; assert the peak equals N and never exceeds it. Test that results are returned in submission order when the caller expects an array, even though the tasks finish out of order. Test that a rejected task does not stall the limiter, so the remaining tasks still run. Test that the queue is bounded and applies backpressure when full.
node -e '
const limit = 4; let active = 0, peak = 0;
const run = async (i) => { active++; peak = Math.max(peak, active); await new Promise((r) => setTimeout(r, 10)); active--; return i; };
// use the limiter over 100 tasks
await mapLimited([...Array(100).keys()], limit, run);
console.log("peak concurrency:", peak); // must equal 4
'
Common pitfalls
Using Promise.all so every task starts at once, an N larger than the downstream capacity, an unbounded queue that grows under a large submission, an active counter not released on failure so the limiter stalls, and forcing an order the caller does not need are the recurring mistakes. A limiter with a queue, an N from the bottleneck, a bounded queue, release in finally, and order only when needed address them.
Conclusion
Bounded concurrency keeps the load on a downstream at a chosen N instead of fanning out. Choose N from the bottleneck, run at most N with a queue, release the counter on success and failure, preserve order only when the caller needs it, and bound the queue. Self-check by submitting many tasks and asserting the peak concurrency equals N and results are ordered. Then a burst becomes a queue that drains at a rate the downstream can take.
Sources: MDN: Promise.all and concurrency, p-limit: Run multiple promise-returning functions with limited concurrency, Go: Bounded concurrency with a semaphore.
FAQ
- Why not just Promise.all?
- Promise.all starts every task at once, so a thousand task array opens a thousand concurrent calls, which can overwhelm the downstream or exhaust sockets. Bounded concurrency starts at most N and queues the rest, keeping the load predictable.
- How do I choose N?
- From the downstream's capacity, the connection pool size, or a measured sweet spot. For an API with a rate limit, N is the allowed rate divided by the call duration. For a database with a small pool, N is the pool size. Too high overloads the downstream; too low wastes capacity.
Report a problem with this articleOpens a pre-filled issue on GitHub.