Circuit Breaker — a resilience pattern that prevents cascading failures by detecting when a downstream service is failing and short-circuiting calls to it, allowing the failing service to recover.
System Design Context: In a microservices architecture, Service A depends on Service B, which depends on Service C. If Service C is slow or down, Service B waits, consuming threads. Service A then waits for Service B, and the entire chain fails. The circuit breaker stops this cascade.
Three States:
Resilience4j — Production Implementation:
1@Service2@Slf4j3public class OrderService {45 private final WebClient webClient;6 private final CircuitBreaker circuitBreaker;7 private final Retry retry;89 public OrderService(WebClient.Builder builder,10 CircuitBreakerRegistry cbRegistry,11 RetryRegistry retryRegistry) {12 this.webClient = builder.baseUrl("http://user-service").build();13 this.circuitBreaker = cbRegistry.circuitBreaker("userService");14 this.retry = retryRegistry.retry("userService");15 }1617 @CircuitBreaker(name = "userService", fallbackMethod = "fallbackGetUser")18 @Retry(name = "userService")19 public User getUser(Long userId) {20 return webClient.get()21 .uri("/api/users/{id}", userId)22 .retrieve()23 .bodyToMono(User.class)24 .block();25 }2627 public User fallbackGetUser(Long userId, Exception e) {28 log.warn("Circuit breaker fallback for user {}: {}", userId, e.getMessage());29 return User.defaultValue();30 }3132 // Event listeners for observability33 @EventConsumer34 public void onCircuitBreakerEvent(CircuitBreakerEvent event) {35 log.info("Circuit breaker event: {} - {}", event.getEventType(),36 event.getCircuitBreaker().getName());37 }38}3940# application.yml41resilience4j:42 circuitbreaker:43 instances:44 userService:45 failureRateThreshold: 5046 slowCallRateThreshold: 10047 slowCallDurationThreshold: 2s48 slidingWindowSize: 1049 slidingWindowSizeType: COUNT_BASED50 minimumNumberOfCalls: 551 waitDurationInOpenState: 10s52 permittedNumberOfCallsInHalfOpenState: 353 automaticTransitionFromOpenToHalfOpenEnabled: true54 registerHealthIndicator: true55 retry:56 instances:57 userService:58 maxAttempts: 359 waitDuration: 500ms60 enableExponentialBackoff: true61 exponentialBackoffMultiplier: 262 retryExceptions:63 - java.io.IOException64 - java.util.concurrent.TimeoutException
Scaling Patterns:
Common Pitfalls:
Monitoring: