Sobes.tech
Junior — Middle

Can you explain how the Circuit Breaker pattern works and its role in system reliability?

sobes.tech AI

Answer from AI

The Circuit Breaker pattern is used to increase the reliability of distributed systems by preventing repeated calls to a service that is not working or responding slowly.

How it works:

  1. Closed state: All requests pass as usual.
  2. Open state: If the error count exceeds a threshold, the Circuit Breaker "opens" — new requests immediately fail without attempting to call the service.
  3. Half-Open state: After some time, the Circuit Breaker allows a limited number of requests to check if the service has recovered.

If the requests are successful, the state returns to Closed; otherwise, it goes back to Open.

This prevents excessive load on the non-functioning service and allows the system to recover faster.

Example of usage in Go (simplified):

// Pseudocode
cb := NewCircuitBreaker()

if cb.AllowRequest() {
    err := callRemoteService()
    if err != nil {
        cb.RecordFailure()
    } else {
        cb.RecordSuccess()
    }
} else {
    // Return an error immediately without calling the service
}

Thus, the Circuit Breaker helps make the system more resilient to failures.