What is the Circuit Breaker pattern?
Topic: microservices, Resilience. Level: Intermediate.
Answer
A circuit breaker stops calling a failing dependency to let it recover and to fail fast. States:
- **Closed**: calls flow; failures are counted.
- **Open**: once a failure threshold is crossed, calls are rejected immediately (return a fallback) for a cooldown window.
- **Half-Open**: after cooldown, a few trial calls are allowed; success closes the circuit, failure re-opens it.
This prevents wasted work and cascading failures, and gives the downstream breathing room.
```java
CircuitBreakerConfig cfg = CircuitBreakerConfig.custom()
.failureRateThreshold(50) // open at 50% failures
.slowCallRateThreshold(80)
.slowCallDurationThreshold(Duration.ofSeconds(2))
.waitDurationInOpenState(Duration.ofSeconds(10))
.permittedNumberOfCallsInHalfOpenState(3)
.slidingWindowSize(20)
.build();
CircuitBreaker cb = CircuitBreaker.of("payment", cfg);
Supplier<Reply> decorated = CircuitBreaker.decorateSupplier(cb,
() -> paymentClient.charge(req));
Reply r = Try.ofSupplier(decorated).recover(ex -> Reply.declined()).get();
```