Video in progress

What is the bulkhead pattern, and how do the semaphore and thread pool bulkheads in Resilience4j differ?

A bulkhead limits the number of parallel calls to a single dependency, so even if it slows down, resources remain for other work. The semaphore variant runs on the current thread and only limits the count, while the thread pool variant runs the call in a separate pool.

📖 Answer

The name comes from a ship: the hull is divided into compartments, and if water gets into one, the ship doesn't sink.

The problem: Tomcat has 200 threads. recommendation-service slows down and all 200 threads end up waiting for it. Now payments, login, nothing works, even though recommendations were a secondary feature.

With a bulkhead, at most 20 calls to recommendations are allowed at once, and the 21st is rejected immediately or gets a fallback:

resilience4j:
  bulkhead:
    instances:
      recommendations:
        max-concurrent-calls: 20
        max-wait-duration: 0
@Bulkhead(name = "recommendations", fallbackMethod = "noRecommendations")
public List<Product> recommend(long userId) { ... }

The difference:

  • SemaphoreBulkhead: the call runs on the same thread, there's just a counter. Simple, no extra threads. It also works naturally with virtual threads.
  • ThreadPoolBulkhead: a separate pool and queue, and the method has to return a CompletionStage. The calling thread isn't tied up, but configuring the pool and passing context (trace, security) takes extra work.

I usually start with the semaphore. I choose the limit based on metrics: the usual number of parallel calls plus a bit of headroom.