Junior — Middle
Kas saaksite selgitada Circuit Breaker mustri tööpõhimõtet ja selle rolli süsteemi usaldusväärsuse tagamisel?
sobes.tech AI
Vastus AI-lt
The Circuit Breaker pattern is used to increase the reliability of distributed systems by preventing repeated calls to a failing or slow-responding service.
How it works:
- Closed (closed state): All requests pass as usual.
- Open (open state): If the error count exceeds a threshold, the Circuit Breaker «opens» — new requests immediately receive an error without attempting to call the service.
- Half-Open (half-open state): After some time, the Circuit Breaker allows a limited number of requests to check if the service has recovered.
If requests succeed, the state returns to Closed; otherwise, it goes back to Open.
This prevents overload on a non-functioning service and allows the system to recover faster.
Example usage in Go (simplified):
// Pseudo-code
cb := NewCircuitBreaker()
if cb.AllowRequest() {
err := callRemoteService()
if err != nil {
cb.RecordFailure()
} else {
cb.RecordSuccess()
}
} else {
// Return error immediately without calling the service
}
Thus, the Circuit Breaker helps make the system more resilient to failures.