How to Implement Bounded Parallelism with Semaphores
Limit how many tasks run at once so a fan-out does not exhaust file descriptors, connections or memory.
On this page
Introduction
Fanning out work in parallel is the easy part; deciding how much parallelism is safe is the hard part. A map over ten thousand items that starts ten thousand fetches at once will exhaust sockets, hit rate limits, and consume memory for ten thousand response buffers. Bounded parallelism caps how many tasks are in flight at any moment, which keeps resource use predictable and turns a burst into a steady stream. A semaphore is the general mechanism: it holds a count of permits, and a task must acquire one before it runs and release it when it finishes. This article builds a counting semaphore, uses it to limit a fan-out, and shows how to weigh tasks, cancel waits and observe saturation.
Why Unbounded Parallelism Fails
Promise.all over a large list launches every task immediately. Each open socket, connection, or in-memory buffer consumes a resource, and the total is proportional to the list length. The failure modes are predictable: the process runs out of file descriptors, the database refuses new connections, the remote service rate-limits you, and the event loop stalls under the bookkeeping. None of these is a bug in any single task; the aggregate is the problem.
Bounded parallelism fixes the aggregate. With a limit of twenty, at most twenty tasks hold resources at once, so the peak is a property of the limit rather than the input size. Throughput stays close to maximum because the slowest tasks no longer starve the rest for resources. The limit also makes behaviour testable: you can reason about peak memory and peak connection count from the limit alone, rather than from a worst-case input you may never observe in a test environment.
A Counting Semaphore
A counting semaphore holds an integer count of available permits and a queue of waiters. Acquire decrements the count if positive and otherwise queues the caller; release increments the count and wakes the next waiter. Implement it with promises so acquires are awaitable, and make release idempotent-safe by throwing if called without a matching acquire.
class Semaphore {
constructor(permits) {
this.permits = permits;
this.waiters = [];
}
async acquire() {
if (this.permits > 0) {
this.permits -= 1;
return;
}
await new Promise((resolve) => this.waiters.push(resolve));
}
release() {
const next = this.waiters.shift();
if (next) {
next(); // hand the permit directly to the next waiter
} else {
this.permits += 1;
}
}
async run(task) {
await this.acquire();
try { return await task(); }
finally { this.release(); }
}
}
Limiting a Fan-Out Over a List
Wrap each task in semaphore.run and await the results. The tasks are still started together, but only the permitted number actually execute at once; the rest wait inside acquire. This keeps a single shared limit over the whole batch, unlike a chunked loop which creates new bursts and can idle the limit between chunks.
async function mapBounded(items, limit, fn) {
const sem = new Semaphore(limit);
return Promise.all(items.map((item, i) => sem.run(() => fn(item, i))));
}
// At most 8 concurrent HTTP requests, regardless of how many items there are
const results = await mapBounded(urls, 8, async (url) => {
const res = await fetch(url);
if (!res.ok) throw new Error('fetch failed: ' + res.status);
return res.json();
});
Weighted Semaphores
Not all tasks cost the same. A small query might use one connection while a batch job uses ten. A weighted semaphore acquires a number of permits and releases the same number, so a heavy task consumes more of the limit. This models real capacity better than treating every task as equal, and it prevents a few heavy tasks from monopolizing the pool.
Size the limit from the resource constraint, not from a guess. If you have a pool of thirty database connections, the limit is at most thirty, and less after you reserve some for interactive traffic. If the constraint is the remote service’s rate limit, derive the limit from that number. The limit should be a stated policy, visible in code, not an incidental constant.
Handling Timeouts and Cancellation
A waiter that is queued forever because permits never free up is a leak. Add a timeout to acquire so a caller can give up; when it gives up, it must remove itself from the queue so it is not handed a permit it will not use. Similarly, support cancellation by removing a waiter from the queue when its signal aborts.
Always release in a finally block, so a task that throws does not permanently consume a permit. A single leaked permit shrinks the effective limit forever, and over time the pool drains to zero. This is the semaphore equivalent of a connection leak and it is just as invisible until throughput collapses.
Observing Saturation
Expose the number of waiters and the number of available permits as a gauge. When waiters climb and permits sit at zero, the limit is the bottleneck and everything downstream waits. That is a signal to raise the limit only if the underlying resource has headroom; otherwise it is a signal to make tasks faster or reduce the input.
Compare the limit against the resource’s own saturation: connection-pool usage, socket count and memory. Bounded parallelism is working when the limit binds before the resource does. If the resource saturates first, the limit is too high; if the limit binds while the resource is idle, it is too low.
Conclusion
Bounded parallelism with a semaphore converts an unpredictable burst into a steady, resource-bounded stream. Implement a counting semaphore with a waiter queue, wrap tasks so permits are always released, weight heavy tasks if they cost more, and add timeouts and cancellation so a queue cannot grow without end. Choose the limit from the real resource constraint and expose the waiter count so saturation is visible. The result is parallelism that is fast without being fragile.
Sources: p-limit (bounded concurrency), Semaphore (programming), Node.js: asynchronous flow control.
FAQ
- Why not just chunk the list and use Promise.all per chunk?
- Chunking still creates bursts and can idle capacity while a slow chunk finishes, since the next chunk does not start until the current one is fully done. A shared semaphore keeps exactly the allowed number in flight continuously and adapts if task durations vary.
- How do I choose the concurrency limit?
- Size it from the tightest real resource: available database connections, socket limits, or a remote service rate limit, minus a reserve for other traffic. Make the number an explicit, documented policy rather than an incidental constant.
Report a problem with this articleOpens a pre-filled issue on GitHub.