How to Implement a Semaphore
Use a semaphore to cap concurrency: acquire a permit before work, release it in finally, and weigh fairness against throughput.
On this page
Introduction
A semaphore holds a number of permits and hands them out to callers who need to enter a bounded section of work. With N permits, at most N callers proceed at once; the rest wait until a permit is released. It is the primitive behind bounded concurrency, connection pools, and rate limiter slots, and it is the generalization of a mutex from one holder to N.
This tutorial implements a semaphore: choose the permit count from the resource, acquire before the work and release in a finally, decide the fairness policy, and test that the cap holds and a failure releases the permit. The examples use an async semaphore, and the same primitive exists as semaphore.Semaphore in Go and asyncio.Semaphore in Python.
Set the permit count from the resource
The permit count is the maximum concurrency, so it comes from the resource the work touches. A database with a pool of ten accepts ten permits; an API with a rate limit gets a count derived from the rate; a CPU-bound computation gets about the number of cores. The semaphore does not create capacity, it limits the load to what the resource can take, so the count should match that capacity.
A count too high overwhelms the resource, and a count too low wastes its capacity, so the number is empirical. Expose the number of available permits and the number of waiters as metrics, so saturation is visible: a queue that keeps growing and zero available permits means the count is the bottleneck and the resource is not.
class Semaphore {
private permits: number;
private queue: (() => void)[] = [];
constructor(permits: number) { this.permits = permits; }
async acquire(): Promise<void> {
if (this.permits > 0) { this.permits--; return; }
await new Promise<void>((res) => this.queue.push(res));
}
release(): void {
const next = this.queue.shift();
if (next) next(); // hand the permit to the next waiter
else this.permits++;
}
async run<T>(fn: () => Promise<T>): Promise<T> {
await this.acquire();
try { return await fn(); } finally { this.release(); } // release on failure too
}
}
Acquire before, release in finally
Acquire a permit before starting the protected work and release it in a finally, so the release happens whether the work succeeds, fails, or is cancelled. A release that runs only on the success path leaks a permit on every failure, slowly reducing the concurrency until no permit is available and all callers wait forever. This is the most common semaphore bug and the hardest to notice.
Keep the protected section as small as it needs to be. The permit is held for the whole section, so unrelated work inside it holds a permit it does not need and reduces the concurrency for others. Acquire as late as possible before the resource access and release as soon as the access is done, not at the end of a longer function.
Choose a fairness policy
A first-in-first-out queue serves waiters in arrival order, which is predictable and prevents a busy caller from being starved by a stream of newcomers. A priority policy serves higher-priority waiters first, which fits when some work must run ahead of others, at the cost of starving low-priority work under load. Choose based on whether older or more important work should win.
Some semaphores also support a timeout on acquire, so a caller that cannot get a permit in time fails rather than waiting indefinitely. A bounded wait is often better than an infinite one under saturation, because it lets the caller shed, retry, or return a degraded result instead of holding a request open. Combine the timeout with metrics so waiters timing out is visible.
import asyncio
sem = asyncio.Semaphore(10) # at most 10 concurrent holders
async def bounded(item):
async with sem: # acquire; released on exit, even on exception
return await handle(item)
# to bound the wait, wrap the acquire in a timeout
async def bounded_with_timeout(item):
try:
await asyncio.wait_for(sem.acquire(), timeout=1.0)
except asyncio.TimeoutError:
return degraded(item)
try:
return await handle(item)
finally:
sem.release()
Use it for rate limiting and pools
A semaphore is the mechanism behind a bounded connection pool: the permits are the pool size, and a caller that needs a connection acquires one. It is also behind a rate limiter that caps in-flight requests rather than requests per second: a token bucket limits the rate, a semaphore limits the concurrency, and they solve different problems. Use both where a downstream has both a rate and a concurrency limit.
Combine the semaphore with a queue depth metric so the backpressure is visible. When the semaphore is saturated, the waiters queue in memory, so bound that queue too, or make acquire time out, so a burst does not grow the queue without limit. The semaphore bounds concurrency; the queue bound and the acquire timeout bound the memory and the wait.
Test the cap and the release on failure
Test that the concurrency never exceeds the permit count, by running more tasks than permits and recording the peak concurrent count. Test that a task that throws still releases its permit, so the next task proceeds; the unguarded version would leak the permit and eventually deadlock. Test that waiters are served in order with a FIFO policy. Test that an acquire times out when no permit is available and the caller gets the degraded path.
node -e '
const sem = new Semaphore(3);
let active = 0, peak = 0;
const task = () => sem.run(async () => { active++; peak = Math.max(peak, active); await new Promise((r) => setTimeout(r, 10)); active--; });
Promise.all(Array.from({ length: 20 }, task)).then(() => console.log("peak:", peak)); // 3
'
Common pitfalls
Releasing only on the success path so a failure leaks a permit, holding a permit across unrelated work, an unbounded waiter queue that grows under a burst, no acquire timeout so callers wait forever under saturation, and a permit count that does not match the resource capacity are the recurring mistakes. Release in finally, a small protected section, a bounded queue or acquire timeout, and a count from the capacity address them.
Conclusion
A semaphore caps concurrency at its permit count. Set the count from the resource, acquire before the work and release in finally so a failure does not leak a permit, choose a fairness policy, and bound the wait with a queue limit or an acquire timeout. Self-check by asserting the peak concurrency equals the permits and that a failed task still releases its permit. Then bounded work uses the resource fully without overwhelming it.
Sources: MDN: AbortController and bounded work, Go: golang.org/x/sync/semaphore, Python: asyncio.Semaphore.
FAQ
- Semaphore or mutex?
- A mutex is a semaphore with one permit: it allows one holder at a time. A semaphore generalizes it to N permits, so N holders run concurrently. Use a mutex for exclusive access and a semaphore for a bounded pool of concurrent work.
- How do I avoid leaking a permit?
- Release in a finally block, so a thrown error or a cancellation still releases. A permit leaked on an error path slowly reduces the concurrency until the semaphore is empty and everything waits forever, which is a subtle and hard-to-find bug.
Report a problem with this articleOpens a pre-filled issue on GitHub.