Sub topic 8
Protecting databases and downstream services
This chapter assumes you can read Java 21 code, know ExecutorService and java.util.concurrent, and have a Spring Boot 3.2+ MVC application with spring.threads.virtual.enabled=true.
Why the old limit disappears
With platform threads, the Tomcat thread pool (200 threads by default) capped how many requests ran at once. That cap also protected your database and the services you call, but only by accident.
Virtual threads remove that cap. The server can run thousands of requests at once, and each one can block on a downstream call. If the database connection pool holds 10 connections, thousands of virtual threads will queue for those 10 connections. Requests then time out waiting, or the downstream service gets far more calls than it can handle.
Virtual threads make waiting cheap. They do not make the database or a partner API any faster.
Limit with a Semaphore
A Semaphore is a counter of permits. A thread calls acquire() to take one and release() to give it back. When no permits are left, acquire() blocks. A blocked virtual thread unmounts from its carrier thread, so waiting costs almost nothing.
Wrap the scarce resource in a class that holds the semaphore:
import java.util.concurrent.Semaphore;
class LimitedInventoryClient {
private final Semaphore permits = new Semaphore(20);
private final InventoryClient delegate;
LimitedInventoryClient(InventoryClient delegate) {
this.delegate = delegate;
}
String stockFor(String sku) throws InterruptedException {
permits.acquire();
try {
return delegate.stockFor(sku);
} finally {
permits.release();
}
}
}The finally block matters. If release() is skipped after an exception, permits leak, and eventually every caller blocks forever.
Choosing the number
Pick the limit from the downstream system's capacity, not from your own thread count.
| Resource | Where the limit usually comes from |
|---|---|
| Database | Connection pool size, such as HikariCP `maximumPoolSize` |
| Partner HTTP API | Rate limit or concurrency agreement |
| Internal service | Load-test results for that service |
For a database, the connection pool already acts as a limit. Threads wait in getConnection() until one is free. That works, but the wait is bounded by the pool's connectionTimeout (30 seconds by default), so a surge produces timeout errors instead of orderly queuing. A semaphore in front of the work gives you control over how long callers wait. Use tryAcquire with a timeout to fail fast:
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
class FailFastGate {
private final Semaphore permits = new Semaphore(20);
String call(java.util.function.Supplier<String> work) throws InterruptedException {
if (!permits.tryAcquire(500, TimeUnit.MILLISECONDS)) {
throw new IllegalStateException("Downstream busy, try again later");
}
try {
return work.get();
} finally {
permits.release();
}
}
}Rejecting a request after 500 ms is usually better than holding thousands of requests for 30 seconds.
Common mistakes
- Pooling virtual threads. Do not create a fixed pool of virtual threads to limit concurrency. Virtual threads are meant to be created per task. Limit the resource with a semaphore instead.
- Raising the connection pool to match traffic. More connections can overload the database itself. Size the pool for what the database can serve.
- One global semaphore. Use a separate limit for each downstream system. Otherwise a slow service uses up permits that a healthy one needs.
- Forgetting timeouts. A permit does not help if the call inside it can hang. Set HTTP and JDBC timeouts too.
Exercise
Your service runs on virtual threads with a HikariCP pool of 10 connections, and under load requests fail after 30 seconds with connection timeout errors. Why does this happen, and what is one way to fix the behavior?
Show answer
Virtual threads let thousands of requests run at once, but only 10 can hold a connection. The rest wait in the pool until connectionTimeout (30 seconds) expires. Put a Semaphore sized near the pool size in front of the database work and use tryAcquire with a short timeout, so excess requests fail quickly instead of waiting 30 seconds.