Video in progress
10,000 virtual threads run at once, and the DB connection pool has 50. What happens, and how do you design the system?
The virtual threads pile up in Hikari's queue waiting for a connection, errors start after connectionTimeout, and the DB still never sees more than 50 queries. You need to limit concurrency at the entry point, cut the work done in the DB, and align the timeouts across the layers.
📖 Answer
In the platform thread days, Tomcat's 200 threads were a natural limit. With virtual threads, every incoming request gets a thread immediately, so the load hits the narrowest resource directly: the DB pool.
What you see:
- thousands of
pending threadsin Hikari; SQLTransientConnectionException: Connection is not available, request timed out after 30000ms;- most of the latency is connection wait, not SQL;
- every waiting request holds its context in the heap, so memory grows.
Raising the pool to 500 is usually not the answer: PostgreSQL starts a separate process for each connection, and with 500 active queries the DB chokes itself. The optimal parallelism for a DB is often around a few times the number of cores.
This is how I design it:
// at the entry: an explicit limit for work that touches the DB
private final Semaphore dbPermits = new Semaphore(60);
public Order find(long id) throws InterruptedException {
if (!dbPermits.tryAcquire(200, TimeUnit.MILLISECONDS)) {
throw new ServiceBusyException(); // 503, fast rejection
}
try { return repo.findById(id).orElseThrow(); }
finally { dbPermits.release(); }
}
The other layers:
- A chain of timeouts: client timeout > service timeout > connection wait (
connectionTimeoutof 1-2 s, not 30 s) >statement_timeout. Otherwise the DB works on a request whose client has already left. - Shorter transactions: no HTTP calls inside a transaction, so a connection is held only for the SQL time.
- Separating reads: a read replica and a cache reduce the demand for connections.
- Bulkhead: heavy requests like reports get a separate, small pool and their own limit.
The main point: virtual threads removed the limit that "a thread is an expensive resource", so admission control now has to be a deliberate design decision.
Sign up to mark studied questions and save your progress.