What you'll learn: By the end of this lesson you will be able to draw the closed, open and half-open states of a circuit breaker and say what moves it between them, choose what counts as a failure and how many calls to judge, explain how a bulkhead limits the damage a slow dependency can do to the threads you share, tell which of the two answers a given symptom (calls that fail versus calls that hang), and read the output of two small labs: a breaker on a fake clock and a bulkhead in a Spring MVC shop.
A house has a fuse box and a hull has watertight compartments, and they solve different problems. The breaker notices that a circuit keeps overloading and cuts it off, so the wiring does not burn while you work out why. The compartment notices nothing: it limits where water can go, so one hole floods one section and not the ship. Software that calls other software needs both ideas: stop calling something that keeps failing, and make sure one thing going wrong can use up only its own share of your threads.
This lesson is the dedicated treatment of both. Timeouts, retries, backoff and jitter bound and repeat a single call, load shedding and retry storms refuse work when you are the one overloaded, graceful degradation and fallbacks decide what the user sees instead, and failure handling end to end joins them on one checkout path. The overview in resilience patterns names the breaker and the bulkhead in a few paragraphs; this lesson shows how each works and where it fails.
Verified with Java 25, Spring Boot 4.1.2, Martin Fowler's circuit breaker article, the Azure Architecture Center pattern pages and the Resilience4j documentation, on 2026-12-01.
The core idea
A circuit breaker is a small state machine around a remote call: while the dependency looks healthy it lets calls through and counts failures, once failures pass a threshold it rejects calls at once without making them, and after a pause it lets a few trial calls through to find out whether the dependency has recovered. A bulkhead is a limit on how many calls to one dependency may be in progress at once, so a dependency that stops answering can hold only its own slots and never all the threads the caller needs for everything else.
They guard against different shapes of trouble:
| Symptom | What is going wrong | The tool |
|---|---|---|
| Calls keep failing, quickly or slowly | You keep paying for calls that cannot succeed and may be hammering a service that is trying to recover | Circuit breaker |
| Calls hang or take far too long | Every caller thread is parked in the same slow dependency, so unrelated work has no thread left | Bulkhead (and a timeout) |
Three illustrations run through the lesson, each labelled:
- Minimal example: two labs, a breaker on a fake clock and a bulkhead with a hanging fake dependency.
- Realistic example: ShopStream's product page and checkout, in "In practice".
- Failure example: a breaker opened by the caller's own errors, in "The 2 a.m. failure".
Why a timeout alone is not enough
A timeout bounds one call and says nothing about the next one. The Azure Architecture Center's circuit breaker page describes the gap: an operation with a time-out can still block concurrent requests to the same operation until it expires, and the blocked requests can hold memory, threads and database connections that unrelated parts of the system need. It adds a warning: a breaker may not fully protect against external services with long time-outs, because a thread can be blocked for a long time before the breaker learns that the call failed.
So the timeout bounds how long one call waits, the breaker stops making calls once many recent ones have failed, and the bulkhead bounds how much of your capacity one dependency can occupy while the other two are still deciding. Retries make the case for a breaker stronger. The Azure page puts the difference plainly: retry expects an operation to eventually succeed, the circuit breaker prevents an operation that is likely to fail, and the two can be combined if the retry logic stops when the breaker says the fault is not transient.
Figure 1. Without isolation, a hanging optional dependency takes the threads the essential one needs. How to read this: every request uses a thread from the same pool, whichever dependency it needs. When recommendations stops answering, its calls occupy the pool, and a checkout request that only needs the healthy payments service waits in the queue behind them.
The circuit breaker as a state machine
Martin Fowler describes the pattern as wrapping a protected function call in a circuit breaker object that monitors for failures. The three states, as Fowler and the Azure page describe them:
- Closed. Calls pass through. Failures are counted, and a success resets the count.
- Open. Calls fail at once with an error and the protected operation is not attempted. A timer runs.
- Half-open. When the timer expires, a limited number of calls are allowed through as trial calls. If they succeed, the breaker closes and its counters reset; if any fails, it opens again and the timer restarts.
Figure 2. The three states and the four transitions. How to read this: the only way back to closed is through half-open, so a recovering dependency is first tested with a handful of calls rather than the full load. The Azure page notes that this protects a service that is recovering from being flooded and failing again.
What trips it
Fowler's simple version counts consecutive failures; he notes that a more advanced version might trip on an error rate such as 50 percent. The Resilience4j documentation, for a Java library that the next lesson uses with Spring, takes the rate approach. It records outcomes in a sliding window (the last N calls, or the calls of the last N seconds), calculates the failure rate only once a minimum number of calls is in the window, and opens when the rate is equal to or greater than a threshold whose documented default is 50 percent. The page's own example makes the point of the minimum: with a minimum of 10 calls, a breaker whose 9 calls all failed still does not open. It also offers a slow-call trigger: a call longer than a configured duration counts as slow, and the breaker can open when the share of slow calls reaches its own threshold. This is the bridge to the bulkhead: a dependency that answers too slowly never produces an error, so only a latency-aware breaker notices it.
What counts as a failure
Fowler's warning is the one to remember: not all errors should trip the circuit; some reflect normal failures that belong in regular logic, and different error types may deserve different thresholds. A card declined for insufficient funds is a successful call that returned a business answer, and a validation error caused by your own bug says nothing about the provider's health. The Azure page adds that a breaker can adjust by exception type, for example requiring more time-outs than "service unavailable" errors before opening. Resilience4j exposes the choice as exceptions that are recorded as failures and exceptions that are ignored (neither a failure nor a success).
Half-open, scope and the open answer
The simplest design has no timer thread: the breaker checks the clock when the next call arrives. Resilience4j documents both options: by default the move to half-open happens only when a call arrives after the wait, and an optional setting makes a monitor thread do it. Half-open admits a limited number of calls and rejects the rest (a documented default of 10 in Resilience4j); when they complete, a failure rate at or above the threshold reopens the breaker and anything below closes it. In the lab below, two trial calls must both succeed.
Use one breaker per dependency, or per independent partition of it: the Azure page warns that one breaker over the shards of a data store lets one shard's failures block calls to healthy shards. And an open breaker has to hand the caller an error, a default value or a cached answer. That is the fallback, a product decision (see the graceful degradation lesson). The Azure page adds that a breaker is no substitute for exception handling in business logic and does not belong around local, in-memory resources.
Build it: a circuit breaker on a fake clock
This is the first of two labs and it already exists: a plain Java model with no framework, with two trip modes (consecutive failures, and failure rate over a sliding window).
Goal. Watch every transition, including a failed trial call, with time under the lab's control.
Setup. From the repository's examples/backend folder:
cd examples/backend && ./gradlew :labs:circuit-breaker:test
./gradlew -q :labs:circuit-breaker:run
The first command runs 18 tests, covering every transition in both modes. The second prints the walk-through below. The code is examples/backend/labs/circuit-breaker/src/main/java/buildingai/labs/circuitbreaker/CircuitBreaker.java.
How the model works. Closed counts failures; in FAILURE_RATE mode the window is a ring buffer of the last K outcomes, judged once a minimum number of calls is in it. Open rejects with CallNotPermittedException until openDurationMillis has passed; the next call then moves it to half-open. All trial calls succeeding closes it with fresh counters, and one failure reopens it and restarts the timer. Time comes from an injected FakeClock, so "one second later" costs nothing.
Expected output, captured from a real run (the first demo section, without its list of transitions):
1. Consecutive-failure mode: trip after 3 failures in a row, stay open 1000 ms, 2 trial calls
t (ms) result state event
0 ok CLOSED healthy call
100 failed CLOSED dependency goes down: failure 1
200 failed CLOSED failure 2
300 ok CLOSED a success resets the streak
400 failed CLOSED failure 1 again
500 failed CLOSED failure 2
600 failed OPEN failure 3 trips the breaker
700 REJECTED OPEN open: rejected without calling
1500 REJECTED OPEN 900 ms after tripping: still open
1600 failed OPEN exactly 1000 ms after tripping: half-open, trial fails, reopens
2100 REJECTED OPEN open again, timer restarted
2600 ok HALF_OPEN recovered: trial call 1 succeeds
2610 ok CLOSED trial call 2 succeeds, breaker closes
2620 ok CLOSED closed: normal traffic
calls that reached the dependency: 11
Read it as a story. The success at 300 ms resets the streak, so three failures in a row only happen at 600 ms. The calls at 700 and 1,500 ms are rejected and never reach the dependency: of 14 calls, 11 reached it. At 1,600 ms the timer has run out, the trial call fails because the dependency is still down, and the timer restarts. Only after recovery do two successful trial calls close the breaker. The demo's second section uses failure-rate mode, where alternating success and failure never makes three in a row but 2 failures in 4 calls reaches 50 percent.
Break it. In CircuitBreaker.onFailure, make the half-open case do nothing: a failed trial no longer reopens the breaker, and the tests halfOpenToOpenWhenATrialFailsAndTheTimerRestarts and aFailedTrialReopens fail. Restore the line afterwards and run the tests again.
What the model leaves out. Slow-call detection, time-based windows, a timer thread and error classification (every exception counts).
The bulkhead: a limit per dependency
The Azure Bulkhead page defines the idea: isolate the elements of an application into pools so that if one element fails, the others continue to function. A consumer that sends requests to an unresponsive service keeps their resources (the page's example is a connection pool) unavailable for a long time; as requests continue the resources are exhausted, and then the consumer cannot reach any other service either. The remedy is to partition resources so those used to call one service cannot affect those used to call another, for example a connection pool per service.
Figure 3. A bulkhead per dependency. How to read this: a request that needs recommendations must first take one of that dependency's slots. When all are held by hung calls, the next such request is refused at once, and checkout, which uses the payments slots, is not affected.
Two ways to build one
The Resilience4j documentation names the two common forms:
| Form | How it limits | What the caller thread does |
|---|---|---|
| Semaphore bulkhead | A count of permits: at most N calls run at the same time | Runs the call itself; if no permit is free it waits up to a configured time (the documented default is 0) or is refused |
| Thread-pool bulkhead | A bounded queue and a fixed pool of threads for the dependency | Hands the work to the dedicated pool, so a hung call occupies the pool's thread and not the caller's |
The semaphore form is cheap and counts calls; the thread-pool form moves the work to other threads, which makes it possible to stop waiting for a call, at the price of a hand-off (see thread pools, executors and CompletableFuture). The documented defaults of the semaphore form are 25 concurrent calls and a wait of 0; the lab and the next lesson set their own values.
Bulkheads exist at other levels too. The Azure page lists consumer-side partitions (processes, thread pools, semaphores), service-side partitions (separate virtual machines, containers or processes), separate queues for asynchronous messages and partitions by tenant. Its trade-off is blunt: capacity set aside for one pool cannot help another, and it names unacceptable resource inefficiency as a reason not to use the pattern.
Sizing a bulkhead
Too small a bulkhead refuses healthy traffic; too large a one protects nothing. The average number of calls in progress is the arrival rate multiplied by the time each takes. At 290 calls per second and 40 ms per call (both illustrative), about 11.6 calls are in progress, and a limit of about 20 leaves headroom for bursts. If calls begin to take 5 seconds, 290 per second would want 1,450 in progress, and the limit holds it to 20 instead of letting it consume every thread. Measure real concurrency and latency before choosing the number, and revisit it as traffic grows.
Build it: a bulkhead in a Spring MVC shop
The second lab is new. It is a Spring Boot 4.1.2 lab, run entirely in memory: Spring MVC controllers are driven through MockMvc (no web server and no Docker), and the dependencies are fakes that the lab controls.
Goal. Show the shape of Figure 1 and Figure 3 with real threads: one pool of four request threads shared by two endpoints, one hanging dependency, with and without a bulkhead.
Setup. From the repository's examples/spring-labs folder:
cd examples/spring-labs && ./gradlew :labs:bulkhead-isolation:test
It runs the bulkhead's unit tests and a golden test that renders the report below and compares it with the committed file (-PwriteGolden rewrites the file after a deliberate change).
How it works. Bulkhead is a Semaphore with tryAcquire(): no free permit means an immediate BulkheadFullException, the equivalent of a wait of zero. ShopController exposes /checkout (payments) and /recommendations (recommendations, guarded when a bulkhead is passed in), and a BulkheadAdvice turns the exception into status 503. The fake Downstream blocks on a latch until the lab releases it. There are no sleeps: the lab waits for events such as "a call has started". The decisive lines are small:
public <T> T call(Supplier<T> action) {
if (!permits.tryAcquire()) {
rejected.incrementAndGet();
throw new BulkheadFullException(name, maxConcurrentCalls);
}
try {
return action.get();
} finally {
permits.release();
}
}
Expected output, captured from a real run (Spring Boot 4.1.2, compiled for Java 25, 2026-12-01):
1. No bulkhead: 4 shared request threads, recommendations hangs, payments is healthy
4 recommendations requests arrive and all start; threads busy: 4 of 4
a checkout request arrives and waits in the queue: queued=1, payments calls started=0
checkout finished? false
recommendations recovers; checkout status: 200
recommendations statuses: [200, 200, 200, 200]
2. Bulkhead of 2 on recommendations: same threads, same hanging dependency
2 recommendations requests start and hang; bulkhead slots free: 0 of 2
recommendations request 3 is refused at once with status 503
recommendations request 4 is refused at once with status 503
bulkhead rejected calls: 2, recommendations calls started: 2
a checkout request arrives; its status while recommendations still hangs: 200
recommendations statuses: [200, 200, 503, 503]
Run 1 is Figure 1: with every thread parked in recommendations, the checkout request is not even started (payments calls started=0) and finishes only once the unrelated dependency recovers. Run 2 is Figure 3: two calls hold the two slots, requests three and four get 503 immediately, and checkout is answered with 200 while recommendations still hangs. The bulkhead does not make recommendations faster; the two hung calls stay hung. It only decides how much of the shop they can hold.
Break it. In ShopController.recommendations, replace the bulkhead branch with a direct recommendations.call(): requests three and four are no longer refused, so the second run waits for a refusal that never comes and the golden test fails. Restore the line and run the tests again.
What the lab leaves out. A real servlet container's pool (four threads stand in for it), the breaker, timeouts and metrics.
Putting them together
The two controls compose, and the order matters. A common arrangement, and the default order of Resilience4j's annotations, puts retry outermost, then the breaker, then the bulkhead next to the call. Both guards reject before the dependency is touched, and only a call that gets through both is recorded by the breaker as a success or failure, so its statistics describe what the dependency really did.
Whether a rejection by the bulkhead should count as a failure for the breaker is a design decision: counting it makes the breaker open when you are the one that is saturated. The next lesson shows how Resilience4j treats each outcome. Whatever you choose, every refusal needs a fallback decided in advance, because a guard that rejects without a plan only moves the failure to the user.
Choosing and tuning: the trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Circuit breaker, count-based window | Simple, predictable on busy services | Tuning of window size and minimum calls; fires late on slow traffic | Traffic is too low to fill a window |
| Semaphore bulkhead | Cheap, counts calls, no extra threads | Caller threads still wait in the call; cannot stop waiting | The call cannot be bounded by a timeout |
| Thread-pool bulkhead | Isolates threads and allows giving up on a call | Thread hand-off, queue to size | Latency budget is tiny |
In practice: ShopStream's product page and checkout
This is the realistic example: an educational scenario on the course's running example ShopStream. Nothing in it describes a real company, and every number is an illustrative assumption.
This is a realistic scenario, not a case history.
The situation
ShopStream's product page calls a recommendations service and checkout calls a payment provider. Recommendations are optional; checkout is the business. The course's shared numbers give about 2,300 browsing requests per second and 58 checkouts per second at peak, served by 8 application servers with 200 request threads each (both illustrative).
Starting architecture
Every request thread can serve any endpoint. The product page calls recommendations with a 5-second timeout (illustrative). There is no breaker and no bulkhead.
Figure 4. The resilient request path. How to read this: the product page reaches recommendations through a bulkhead and checkout reaches the provider through a breaker. When either refuses, the caller gets a planned fallback: an empty list on the product page, and for checkout the order is accepted with payment pending, the degradation designed in the fallbacks lesson.
Options considered
| Option | What happens when recommendations hangs | Risk |
|---|---|---|
| A. Only shorter timeouts | Threads are held for less time, but at 2,300 requests per second the pool still fills | Short timeouts also cut healthy slow calls |
| B. Bulkhead on recommendations | At most its slots are held; the rest are refused at once | The limit must be sized and revisited |
The decision
Option B for recommendations and a circuit breaker for the payment provider, each with a fallback. Each of the 8 servers sees about 2,300 / 8 = 288 recommendation calls per second; at 40 ms (illustrative) about 11.5 are in progress, so a bulkhead of 20 per server (illustrative). If recommendations hangs for 5 seconds, 288 calls per second would want about 1,440 threads, and the pool of 200 would be gone in 200 / 288, under a second. The bulkhead holds the cost to 20 threads. For the provider, the breaker records time-outs and 5xx answers, not declined cards, and the open state returns "payment pending" so the order is kept.
Rollout and verification
A rollout would first observe only: a bulkhead limit high enough to refuse nothing, so the team reads real concurrency and failure rates before enforcing. It then tightens the limits on one server and watches refused-call counts. Verification is a game day: make recommendations hang in a test environment and confirm that checkout is unchanged while refused calls rise on the product page only.
The 2 a.m. failure
The page reads: checkouts are failing with "payment pending" although the provider's status page is green. The breaker is open. Its failure count was driven by HTTP 400 responses to malformed requests from a bad deployment of the checkout service itself: the provider was healthy and rejecting garbage, and the breaker counted each rejection as a dependency failure. The result was a self-inflicted outage for every customer.
The checks: the breaker's recorded failure types, the provider response codes in the minute before it opened, and the deploy log. The mitigation is to roll back the deploy and reset the breaker (Fowler says operations staff should be able to trip or reset breakers). The lasting fix is to classify failures: record time-outs, connection errors and 5xx responses, ignore client errors, alert when a breaker opens, and test the classification with a bad request.
The other side of this topic
A browser or mobile client can also protect itself and the server: stop calling an endpoint that keeps failing and show cached or reduced content. The same state machine applies, with different choices about storage and user messages. The frontend track covers it in its lesson on resilient interfaces and client-side circuit breakers.
Architect's notes
- Decide what counts as a failure before you pick thresholds. The classification matters more than the window size.
- Pair every guard with a fallback. A rejection with no plan is a faster error.
- Observe before you enforce. Set limits from measured concurrency, latency and failure rates.
- Alert on state changes. Fowler says every change in breaker state should be logged.
Common mistakes
- Counting caller errors as dependency failures. A bad request is not a sick provider.
- A bulkhead sized from a guess. Too small refuses healthy traffic; too large protects nothing.
- Retrying into an open breaker. Make retry stop on a rejection (the next lesson's lab shows the effect).
- A shared breaker for independent shards or providers. One bad shard blocks the rest.
- Expecting a bulkhead to speed anything up. The hung calls stay hung.
Key takeaways
- A circuit breaker is closed, open or half-open; failures past a threshold open it, a timer moves it to half-open, and trial calls decide whether it closes or reopens.
- Judge failure by rate over a window with a minimum number of calls, count slow calls too, and ignore errors that are the caller's fault.
- A bulkhead limits concurrent calls per dependency so a hanging dependency can hold only its own slots.
- The breaker answers "stop calling what keeps failing"; the bulkhead answers "do not let one thing take everything".
- Both reject before touching the dependency, so both need a fallback decided in advance; size limits from measurements and alert on state changes.
Practice exercises
Exercise 1 (20 min). For a window of 10 calls, a minimum of 5 and a threshold of 50 percent, list the shortest sequence that opens the breaker and one that does not.
Exercise 2 (45 min). Run both labs. In the breaker demo, change the open duration to 500 ms and predict every row before running. In the bulkhead report, say what changes if the bulkhead is 3.
Exercise 3 (2 hours). For ShopStream's search, notifications and courier tracking, decide which need a breaker, which a bulkhead and what the fallback is, and how you would measure the limits.
Related reading
- Resilience Patterns: breakers, bulkheads and shedding together.
- Timeouts, Retries, Backoff and Jitter: the bounds on one call that a breaker builds on.
- Load Shedding and Retry Storms: refusing work when you are the one overloaded.
- Graceful Degradation and Fallbacks: what to return when a guard refuses.
- Failure Handling End to End: the guards on one checkout path.
- Thread Pools, Executors and CompletableFuture: the pools a bulkhead protects.
- ShopStream Stage 9: Resilience: the same guards in the running project.
Official documentation
- Martin Fowler, CircuitBreaker.
- Azure Architecture Center, Circuit Breaker pattern and Bulkhead pattern.
- Resilience4j documentation, CircuitBreaker and Bulkhead.