β Back to Gallery
π‘οΈ
Circuit Breaker Pattern
Definition
The Circuit Breaker Pattern prevents an application from repeatedly trying to execute an operation that's likely to fail. It monitors for failures and, when a threshold is reached, trips the circuit breaker to prevent further attempts. After a timeout, it allows test requests to check if the underlying issue is resolved.
When to Use It
- Protecting against cascading failures in distributed systems
- Calling remote services that might be unavailable
- You want to fail fast instead of waiting for timeouts
- Implementing graceful degradation
- Providing fallback mechanisms
- Systems requiring high availability
Pros & Cons
β Pros
- Prevents cascading failures
- Fail fast instead of long timeouts
- Improves system stability
- Automatic recovery detection
- Better resource utilization
- Enables graceful degradation
β Cons
- Adds complexity to the system
- Requires careful threshold tuning
- May block valid requests temporarily
- Monitoring overhead
- State management required
- Testing edge cases is complex
Architecture Diagram
Circuit Breaker States and Flow
================================
ββββββββββββββββ
βββββββ€ CLOSED βββββββ
β β (Normal) β β
β ββββββββ¬ββββββββ β
β β β
Success β β Failure β Reset
Count β β Threshold β Timer
Reset β βΌ Exceeded β
β ββββββββββββββββ β
β β OPEN β β
β β (Blocking) β β
β ββββββββ¬ββββββββ β
β β β
β β Timeout β
β βΌ β
β ββββββββββββββββ β
ββββββΊβ HALF-OPEN βββββββ
β (Testing) β
ββββββββββββββββ
Request Flow:
βββββββββββββ
ββββββββββββ ββββββββββββββββββββ ββββββββββββ
β β β Circuit Breaker β β External β
β Client ββββββββββΊβ ββββββββββΊβ Service β
β β Request β State: CLOSED β Forward β β
ββββββββββββ ββββββββββββββββββββ ββββββββββββ
β
β Track Failures
βΌ
βββββββββββββββββββ
β Failure Count β
β Exceeds Limit? β
ββββββββββ¬βββββββββ
β Yes
βΌ
βββββββββββββββββββ
β State: OPEN β
β Return Error β
β (Fail Fast) β
ββββββββββ¬βββββββββ
β Wait Timeout
βΌ
βββββββββββββββββββ
β State: HALF-OPENβ
β Allow Test Req β
ββββββββββ¬βββββββββ
β
ββββββββββ΄βββββββββ
β β
Successβ βFailure
βΌ βΌ
ββββββββββββ ββββββββββββ
β CLOSED β β OPEN β
ββββββββββββ ββββββββββββ
Configuration:
β’ Failure Threshold: 5 failures
β’ Timeout: 30 seconds
β’ Success Threshold: 2 successes