Senior
How does the Circuit Breaker pattern work?
sobes.tech AI
Answer from AI
The Circuit Breaker pattern is used to prevent repeated calls to a failing or slow-responding service, in order to avoid excessive load and speed up error handling.
Main states of the Circuit Breaker:
- Closed: all requests pass as usual.
- Open: after a certain number of failures, calls are immediately blocked, returning an error without attempting to contact the service.
- Half-Open: after some time since opening, the Circuit Breaker allows a limited number of requests to check if the service has recovered.
Working principle:
- In the Closed state, the error counter tracks the number of failed calls.
- If too many errors occur in a short period, it switches to Open.
- In Open, all calls are immediately rejected to give the service time to recover.
- After a timeout, it transitions to Half-Open, where it tests the service.
- If the test calls succeed, it returns to Closed; otherwise, it goes back to Open.
Example in Java using the Resilience4j library:
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("myCircuitBreaker");
Supplier<String> decoratedSupplier = CircuitBreaker
.decorateSupplier(circuitBreaker, () -> remoteService.call());
Try<String> result = Try.ofSupplier(decoratedSupplier)
.recover(throwable -> "Fallback response");