java 31 lines · 7 steps

Bulkhead-protected HTTP calls in Spring

A Spring service caps concurrent warehouse calls with a semaphore bulkhead and degrades gracefully when it saturates or fails.

Explained by highlit
1@Service
2public class InventoryService {
3 
4 private final RestClient warehouseClient;
5 
6 public InventoryService(RestClient.Builder builder) {
7 this.warehouseClient = builder
8 .baseUrl("https://warehouse.internal/api")
9 .build();
10 }
11 
12 @Bulkhead(name = "warehouse", type = Bulkhead.Type.SEMAPHORE, fallbackMethod = "cachedStock")
13 public StockLevel currentStock(String sku) {
14 return warehouseClient.get()
15 .uri("/stock/{sku}", sku)
16 .retrieve()
17 .body(StockLevel.class);
18 }
19 
20 private StockLevel cachedStock(String sku, BulkheadFullException ex) {
21 log.warn("Warehouse bulkhead saturated for sku={}, serving degraded stock", sku);
22 return StockLevel.unknown(sku);
23 }
24 
25 private StockLevel cachedStock(String sku, Throwable ex) {
26 log.error("Warehouse lookup failed for sku={}", sku, ex);
27 return StockLevel.unknown(sku);
28 }
29 
30 private static final Logger log = LoggerFactory.getLogger(InventoryService.class);
31}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A semaphore bulkhead bounds concurrent calls to a dependency so one slow service can't exhaust your threads.
  2. 2Fallback methods let you return a degraded-but-valid response instead of propagating failures to callers.
  3. 3Matching fallbacks by exception type lets you distinguish saturation from genuine downstream errors.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Bulkhead-protected HTTP calls in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code