In distributed systems, service failures are inevitable. When one microservice fails, it can cause cascading failures throughout the system. The Circuit Breaker pattern, inspired by electrical circuit breakers, prevents this by detecting failures and providing fallback mechanisms.
Why Circuit Breaker?
Traditional retry mechanisms can worsen failures by continuously calling failing services. Circuit breakers:
- Prevent cascading failures
- Provide graceful degradation
- Reduce latency by failing fast
- Allow time for recovery
Implementing with Spring Cloud Circuit Breaker
Spring Cloud provides a unified API for circuit breakers. Here's how to implement it:
1. Add Dependencies
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
2. Configure Circuit Breaker
# application.yml
resilience4j.circuitbreaker:
instances:
paymentService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 3
3. Implement with @CircuitBreaker
@Service
public class PaymentService {
@CircuitBreaker(name = "paymentService",
fallbackMethod = "processPaymentFallback")
public PaymentResponse processPayment(PaymentRequest request) {
// Call external payment gateway
return paymentGateway.process(request);
}
public PaymentResponse processPaymentFallback(PaymentRequest request,
Throwable t) {
log.error("Payment service failed, using fallback", t);
return PaymentResponse.builder()
.status("QUEUED")
.message("Payment will be processed later")
.build();
}
}
Monitoring and Metrics
Monitor circuit breaker states with Spring Boot Actuator:
/actuator/health
/actuator/circuitbreakers
/actuator/metrics/resilience4j.circuitbreaker.calls
Circuit breakers are essential for building resilient microservices. By implementing them properly, you can ensure your system remains available even when dependencies fail.