Sub topic 8
Protecting databases and downstream services
This chapter assumes you know Java 21 concurrency basics, have a Spring Boot 3.2+ MVC application, and understand blocking I/O such as JDBC and HTTP clients. It also assumes you have read the earlier chapters on what a virtual thread is and how to enable virtual threads in Spring Boot.
The limit you removed by accident
With platform threads, the Tomcat thread pool did two jobs at once. It handled requests, and it capped how much work reached your database and your downstream services. The default Tomcat pool has 200 threads. Even if traffic spiked, at most about 200 requests ran your code at the same time.
Virtual threads remove that cap. Once spring.threads.virtual.enabled=true is set, each request gets its own virtual thread, and the number of requests in flight is limited only by memory and by what the clients can accept. That is the point of virtual threads. It also means the old accidental protection is gone.
Consider an application with a HikariCP connection pool of 10 connections. Before the change, 200 request threads competed for 10 connections, and 190 of them waited. After the change, 5,000 virtual threads may compete for the same 10 connections. The pool still hands out 10 at a time, so database load does not rise. But the waiting requests now pile up inside the pool and time out, and the application reports errors that look like a database problem.
Find the real bottleneck
Before adding limits, list the resources a request touches and write down the capacity of each one.
| Resource | Where the limit lives | Typical symptom when exceeded |
|---|---|---|
| Database connections | `spring.datasource.hikari.maximum-pool-size` | `Connection is not available, request timed out after 30000ms` |
| Database server | `max_connections`, CPU, locks | Slow queries, refused connections |
| Downstream HTTP service | The other team's rate limit or capacity | HTTP 429 or 503, rising latency |
| HTTP client connection pool | Client library settings | Requests wait for a free connection |
| Memory | JVM heap | `OutOfMemoryError`, long GC pauses |
The rest of this chapter shows how to place a limit close to each scarce resource, so that excess requests wait cheaply or fail quickly instead of overloading it.
Keep the connection pool as the database limit
The connection pool is already a limit, and it is the right one for the database. Do not raise maximum-pool-size because you now have more threads. A pool size is chosen from what the database server can serve efficiently, not from how many threads exist in the application.
What you should review is the wait time. HikariCP's connection-timeout defaults to 30 seconds. With platform threads, a request rarely waited that long because the thread pool queue was bounded by 200 threads. With virtual threads, many more requests may wait, so a long timeout holds many parked virtual threads and keeps clients waiting for an answer that will probably be an error.
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.connection-timeout=2000A short timeout makes the application fail fast under overload. Callers get an error in two seconds instead of thirty, and they can retry or back off. Choose the value from your latency goals, not from this example.
Limit concurrency with a Semaphore
A Semaphore holds a fixed number of permits. A thread calls acquire() to take one and release() to return it. If none are free, the thread waits. With virtual threads, waiting on a semaphore parks the virtual thread and frees its carrier thread, so thousands of waiting threads cost little.
This pattern fits a downstream service with a known capacity. The following wrapper allows at most 20 simultaneous calls to an inventory service.
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();
}
}
}Three details matter here.
- The
release()call is in afinallyblock. If it were skipped after an exception, permits would leak, and the service would eventually stop making calls at all. acquire()throwsInterruptedException. Let it propagate, or restore the interrupt flag withThread.currentThread().interrupt()if you catch it.- The permit count is set from the downstream capacity. If the inventory service handles 20 concurrent requests well, use 20. Do not copy the number from the example.
Fail fast with a timeout
acquire() waits forever. Under sustained overload, requests stack up behind the semaphore, each holding memory and a client connection. Use tryAcquire with a timeout to bound the wait.
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
class BoundedInventoryClient {
private final Semaphore permits = new Semaphore(20);
private final InventoryClient delegate;
BoundedInventoryClient(InventoryClient delegate) {
this.delegate = delegate;
}
String stockFor(String sku) throws InterruptedException {
if (!permits.tryAcquire(500, TimeUnit.MILLISECONDS)) {
throw new IllegalStateException("Inventory service is saturated");
}
try {
return delegate.stockFor(sku);
} finally {
permits.release();
}
}
}Throwing after 500 milliseconds turns overload into a clear, fast error. In a real application you would map that exception to an HTTP 503 response, often with a Retry-After header.
Do not hold a permit longer than needed
Acquire the permit immediately before the limited call and release it immediately after. If you acquire it at the start of the request and the request then does other slow work, you reduce throughput without protecting anything more.
Do not pool virtual threads
Platform thread pools exist because threads are expensive, so you reuse them. Virtual threads are cheap, so you create one per task and let it end. A fixed-size pool of virtual threads works as a concurrency limit, but it hides the real constraint and mixes two purposes. Use a semaphore, a connection pool, or a rate limiter for the limit, and create threads freely.
This also affects @Async and scheduled work. When the property is on, Boot's application task executor uses virtual threads, so a burst of @Async calls no longer queues behind a small pool. If that work calls a limited resource, put a limit around the resource, as shown above.
Choose the right tool for each limit
| Tool | Limits | Good for |
|---|---|---|
| Connection pool (HikariCP) | Open connections to one database | Database access |
| `Semaphore` | Simultaneous calls | A downstream service with a known concurrency limit |
| Rate limiter (for example Resilience4j) | Calls per time period | APIs with a rate quota such as 100 requests per second |
| Bulkhead | Concurrent calls per dependency | Keeping one slow dependency from using all capacity |
| Client timeouts | Time spent waiting | Every remote call, always |
A semaphore limits concurrency, which is the number of calls in flight. A rate limiter limits frequency, which is calls per second. They answer different questions. A service that takes 2 seconds per call and allows 20 concurrent calls can handle about 10 calls per second. A service that takes 10 milliseconds per call and allows 20 concurrent calls can handle about 2,000. Pick the tool that matches how the downstream service states its limit.
Always set timeouts on remote calls
A virtual thread blocked on a hung socket costs little, but it still holds the request open and may still hold a semaphore permit or a database connection. Set connect and read timeouts on every HTTP client, and a query timeout for database calls. With Spring's JdbcTemplate you can use setQueryTimeout, and with JPA you can set the jakarta.persistence.query.timeout hint.
Common mistakes
- Raising the pool size to match the new thread count. The database did not get larger. More connections often make it slower.
- Leaving the 30 second connection timeout. Overload then shows up as long hangs instead of quick errors.
- Forgetting
finallyaroundrelease(). Leaked permits slowly shut the call path down. - Using one semaphore for several unrelated dependencies. A slow dependency then uses permits that the others need. Use one semaphore per dependency.
- Limiting at the wrong layer. A semaphore around the whole controller method limits all work, including parts that need no protection.
Exercise
Your service runs on Spring Boot 3.2 with virtual threads enabled. A HikariCP pool has 10 connections, and during a traffic spike users see "Connection is not available, request timed out after 30000ms". A teammate proposes raising maximum-pool-size to 500. Give two reasons this is a poor fix and one better change.
Show answer
The database server cannot serve 500 concurrent queries efficiently, so more connections raise contention and often slow every query. Also, the spike may still exceed 500, so the failure only moves. A better change is to shorten connection-timeout so overload fails fast, and to limit concurrency before the database call (for example with a Semaphore using tryAcquire and a timeout, or a bulkhead) so excess requests are rejected quickly with a 503 instead of waiting 30 seconds.
Exercise
An inventory service accepts at most 20 concurrent requests. Each call takes 100 ms. Roughly how many calls per second can your application make to it without overloading it, and which tool would you use to enforce the limit?
Show answer
With 20 calls in flight and each lasting 0.1 seconds, throughput is about 20 / 0.1 = 200 calls per second. A Semaphore with 20 permits enforces the concurrency limit, ideally with tryAcquire and a timeout so waiting requests fail fast.