Sobes.tech
Senior

Explain how the Circuit Breaker works and its states.

sobes.tech AI

Answer from AI

A Circuit Breaker is a pattern used to increase the resilience of distributed systems. It prevents constant attempts to call a non-responsive service, helping to avoid overload and speed up recovery.

Main states of the Circuit Breaker:

  1. Closed — all requests pass as usual. If the error count exceeds a threshold, it switches to Open.
  2. Open — all requests are immediately rejected without attempting to call the service, allowing time for recovery.
  3. Half-Open — after a timeout, the Circuit Breaker allows a limited number of requests to check if the service has recovered. If the requests 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 = decoratedSupplier.get();
} catch (CallNotPermittedException ex) {
    // Circuit Breaker is in Open state, call is not permitted
}