1. Overview
In this lesson, we’ll wrap a remote call with a circuit breaker so that a failing downstream service doesn’t drag the caller down with it. We’ll add Spring Cloud Circuit Breaker to an existing remote call and then watch the three states, Closed, Open, and Half-Open, in action as the downstream service goes down and comes back up.
The relevant module we need to import when starting this lesson is: circuit-breaker-start.
If we want to reference the fully implemented lesson, we can import: circuit-breaker-end.
2. The Cascade Failure Problem
Our starting project has two services that talk to each other. An upstream caller posts to task-service, which saves a campaign and then calls notification-service over HTTP to send a notification about the newly created campaign. On the happy path, both services are up, the notification goes out, and the request completes in milliseconds.
Now let’s think about what happens when notification-service becomes slow or stops responding. The RestClient inside task-service blocks, waiting for a response from the downstream service until the HTTP timeout fires. Every incoming request that reaches the save path holds a thread while it waits. The service’s thread pool fills up, and soon, task-service starts refusing requests unrelated to notifications. One slow dependency has cascaded into a broader outage, and the caller is now dragging its own clients down with it.
A couple of adjustments could partially help here. A shorter HTTP timeout reduces how long each thread waits, but every call still attempts the failing downstream and threads still pile up. A non-blocking HTTP client avoids exhausting the thread pool, but it still fires a request on every call regardless of whether the downstream is known to be failing. Neither approach automatically detects when notification-service has recovered.
What we need is a mechanism that lets task-service stop calling notification-service once it’s clear the downstream is failing, and then start retrying once conditions may have recovered.
3. The Circuit Breaker Pattern
The circuit breaker sits between the caller and the remote call. Its job is to detect that the remote side is failing and short-circuit subsequent calls so the caller’s threads aren’t wasted, then periodically check whether the remote side has recovered. The pattern is modeled as a small state machine with three states:
- Closed: calls pass through to the remote side and the breaker counts successes and failures. This is the normal operating mode.
- Open: a failure threshold has been crossed and the breaker rejects calls immediately, without touching the remote side. This is the state that actively protects the caller. No threads wait on a broken downstream, and failures return in milliseconds.
- Half-Open: after a wait window following Open, the breaker lets a limited number of trial calls through to probe for recovery. If those trials succeed, it goes back to Closed. If they fail, it returns to Open.
Two patterns often mentioned alongside the circuit breaker are the Bulkhead pattern, which isolates resources so a failure in one area can’t exhaust another, and the Rate Limiter pattern, which caps the volume of calls the caller makes. They’re outside the scope of this lesson, and Baeldung’s Resilience4j guide covers both for students who want to go further.
4. Setting Up Spring Cloud Circuit Breaker
Spring Cloud Circuit Breaker is an abstraction over several backend implementations. It exposes a common API, CircuitBreakerFactory, and we pick a backend by adding the corresponding starter rather than by coding to a backend-specific annotation. For this lesson, we’ll use the Resilience4j backend.
Let’s add the starter to task-service‘s pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
The version is managed by the Spring Cloud BOM, so we don’t specify it here.
Next, let’s configure a circuit breaker instance named campaign-cb by adding these properties to application.properties:
resilience4j.circuitbreaker.instances.campaign-cb.slidingWindowSize=5
resilience4j.circuitbreaker.instances.campaign-cb.minimumNumberOfCalls=5
resilience4j.circuitbreaker.instances.campaign-cb.failureRateThreshold=50
resilience4j.circuitbreaker.instances.campaign-cb.waitDurationInOpenState=10s
resilience4j.circuitbreaker.instances.campaign-cb.permittedNumberOfCallsInHalfOpenState=2
Each property maps directly to what we’ll observe in the walkthrough:
- slidingWindowSize and minimumNumberOfCalls: the breaker tracks the last five calls and waits for at least five before making a decision.
- failureRateThreshold: set to 50, so the breaker opens when half or more of those five calls fail.
- waitDurationInOpenState: set to 10s, the breaker stays Open for ten seconds before letting a trial call through.
- permittedNumberOfCallsInHalfOpenState: set to 2, two trial calls determine whether the breaker closes again or returns to Open.
By default, Resilience4j uses a much larger slidingWindowSize (100) and a longer waitDurationInOpenState (60 seconds). The five values above override those defaults and are set intentionally low so the state transitions become visible within seconds during this demo. In production, we’d normally use values closer to the defaults.
5. Wrapping a Remote Call With a Circuit Breaker
The idea is to wrap the notification call so the circuit breaker can track failures and short-circuit when the downstream is down.
5.1. The Existing Call
Let’s look at the save path in DefaultCampaignService. It already posts a notification through a RestClient configured with a hardcoded base URL pointing at notification-service:
public Campaign save(Campaign campaign) {
Campaign saved = campaignRepository.save(campaign);
NotificationDto notification = new NotificationDto(
"[email protected]",
"[email protected]",
"Campaign created: " + saved.getName(),
"Campaign with code " + saved.getCode() + " has been created.");
restClient.post()
.uri("/notification/send")
.contentType(MediaType.APPLICATION_JSON)
.body(notification)
.retrieve()
.toBodilessEntity();
return saved;
}
If notification-service is down, retrieve() blocks and eventually throws. That blocking is exactly what the circuit breaker should cut short once failures become consistent.
5.2. Adding the Circuit Breaker
Let’s inject a CircuitBreakerFactory into DefaultCampaignService via the constructor:
private CircuitBreakerFactory<?, ?> circuitBreakerFactory;
public DefaultCampaignService(
CampaignRepository campaignRepository,
RestClient.Builder restClientBuilder,
CircuitBreakerFactory<?, ?> circuitBreakerFactory) {
this.campaignRepository = campaignRepository;
this.restClient = restClientBuilder.baseUrl(NOTIFICATION_SERVICE_URL).build();
this.circuitBreakerFactory = circuitBreakerFactory;
}
Notice we’re injecting a factory, not a circuit breaker directly. The name we pass to create(…) is what partitions state. Call sites that use the same name share the same state machine, while different names track their successes and failures independently against different protected dependencies. For now, we’ll use just one name.
Now let’s route the notification call through the breaker:
public Campaign save(Campaign campaign) {
Campaign saved = campaignRepository.save(campaign);
NotificationDto notification = new NotificationDto(
"[email protected]",
"[email protected]",
"Campaign created: " + saved.getName(),
"Campaign with code " + saved.getCode() + " has been created.");
circuitBreakerFactory.create("campaign-cb")
.run(() -> restClient.post()
.uri("/notification/send")
.contentType(MediaType.APPLICATION_JSON)
.body(notification)
.retrieve()
.toBodilessEntity(),
throwable -> {
log.warn("Notification call skipped: {}", throwable.getMessage());
return null;
});
return saved;
}
The name campaign-cb ties this invocation to the configuration we added in Section 4.
The run method takes two arguments: a Supplier with the protected work (the code the breaker may short-circuit), and a Function that receives a Throwable and returns a fallback value. The breaker calls the fallback when it’s Open (no call is attempted) or when the Supplier throws (the failure is recorded first). From the outside, run always returns a value. The breaker and its fallback together form a single resilient boundary around the remote call.
We’re keeping the fallback deliberately small: log a warning and return null. We accept that a notification may be missed. Richer fallback handling, including call duration bounding and distinguishing business errors from system failures, goes beyond the scope of this lesson.
The breaker itself is the stateful instance the factory returns from create(“campaign-cb”), and each call to run(…) drives its state machine forward, which is what we’ll watch in the next section.
6. Walking Through the State Transitions
Now let’s watch the breaker actually do its job. The plan is to start both services, trigger the save path, and progress through the states by stopping and restarting notification-service.
Let’s start notification-service on port 8081 and task-service on port 8080. To trigger the save path, we’ll use the REST-requests.json file from src/main/resources, which we can import as a collection in Postman, and send its create campaign request against task-service. Note that each request needs a unique value for code.
6.1. Closed: Calls Succeed
Let’s send two or three POST /campaigns requests. Each one saves a campaign and fires a successful notification:
HTTP/1.1 201 Created
On the notification-service side, we’ll see incoming calls on /notification/send. There’s no visible breaker activity yet, and that’s exactly the point. The breaker is Closed, and calls flow through unchanged while it counts successes in its sliding window.
6.2. Transition to Open
Now let’s shut down notification-service and fire POST /campaigns requests in quick succession. Each request goes through the run(…) call we wrote in the previous section, so every attempt feeds the breaker’s view of what’s happening downstream.
One clarification before we continue. Shutting down notification-service produces an immediate connection-refused error, while the cascade-failure framing from Section 2 describes a slow or hanging dependency that blocks threads. The demo still shows the breaker’s fast-fail and short-circuit behavior correctly.
The first few calls fail because notification-service refuses the connection. Our fallback runs, logs a warning, and the campaign is still saved:
WARN Notification call skipped: I/O error on POST request for "http://localhost:8081/notification/send": null
The breaker is still Closed at this point because it’s accumulating failures in its sliding window. Each of those early requests still pays the full cost of trying to reach the downstream, which is what we want the breaker to cut short once the signal becomes unambiguous.
Once the sliding window holds at least five calls with a failure rate of 50% or more, the breaker transitions to Open. From this point, the next call no longer attempts the HTTP request at all. The fallback runs immediately, and the warning message changes to reflect that the breaker, not the HTTP call, decided to skip:
WARN Notification call skipped: CircuitBreaker 'campaign-cb' is OPEN and does not permit further calls
The request returns in milliseconds instead of waiting for a socket timeout. This is the moment the breaker is actively protecting task-service. Threads that would otherwise be blocked on a dead socket are free to serve other work, which is the property that prevents the cascade failure we opened with.
6.3. Half-Open: The Trial Call
Let’s wait about ten seconds without sending any requests. That’s the waitDurationInOpenState we configured earlier. Then we send a POST /campaigns request.
The breaker lets the request through as a trial call because it has transitioned to Half-Open. Since permittedNumberOfCallsInHalfOpenState is set to 2, up to two trial calls may be allowed before the breaker evaluates the outcome. If the trial calls indicate that notification-service is still failing and the failure-rate threshold is reached, the breaker transitions back to Open. Subsequent calls then fail fast and execute the fallback instead of making the HTTP call.
Half-Open is a temporary probing state, not a stable resting state. The breaker uses it to determine whether the downstream service has recovered before transitioning back to Closed or Open.
6.4. Recovery: Back to Closed
Now let’s restart notification-service and wait another ten seconds for the Open window to elapse.
Let’s send a POST /campaigns request. It goes through as the first Half-Open trial, and this time the call succeeds.
We’ve just watched the full cycle: Closed, Open, Half-Open, and back to Closed. Thanks to the Open phase, task-service stayed responsive the entire time, even while notification-service was down. Failures were contained at the call site that produced them, and calls resumed naturally when the downstream came back.
7. Conclusion
In this lesson, we’ve added a circuit breaker around a remote notification call and watched it detect failure, shield the caller, probe for recovery, and return to normal operation, all without any changes to the downstream service. The protection comes from a small piece of configuration and one wrapping call, and the caller stays healthy when the dependency doesn’t.
Richer failure handling, including fallback logic, call duration bounding, and distinguishing business errors from system failures, gets dedicated treatment in a later lesson. We’ll also revisit how the same circuit breaker protection applies when using a declarative client instead of a direct remote call.