The user wants a program that implements the Circuit Breaker pattern. This is a design pattern used in software development to detect failures and encapsulate the logic of preventing a failure from constantly recurring during maintenance, temporary external system failure, or unexpected system difficulties.
I need to explain what the Circuit Breaker pattern is briefly to provide context, and then provide a Python implementation (as it's a common, readable language for such patterns).
Key Concepts of Circuit Breaker:
-
States: It has three states:
- Closed: Normal operation. Requests go through. If failures exceed a threshold, it trips to Open.
- Open: The circuit is "broken". Requests fail immediately without attempting the actual operation. After a timeout, it moves to Half-Open.
- Half-Open: A limited number of test requests are allowed. If they succeed, the circuit goes back to Closed. If they fail, it goes back to Open.
-
Parameters:
- Failure threshold (number of failures before opening).
- Recovery timeout (time to wait before trying again).
- Expected exceptions (which exceptions count as failures).
-
Structure:
- A class (e.g.,
CircuitBreaker) that wraps a function call.
- State tracking mechanism.
- Thread safety (usually important in concurrent environments, though a simple example might skip strict locking for brevity, it's better to include basic thread safety or at least mention it).
Drafting the Code (Mental or Scratchpad):
-
Class: CircuitBreaker
-
State: Enum or constants (CLOSED, OPEN, HALF_OPEN).
-
Init:
failure_threshold: int
recovery_timeout: float (seconds)
expected_exception: type (tuple of types)
-
Internal State:
_state: string
_failure_count: int
_last_failure_time: timestamp
_lock: threading.Lock (for safety)
-
Method call(func, *args, **kwargs):
- Check state.
- If OPEN:
- Check if
recovery_timeout has passed since last_failure_time.
- If yes -> change to
HALF_OPEN.
- If no -> Raise
CircuitBreakerOpen exception immediately.
- If HALF_OPEN or CLOSED:
- Try executing
func.
- If success:
- Reset failure count.
- If
HALF_OPEN -> change to CLOSED.
- If exception:
- Increment failure count.
- Record time.
- If count >= threshold -> change to
OPEN.
- Re-raise the exception.
-
Decorator approach: It's very Pythonic to implement this as a decorator @circuit_breaker(...).
Refining the Implementation:
- Define Custom Exceptions: Need a specific exception for when the circuit is open (e.g.,
CircuitBreakerOpenError).
- State Management: Simple string comparison is fine for a demo, but an Enum is cleaner.
- Time Handling:
time.monotonic() is better than time.time() for measuring intervals.
- Context Manager: Also useful, but a Decorator is usually the primary use case. I'll stick to the Decorator approach.
Example Usage:
- Create a dummy function that fails sometimes (using
random).
- Wrap it with the circuit breaker.
- Run a loop to show the state changes.
Code Structure Plan:
- Imports (
time, threading, functools, random).
- Custom Exception definition.
CircuitBreaker class.
__init__
__call__ (makes it a decorator).
_execute
_allow_request
_record_success
_record_failure
- Example usage logic.
Self-Correction/Refinement during drafting:
- Thread Safety: Should I use locks? Yes, otherwise
_failure_count races can occur. I'll include a simple threading.Lock.
- Half-Open Logic: In Half-Open, usually only one request is allowed to pass to test the waters. If it fails, back to Open. If it succeeds, reset to Closed. A simple boolean or counter helps here. To keep it simple for a demo: In Half-Open, allow the request. If fail -> Open. If success -> Closed.
Final Code Structure:
CircuitBreakerState (Enum).
CircuitBreakerError.
CircuitBreaker class.
- Decorator wrapper.
- Simulation code.
Let's write the code.
import time
import threading
import functools
from enum import Enum, auto
class State(Enum):
CLOSED = auto()
OPEN = auto()
HALF_OPEN = auto()
class CircuitBreakerError(Exception):
pass
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=60, expected_exception=Exception):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.expected_exception = expected_exception
self.failure_count = 0
self.last_failure_time = 0
self.state = State.CLOSED
self.lock = threading.Lock()
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with self.lock:
# Check state logic
if self.state == State.OPEN:
if time.time() - self.last_failure_time > self.recovery_timeout:
self.state = State.HALF_OPEN
else:
raise CircuitBreakerError("Circuit is open")
try:
result = func(*args, **kwargs)
except self.expected_exception as e:
with self.lock:
self._record_failure()
raise e
with self.lock:
self._record_success()
return result
return wrapper
# Helper methods...
Wait, the lock scope in the wrapper is a bit messy in that draft.
If I hold the lock while executing func, I serialize everything, which kills performance.
Correct logic:
- Check state (lock).
- If Open -> raise.
- If allowed -> run
func (no lock).
- On success/fail -> update state (lock).
Also, handling Half-Open specifically:
Usually, in Half-Open, we allow one request. If it succeeds, close. If it fails, open immediately.
Let's refine the wrapper logic:
def wrapper(*args, **kwargs):
# 1. Pre-check (State determination)
with self.lock:
current_state = self.state
if current_state == State.OPEN:
if time.time() - self.last_failure_time > self.recovery_timeout:
self.state = State.HALF_OPEN
current_state = State.HALF_OPEN
else:
raise CircuitBreakerError("Circuit Breaker is OPEN")
# 2. Execution
try:
result = func(*args, **kwargs)
except Exception as e:
# 3. Failure Handling
# Only catch expected exceptions
if isinstance(e, self.expected_exception):
with self.lock:
self._on_failure()
raise e
# 4. Success Handling
with self.lock:
self._on_success()
return result
This looks safer. The Half-Open logic in on_success resets everything. The on_failure increments count and potentially moves to Open (or immediately to Open if in Half-Open).
Let's write the final response.
Here is a clean, thread-safe implementation of the Circuit Breaker pattern in Python.
The Concept
A Circuit Breaker prevents an application from repeatedly trying to execute an operation that is likely to fail. It has three states:
- Closed: (Normal) Requests pass through. If failures exceed a threshold, the circuit trips to Open.
- Open: (Failing) Requests are blocked immediately. After a timeout, the circuit enters Half-Open.
- Half-Open: (Testing) A limited number of requests are allowed through to test the service. If they succeed, the circuit closes. If they fail, it opens again.
The Implementation
import time
import threading
import functools
from enum import Enum, auto
class CircuitState(Enum):
CLOSED = auto()
OPEN = auto()
HALF_OPEN = auto()
class CircuitBreakerError(Exception):
"""Custom exception raised when the circuit is open."""
pass
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=30, expected_exception=Exception):
"""
:param failure_threshold: Number of failures before opening the circuit.
:param recovery_timeout: Seconds to wait before attempting to close the circuit (Half-Open).
:param expected_exception: The type of exception that counts as a failure.
"""
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.expected_exception = expected_exception
self.failure_count = 0
self.last_failure_time = 0
self.state = CircuitState.CLOSED
# Lock for thread safety
self._lock = threading.RLock()
def _on_success(self):
"""Reset state on successful call (mostly used in Half-Open)."""
with self._lock:
self.failure_count = 0
self.state = CircuitState.CLOSED
def _on_failure(self):
"""Handle a failed attempt."""
with self._lock:
self.failure_count += 1
self.last_failure_time = time.time()
if self.state == CircuitState.HALF_OPEN:
# If it failed while testing, open immediately
self.state = CircuitState.OPEN
elif self.failure_count >= self.failure_threshold:
# If threshold reached, open the circuit
self.state = CircuitState.OPEN
def _allow_request(self):
"""Check if a request should be permitted."""
with self._lock:
if self.state == CircuitState.CLOSED:
return True
if self.state == CircuitState.OPEN:
# Check if enough time has passed to try again
if (time.time() - self.last_failure_time) >= self.recovery_timeout:
# Transition to Half-Open
self.state = CircuitState.HALF_OPEN
return True
return False
if self.state == CircuitState.HALF_OPEN:
# In a simple implementation, we allow 1 request through to test
# More complex versions might limit this rate
return True
return False
def call(self, func, *args, **kwargs):
"""Execute the function protected by the circuit breaker."""
if not self._allow_request():
raise CircuitBreakerError("Circuit Breaker is OPEN")
try:
result = func(*args, **kwargs)
self._on_success()
return result
except self.expected_exception as e:
self._on_failure()
raise e
def __call__(self, func):
"""Decorator support."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
return self.call(func, *args, **kwargs)
return wrapper
# ==========================================
# Example Usage
# ==========================================
# 1. Define a simulated unstable service
class UnstableService:
def __init__(self):
self.attempt_count = 0
def fetch_data(self):
self.attempt_count += 1
# Simulate a service that fails for the first 8 calls, then succeeds
if self.attempt_count <= 8:
print(f" [Service] Attempt {self.attempt_count}: Failing (Simulated Error)")
raise ConnectionError("Service unavailable")
else:
print(f" [Service] Attempt {self.attempt_count}: Success!")
return {"data": "valid_response"}
# 2. Configure the Circuit Breaker
# Trip after 3 failures, wait 5 seconds before retrying
breaker = CircuitBreaker(
failure_threshold=3,
recovery_timeout=5,
expected_exception=ConnectionError
)
service = UnstableService()
# Wrap the method with the circuit breaker logic
protected_fetch = breaker.call
print("--- Starting Circuit Breaker Test ---")
# 3. Run tests
for i in range(1, 12):
print(f"Client Request {i}:", end=" ")
try:
# Attempt to call the service
result = protected_fetch(service.fetch_data)
print(f"Result: {result}")
except CircuitBreakerError:
print("Blocked by Circuit Breaker (Fast Fail).")
except ConnectionError as e:
print(f"Caught Exception: {e}")
# Brief sleep to simulate processing time,
# and to allow the recovery timeout to pass eventually
time.sleep(1)
print("--- Test Complete ---")
How to Interpret the Output
If you run this code, you will see the pattern emerge:
- Requests 1-3: The service fails. The Circuit Breaker (initially CLOSED) counts the failures.
- Request 4: The failure threshold (3) is reached. The Circuit Breaker trips to OPEN. The code raises
CircuitBreakerError immediately without calling the actual service (Fast Fail).
- Requests 5-7: The Circuit Breaker is still OPEN. Time has not exceeded the
recovery_timeout (5 seconds). Calls are blocked.
- Request 8 (approx): 5 seconds have passed. The Circuit Breaker transitions to HALF_OPEN. It allows one call through.
- Since our simulated service is still failing at this point, the call fails.
- The Circuit Breaker immediately trips back to OPEN.
- Requests 9-10: Blocked again because it opened anew.
- Request 11+: The timeout passes again. The breaker enters HALF_OPEN. By now, the simulated service logic (count > 8) returns success. The breaker sees the success, resets the failure count, and goes back to CLOSED.
Usage as a Decorator
You can also use the class as a decorator directly on functions:
@CircuitBreaker(failure_threshold=2, recovery_timeout=10)
def critical_api_call():
# logic here
pass