Circuit Breaker Pattern in Spring Boot using Resilience4j
“When things go wrong, stop hitting the wall — use a Circuit Breaker.”
Circuit Breaker Pattern in Spring Boot using Resilience4j
Have you ever seen your API crash because one downstream service failed? I did — and that’s when I learned about the Circuit Breaker pattern.
💡 What is a Circuit Breaker?
Imagine you’re calling another service — maybe a payment gateway or inventory API and that service goes down. Your application keeps calling it again and again… slowing down or crashing your system too.
That’s where the Circuit Breaker pattern comes in.
It acts like a fuse in an electrical circuit. If the downstream service keeps failing, the circuit breaker “opens” and blocks further calls for a while — protecting your app from cascading failures.
⚙️ Why Use Resilience4j?
Resilience4j is a lightweight fault tolerance library designed for Java 8 and functional programming. It offers modules for:
✅ Circuit Breaker ✅ Retry ✅ Rate Limiter ✅ Bulkhead ✅ Time Limiter ✅ Cache
You can use any or all of them — independently.
🧩 Circuit Breaker States Explained
Here’s how the Circuit Breaker lifecycle works:
StateDescriptionClosedAll requests pass through. Failures are counted. OpenRequests are blocked after reaching a failure threshold. Half-Open After a wait time, limited requests are allowed to test recovery. Closed (again)If the service is back, circuit closes and normal flow resumes.
🧭 Circuit Breaker Flow Diagram
Here’s a simple diagram showing the behavior:
┌─────────────┐ Success ┌──────────────┐
│ Closed │ ─────────────────▶│ Closed │
│ (Normal) │ │ (Reset Fail) │
└──────┬──────┘
│
│ Failures exceed threshold
▼
┌─────────────┐
│ Open │ <─── Timer expires ───
│ (Block Calls)│ │
└──────┬──────┘ │
│ │
▼ │
┌─────────────┐─────────────────────┘
│ Half-Open │ (Test few requests)
└─────────────┘
🧱 Add Dependency
In your pom.xml:
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.2.0</version>
</dependency>
For Spring Boot 2, use resilience4j-spring-boot2.
🚀 Example Implementation
Let’s say you have a service calling an external REST API.
Step 1: Create a Service
@Service
public class ProductService {
private final RestTemplate restTemplate;
public ProductService(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
@CircuitBreaker(name = "productService", fallbackMethod = "fallbackProduct")
public String getProducts() {
String url = "https://external-api.com/products";
return restTemplate.getForObject(url, String.class);
}
// fallback method
public String fallbackProduct(Throwable t) {
return "External service is down. Showing cached or default products.";
}
}
Step 2: Define Configuration (optional)
In application.yml:
resilience4j:
circuitbreaker:
instances:
productService:
registerHealthIndicator: true
failureRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 3
slidingWindowSize: 10
slidingWindowType: COUNT_BASED
Step 3: Create a Controller
@RestController
@RequestMapping("/api")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/products")
public String fetchProducts() {
return productService.getProducts();
}
}
🔍 Test the Flow
- Start your Spring Boot app.
- Hit the
/api/productsendpoint. - If the external API fails multiple times, Resilience4j will open the circuit.
- You’ll receive the fallback message instead of repeated slow failures.
You can monitor it using Actuator endpoints like:
/actuator/health or /actuator/metrics/resilience4j.circuitbreaker.state
🧰 Bonus: Combine with Retry
You can chain Retry with Circuit Breaker for extra fault tolerance.
@Retry(name = "productRetry")
@CircuitBreaker(name = "productService", fallbackMethod = "fallbackProduct")
public String getProducts() {
...
}
🎯 Key Takeaways
- Circuit Breaker prevents system overload when a dependency fails.
- Resilience4j is modular, easy to integrate, and production-ready.
- Always use fallbacks to provide a graceful degradation.
- You can combine Retry + CircuitBreaker for more robustness.
🧑💻 Key notes:
“How does Circuit Breaker work internally?”
“Resilience4j maintains a state machine per circuit. It records success/failure in a sliding window. Once failure rate crosses a threshold, it opens the circuit rejecting calls immediately. After a cooldown, it switches to half-open to test if the remote service is back. This prevents resource exhaustion and improves resilience.”
메타데이터
- post_id
- 241ee22cff2b
- slug
- circuit-breaker-pattern-in-spring-boot-using-resilience4j-241ee22cff2b
- url
- https://medium.com/@artipatel1994/circuit-breaker-pattern-in-spring-boot-using-resilience4j-241ee22cff2b
- canonical_url
- https://medium.com/@artipatel1994/circuit-breaker-pattern-in-spring-boot-using-resilience4j-241ee22cff2b
- author_url
- https://medium.com/@artipatel1994
- status
- ok
- fetched_at
- 2026-08-09 06:43:16