Bound Outbound Concurrency with a Java Counting Semaphore
Use java.util.concurrent.Semaphore to cap parallel outbound calls without dropping requests, plus how to verify the bound under load.
16 Dec 2025, 07:07 UTC

The problem: your service is calling an API faster than it can answer
Imagine a Java service that ingests user events and forwards each one to a third-party enrichment API. Under normal load this works fine. During a traffic spike, the application spawns hundreds of threads, each opening its own HTTP call to the same endpoint. The external API starts returning HTTP 429 Too Many Requests, connection pools exhaust, and latency for unrelated endpoints climbs because threads are stuck waiting on slow responses.
A counting semaphore is a synchronization object that holds a fixed number of permits. A thread must acquire a permit before entering a critical section and release it when it leaves. If no permits are available, the thread blocks until one is returned. In this scenario, the critical section is the outbound API call, and the semaphore caps how many can run at the same time.
Thesis: cap parallelism, not throughput
You do not need to reject requests during a spike. You need to bound how many are in flight so the downstream service stays healthy and your own threads do not pile up waiting on a single slow dependency. A semaphore with N permits lets up to N calls execute concurrently while additional callers wait in line. When a call finishes, it returns its permit, unblocking the next waiter.
Worked example: bounding outbound calls in Java
Assumptions: Java 8 or later. java.util.concurrent.Semaphore has been in the standard library since Java 5, so no external dependency is required.
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.Semaphore;
public class EnrichmentClient {
private final HttpClient http = HttpClient.newHttpClient();
// Three permits means at most three outbound calls run at once.
private final Semaphore concurrencyLimit = new Semaphore(3, true);
public String enrich(String eventId) throws Exception {
concurrencyLimit.acquire(); // blocks if all permits are in use
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create("https://api.example.com/enrich/" + eventId))
.GET()
.build();
HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
} finally {
concurrencyLimit.release(); // always return the permit, even on failure
}
}
}
The Semaphore(3, true) constructor creates a fair semaphore: permits are granted in roughly the order threads requested them. Fairness reduces starvation but adds a small scheduling overhead. If order does not matter, new Semaphore(3) is slightly cheaper.
Callers can submit work from an executor without changing the semaphore logic:
ExecutorService executor = Executors.newFixedThreadPool(20);
for (String eventId : eventIds) {
executor.submit(() -> {
try {
client.enrich(eventId);
} catch (Exception e) {
// log and continue; the semaphore permit was already returned in finally
}
});
}
Twenty threads compete for three permits, so at most three enrichments run simultaneously. The other seventeen block inside acquire() until a permit becomes available.
Verify the bound under load
Run this check locally before deploying. The goal is to confirm that the number of simultaneous critical-section executions never exceeds the permit count.
- Instrument the
enrichmethod to increment anAtomicInteger activeCallson acquire and decrement it infinallyafter release, tracking the maximum observed value. - Launch more threads than permits—for example, 50 threads against a semaphore initialized with 5 permits.
- Make each thread hold its permit for a fixed, measurable time (e.g., 200 ms) so overlap is likely.
- Assert that
maxActiveCallsnever exceeds 5.
Where to run: on a developer workstation or CI runner with a JDK installed. No special OS permissions are required beyond executing the Java process. Risk: if a code path returns early without calling release() inside a finally block, the permit is leaked. Repeated leaks reduce the available permit count until the semaphore blocks indefinitely.
In production, monitor wait time on acquire(). Rising wait times mean the semaphore is the intended bottleneck; rising response times with flat wait times suggest the problem is downstream latency, not concurrency.
Trade-offs and limitations
- Intra-process only. A Java semaphore coordinates threads inside one JVM. If your service runs behind a load balancer across multiple instances, each instance maintains its own permit pool. Five instances with three permits each can still generate fifteen concurrent calls to the downstream API. For cross-instance bounds, use a distributed rate limiter or a shared connection pool with a hard max.
- Not a rate limiter. A semaphore bounds concurrency, not requests per second. If each call takes one second and you have three permits, the theoretical maximum is roughly three requests per second, but bursty traffic can still exceed short-term quotas enforced by the remote API.
- Fairness is optional. Unless you construct the semaphore as fair, a thread that just released a permit may re-acquire it before a long-waiting thread, increasing the risk of starvation under heavy contention.
- Permit leaks collapse the bound. Every
acquire()must pair with exactly onerelease(). Releasing more times than acquired inflates the permit count and removes the concurrency cap.
Actionable closing
Pick the downstream call that causes the most incidents during spikes. Wrap it in a semaphore sized to the remote service's documented concurrency limit, or start conservatively with a small number such as three or five and increase while monitoring error rates. Always release in a finally block, verify the maximum simultaneous count with a local test, and remember that the bound applies per service instance, not across your whole cluster.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.