Video in progress

How does building the Bulkhead pattern with thread pools change in the era of virtual threads?

The classic bulkhead gives each external dependency its own thread pool. With virtual threads, since threads are cheap, you limit the number of concurrent calls with a semaphore instead of a pool: the isolation idea stays, the tool changes.

📖 Answer

The goal of a bulkhead: one slow dependency must not sink the whole service. For example, the SMS provider stops responding for 30 seconds. If all requests share the same 200 Tomcat threads, within a few seconds they are all busy waiting on SMS, and the payment endpoint stops responding too.

In the era of platform threads the solution is a separate ThreadPoolExecutor for SMS (say, 20 threads and a queue of 50). When it's full, you reject immediately, and the main pool stays free. Hystrix was built on this idea. The cost: picking a pool size for every dependency, passing context (MDC, security, trace) between threads, and a lot of memory.

With virtual threads (Java 21, spring.threads.virtual.enabled=true on Spring Boot 3.2+), every request gets its own virtual thread, and the problem of running out of threads almost disappears. But that doesn't mean you no longer need a bulkhead: the problem just moves elsewhere:

  • 10,000 virtual threads wait on the slow provider at once and open 10,000 connections to it;
  • the connection pool (HikariCP) fills up and everyone queues for it;
  • memory: each virtual thread's stack lives on the heap, and as waiting requests grow, GC pressure rises.

So the bulkhead is now a semaphore:

private final Semaphore smsSlots = new Semaphore(50);

void send(Sms sms) {
    if (!smsSlots.tryAcquire(100, TimeUnit.MILLISECONDS)) throw new SmsBusyException();
    try { client.send(sms); } finally { smsSlots.release(); }
}

Resilience4j's SemaphoreBulkhead is the same thing. Watch out for pinning: in Java 21-23, blocking inside synchronized pins a virtual thread to its carrier; in JDK 24 this is mostly fixed. If you work with older libraries, check with -Djdk.tracePinnedThreads (21-23) or JFR events.

When setting a platform standard, I make a limit, a timeout and a "limit reached" metric mandatory for every external dependency. The limit's value itself is determined by a load test and the provider's SLA, not by guessing.