Circuit Breaker in Spring Boot — Complete Guide With Real Example (2025 Edition)

 

Circuit Breaker in Spring Boot — Complete Guide With Real Example (2025 Edition)

Modern microservices constantly depend on other services — internal API calls, third-party services, databases, payment gateways, or internal microservice-to-microservice communication.

But what happens when one of those services becomes slow or unstable?

  • Your threads get stuck

  • Your service slows down

  • Requests start timing out

  • Your system collapses (cascading failure)

To prevent this, we use the Circuit Breaker Pattern.


1. What Is a Circuit Breaker?

A Circuit Breaker prevents your application from continuously calling a failing service.

It works like an electrical breaker:

  • Closed → ON → working normally

  • Open → OFF → stop calling the service

  • Half-Open → testing the service


2. Why Do We Use a Circuit Breaker?

ProblemWhat Circuit Breaker Does
Slow external APIStops further calls; returns fallback
Service downPrevents thread blocking
Too many failuresOpens circuit quickly
Cascading failuresProtects upstream services
Improves reliabilityFail fast instead of waiting

3. Circuit Breaker Lifecycle (Simple Diagram)

┌──────────────┐ │ CLOSED │ ← everything normal └───────┬──────┘ │ failures exceed threshold ▼ ┌──────────────┐ │ OPEN │ ← stop calling service └───────┬──────┘ │ wait duration expires ▼ ┌──────────────┐ │ HALF-OPEN │ ← send limited test calls └───────┬──────┘ │ success ▼ ┌──────────────┐ │ CLOSED │ ← service recovered └──────────────┘

4. What Happens When Multiple Failures Occur?

Consider this configuration:

failure-rate-threshold: 50 sliding-window-size: 10 minimum-number-of-calls: 5 wait-duration-in-open-state: 5s

✔ Step-by-Step Example

You call an endpoint 5 times:

Call 1 → FAIL Call 2 → FAIL Call 3 → FAIL Call 4 → FAIL Call 5 → FAIL

Now:

Total calls = 5 Failures = 5 Failure rate = 100% (greater than threshold 50%)

✔ Circuit Breaker immediately switches to OPEN.


5. What Happens in OPEN State?

NO calls are sent to the real endpoint.
⭐ Every call is immediately failed by the circuit breaker.
⭐ The fallback method is executed instantly.

This is called FAIL-FAST.

So yes:

“If 5 failures happen, the circuit will stop hitting that endpoint for a few seconds/minutes until it recovers.”


6. HALF-OPEN State (Testing Recovery)

After the wait-duration passes (5 seconds):

  • Circuit moves to HALF-OPEN

  • Allows limited number of test calls
    (permitted-number-of-calls-in-half-open-state)

If test calls succeed → circuit goes back to CLOSED
If test calls fail → circuit goes back to OPEN


7. CLOSED State (Recovered)

Once enough successful calls occur, the service is considered healthy again.

Circuit becomes CLOSED, and traffic flows normally.


8. Implementing Circuit Breaker in Spring Boot (Using Resilience4j)

Resilience4j is the most modern and recommended fault-tolerance library for Spring Boot (replacing Netflix Hystrix).


✔ Step 1: Add Dependencies (pom.xml)

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot3</artifactId> </dependency>

✔ Step 2: Add Configuration (application.yml)

resilience4j: circuitbreaker: instances: externalServiceCB: failure-rate-threshold: 50 sliding-window-size: 10 minimum-number-of-calls: 5 wait-duration-in-open-state: 5s permitted-number-of-calls-in-half-open-state: 3

✔ Step 3: Create a Service That Calls an External API

@Service public class ExternalApiService { private final RestTemplate restTemplate = new RestTemplate(); @CircuitBreaker(name = "externalServiceCB", fallbackMethod = "fallback") public String callExternalService() { // Simulating a failing service String url = "https://example.com/api/data"; return restTemplate.getForObject(url, String.class); } public String fallback(Exception ex) { return "Fallback: External service unavailable"; } }

✔ Step 4: Add Controller

@RestController public class DemoController { @Autowired private ExternalApiService apiService; @GetMapping("/get-data") public String getData() { return apiService.callExternalService(); } }

9. Testing the Circuit Breaker

Case A — External API is down

✔ First 5 attempts → failures
✔ Circuit goes OPEN
✔ All next requests return immediately:

Fallback: External service unavailable

Case B — After 5 seconds

✔ Circuit enters HALF-OPEN
✔ Allows 3 test calls
✔ If successful → closes
✔ If fails → stays open


10. Real Use Cases of Circuit Breaker

✔ Microservices communication

E.g., Order Service → Payment Service

✔ 3rd party systems

SMS gateways, Stripe, PayPal, email APIs.

✔ Database outage

Fail fast instead of waiting for JDBC timeout.

✔ Cloud-native systems

Network hiccups are common.

✔ High-traffic applications

Avoid saturating threads and CPU.


11. Final Summary (Interview-Ready)

  • Circuit Breaker protects your app from calling failing services.

  • After repeated failures, the circuit opens.

  • In OPEN state, service calls are blocked immediately.

  • Fallback method handles the failure gracefully.

  • After wait time, HALF-OPEN state tests service health.

  • If OK → CLOSE; if fail → OPEN again.

  • Prevents cascading failures and improves reliability.

No comments:

Post a Comment

Distributed Tracing in Spring Boot using OpenTelemetry + Jaeger (2025 Guide)

  Distributed Tracing in Spring Boot using OpenTelemetry + Jaeger (2025 Guide) This guide helps you understand: ✅ What is distributed trac...

Featured Posts