Semaphores and Resource Pools
A web service runs 200 request threads, and every request needs the database. The database accepts at most 20 connections. Opening a new connection for each request is slow, and the 21st one is refused. So the service keeps 20 connections open and shares them: a thread borrows one, runs its query and gives it back. When all 20 are in use, the next thread has to wait, give up after a while, or be told "busy, try later."
This is a scarcity problem: there are N of something and more than N threads want one. Locks don't fit, because a lock lets one thread in, not twenty. The tool for "up to N at once" is the semaphore, and the structure built on it is a resource pool. This post covers both, and what to do when demand is bigger than supply, which is called backpressure.
💡 Why this matters in an interview: connection pools, rate limiters, download managers, parking garages and worker pools are all "N of something" problems. Interviewers want to see a correct bound, a clear answer to "what happens when it's full?", and no leaked permits when something throws.
A Semaphore Is a Counter of Permits
A semaphore holds a count of available permits. It has two operations:
- acquire: if a permit is available, take it (count goes down by one) and continue. If none is, wait until one is released.
- release: give a permit back (count goes up by one) and wake one waiting thread.
Picture a coat check with 20 hooks and a counter showing how many are free. Anyone can take a hook while the counter is above zero; when it hits zero, the next person waits in line until someone collects a coat.
Here is a client for a slow partner API that allows at most 5 requests in flight from our service:
class ShippingQuoteClient:
def __init__(self, max_in_flight: int = 5) -> None:
self._permits = threading.BoundedSemaphore(max_in_flight)
def quote(self, parcel: Parcel) -> int:
with self._permits: # acquire; released on exit, even on exception
return self._call_partner_api(parcel)
class ShippingQuoteClient {
private final Semaphore permits = new Semaphore(5);
public int quote(Parcel parcel) throws InterruptedException {
permits.acquire();
try {
return callPartnerApi(parcel);
} finally {
permits.release(); // always, or the permit leaks
}
}
}
Two hundred threads can call quote at once. Five are inside _call_partner_api; 195 are asleep in acquire.
Each time one finishes, one sleeper wakes and goes in.
Semaphore vs Lock
A semaphore with one permit (a binary semaphore) looks like a lock, but there are real differences:
| Lock (mutex) | Semaphore | |
|---|---|---|
| How many inside | exactly one | up to N |
| Ownership | only the thread that acquired it may release it | any thread may release (no owner) |
| Reentrant | often (RLock, synchronized) |
never: acquiring twice takes two permits |
| Protects | shared data (correctness) | a limited resource (scarcity) |
The "no owner" row matters. It makes semaphores useful for signalling between threads (thread A releases a permit that thread B is waiting to acquire, which is how many "print in order" puzzles are solved). It also means nothing stops a buggy thread from releasing a permit it never took.
⚠️ Common mistake: thinking the semaphore protects the data the threads use. It only counts. If the five threads inside share a list or a counter, that state still needs its own lock. "A semaphore for the limit, a lock for the data" is the usual pair.
Releasing Exactly Once
A permit must be released exactly once for every successful acquire, on every path.
- Released zero times: an exception skips the
release, so the permit is gone for good. After five such errors the client is stuck at zero, and every caller waits forever. Usetry/finally(Java) orwith(Python). - Released twice: a retry path or a double cleanup calls
releaseagain, and the semaphore now allows six. The bound you promised silently drifts. Python'sBoundedSemaphoreraisesValueErrorwhen released above its starting value, which catches this bug, so prefer it to plainSemaphore. - Released without acquiring: an
acquirethat timed out or was interrupted didn't get a permit, so its cleanup must not release one. In Java, putacquire()before thetry, as above, so a failed acquire never reaches thefinally.
Don't Wait Forever
acquire() with no timeout can wait indefinitely. For a background worker that is fine. For a thread serving a
user, it usually isn't. Both languages let you bound the wait:
if not self._permits.acquire(timeout=0.5):
raise BusyError("partner API saturated") # fail fast instead of queueing forever
try:
return self._call_partner_api(parcel)
finally:
self._permits.release()
if (!permits.tryAcquire(500, TimeUnit.MILLISECONDS)) {
throw new BusyException("partner API saturated");
}
try {
return callPartnerApi(parcel);
} finally {
permits.release();
}
tryAcquire() with no arguments doesn't wait at all: it takes a permit if one is free and returns false
otherwise. This is the basis of every backpressure choice later in the post.
Fairness. By default, a released permit can go to any waiting thread, or even to a thread that just arrived
and never waited. Under heavy load, an unlucky thread can wait much longer than others (starvation). Java's
new Semaphore(5, true) hands permits out in arrival order, at some cost in throughput. Python's semaphore makes
no ordering promise.