Sobes.tech
Senior

Circuit Breaker: implementation and states of the algorithm.

sobes.tech AI

Answer from AI

Circuit Breaker is a pattern for increasing the resilience of distributed systems, preventing repeated calls to a failing service.

Main states:

  1. Closed — all requests pass as usual.
  2. Open — requests are blocked immediately to avoid overloading the non-functioning service.
  3. Half-Open — after a timeout, a limited number of requests are attempted to check if the service has recovered.

Working principle:

  • When the error threshold is exceeded (e.g., 5 consecutive failures), it switches to Open.
  • After a specified timeout, it transitions to Half-Open and attempts requests.
  • If requests succeed, it returns to Closed; otherwise, it switches back to Open.

Implementations in Java:

  • Resilience4j library — modern, lightweight, supports Circuit Breaker, Rate Limiter, etc.
  • Netflix Hystrix — popular but outdated.

Example of using Resilience4j CircuitBreaker:

CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("myCircuitBreaker");
Supplier<String> decoratedSupplier = CircuitBreaker
    .decorateSupplier(circuitBreaker, () -> remoteService.call());

Try<String> result = Try.ofSupplier(decoratedSupplier)
    .recover(throwable -> "Fallback response");

This approach helps avoid cascading failures and improves system stability.