Spring Boot & Microservices (50 Qs)•Part 3: Microservices, Distributed Systems & Observability (25 - 35)
What is the Circuit Breaker Pattern, and how do you implement it with Resilience4j in Spring Boot?
senior LevelCode ExampleSystem DesignMicroservices
In Simple Words: Prevents cascading failures when a downstream service is down:
- CLOSED: Traffic flows normally.
- OPEN: Failure rate exceeds threshold (e.g. 50%); requests fail fast immediately without calling the broken service.
- HALF-OPEN: After a wait duration, test requests are sent to check if the downstream service recovered.
java
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse chargeCard(PaymentRequest request) {
return restTemplate.postForObject("/payments", request, PaymentResponse.class);
}
public PaymentResponse paymentFallback(PaymentRequest request, Throwable ex) {
return new PaymentResponse("QUEUED_FOR_RETRY", "Payment service degraded");
}