The user wants a program that implements the Circuit Breaker pattern.
-
Understand the Goal: The objective is to create a code example demonstrating 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.
-
Identify Key Concepts:
- States: The Circuit Breaker has three main states:
- Closed: Normal operation. Requests go through. Failures are counted. If failures exceed a threshold, move to Open.
- Open: Requests fail immediately (fallback/error) without hitting the external service. After a timeout, move to Half-Open.
- Half-Open: A limited number of requests are allowed to pass through to test the health of the service. If successful, move to Closed. If failed, move back to Open.
- Parameters:
- Failure Threshold: Number of failures required to trip the breaker.
- Timeout/Reset Timeout: Time to wait before attempting to recover (transitioning from Open to Half-Open).
- Success Threshold (Optional): Number of successes required in Half-Open to close.
- Concurrency: Since this is often used in multi-threaded environments (like a web server calling a database or API), the implementation needs to be thread-safe.
-
Select a Programming Language: Python is a great choice for readability and pseudo-code-like structure, but Java or C# are also common in enterprise contexts. I will stick with Python as it's universally understood, but I will structure it like a library/class so it's reusable.
-
Drafting the Implementation (Python):
- Class Structure:
CircuitBreaker
- Initialization: Needs the function to protect, failure threshold, recovery timeout.
- State Management: Enum for
CLOSED, OPEN, HALF_OPEN.
- The Call Logic: A method
call or execute.
- Thread Safety: Use
threading.Lock.
-
Refining the Logic (Step-by-Step):
- State: Start as
CLOSED.
- Calling in CLOSED:
- Try
func().
- If success: reset failure count.
- If exception: increment failure count. If count >= threshold, switch to
OPEN and record last_failure_time.
- Calling in OPEN:
- Check
current_time - last_failure_time.
- If time < timeout: Raise Exception immediately (Circuit Breaker is Open).
- If time >= timeout: Switch to
HALF_OPEN.
- Calling in HALF_OPEN:
- Try
func().
- If success: Switch to
CLOSED, reset stats.
- If fail: Switch back to
OPEN, reset last_failure_time.
-
Adding "Syntactic Sugar" (Decorator): In Python, decorators are the Pythonic way to wrap functions. I should implement the class logic first, then wrap it in a decorator for ease of use.
-
Writing the Code (Mental Draft & Refinement):
-
Creating a Simulation/Demo:
- Need an external service simulation (flakey function).
- Need a loop that calls the protected function.
- Show the transition: Closed -> Open -> Half-Open -> Closed (or back to Open).
-
Reviewing against Best Practices:
- Thread Safety: The logic above isn't thread-safe. Multiple threads could change the state simultaneously. Need a Lock. I will add
with self.lock: in the critical sections.
- Async: For simplicity, I will stick to synchronous Python code. Async requires
asyncio locks, which complicates the example unnecessarily for a general understanding.
-
Final Code Structure:
- Imports.
- CircuitBreakerError class.
- CircuitBreaker class (Thread-safe).
- Decorator function.
- Example usage (UnreliableService).
- Main loop to demonstrate.
-
Self-Correction during drafting:
- Initial thought: Should I count successes in Half-Open?
- Correction: Usually, a single success in Half-Open is enough to close it, or a small number. For this example, 1 success -> Closed is simplest and standard.
- Exception handling: Should it catch all exceptions? Yes, usually, or allow a list of expected exceptions. I'll catch generic Exception for the demo but mention it should be specific in production.
-
Output Generation: (Proceeding to generate the Python code based on these steps). I will also explain the states clearly in the text accompanying the code.
(Self-Correction regarding the specific request): The user asked for a "program". Providing just a library class is good, but a complete runnable script that simulates the behavior is better.
Let's write the Python code.
- State Enum: CLOSED, OPEN, HALF_OPEN.
- CircuitBreaker Class:
__init__: thresholds.
call: the main logic.
_handle_success: transition logic on success.
_handle_failure: transition logic on failure.
- Demo:
- Function that works 50% of the time.
- Loop calling it, printing state changes.
This looks solid. I will ensure the comments explain the flow. I will also verify the "Half-Open" logic is correct: it allows one request through. If that fails, back to Open. If succeeds, Close. (Actually, in a highly concurrent system, you might let a few through, but let's keep it simple: Half-Open allows the next attempt).
Wait, in Half-Open, if multiple threads hit it simultaneously, it's tricky. With a simple Lock, only one enters the critical section. I will implement it such that if it's Half-Open, we try the call. If it fails, we lock, set to Open. If it succeeds, we lock, set to Closed.
Let's go.
Here is a complete, thread-safe implementation of the Circuit Breaker pattern in Python.
The Logic
The Circuit Breaker acts as a proxy for operations that might fail. It has three states:
- CLOSED: Everything is normal. Requests pass through. If failures exceed a threshold, it trips to OPEN.
- OPEN: Requests are blocked immediately (failing fast). After a timeout, it moves to HALF-OPEN.
- HALF-OPEN: A limited number of requests are allowed through to test the service. If they succeed, the breaker closes. If they fail, it opens again.
The Implementation
import time
import threading
import random
from enum import Enum, auto
from functools import wraps
class State(Enum):
CLOSED = auto()
OPEN = auto()
HALF_OPEN = auto()
class CircuitBreakerError(Exception):
"""Raised when the circuit is open."""
pass
class CircuitBreaker:
def __init__(self, name, failure_threshold=3, recovery_timeout=5, expected_exception=Exception):
"""
:param failure_threshold: Number of failures before opening the circuit.
:param recovery_timeout: Seconds to wait before switching from OPEN to HALF_OPEN.
:param expected_exception: The type of exception that counts as a failure.
"""
self.name = name
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.expected_exception = expected_exception
self._state = State.CLOSED
self._failure_count = 0
self._last_failure_time = 0
self._lock = threading.RLock()
@property
def state(self):
with self._lock:
if self._state == State.OPEN:
# Check if timeout has elapsed to move to HALF_OPEN
if time.time() - self._last_failure_time >= self.recovery_timeout:
self._state = State.HALF_OPEN
return self._state
def call(self, func, *args, **kwargs):
"""Executes the protected function."""
with self._lock:
current_state = self.state # Property handles the OPEN -> HALF_OPEN logic
if current_state == State.OPEN:
raise CircuitBreakerError(f"CircuitBreaker [{self.name}] is OPEN")
# Attempt the actual call outside the lock to avoid blocking other threads
# during the network request/execution.
try:
result = func(*args, **kwargs)
self.on_success()
return result
except self.expected_exception as e:
self.on_failure()
raise e
def on_success(self):
"""Called when the operation succeeds."""
with self._lock:
if self._state == State.HALF_OPEN:
# If successful in half-open state, reset completely
self._state = State.CLOSED
self._failure_count = 0
print(f"[{self.name}] SUCCESS in HALF_OPEN. Closing Circuit.")
elif self._state == State.CLOSED:
# Reset failure count on success
self._failure_count = 0
def on_failure(self):
"""Called when the operation fails."""
with self._lock:
self._failure_count += 1
self._last_failure_time = time.time()
if self._state == State.HALF_OPEN:
# If failed during test, open immediately
self._state = State.OPEN
print(f"[{self.name}] FAILURE in HALF_OPEN. Re-opening Circuit.")
elif self._state == State.CLOSED:
if self._failure_count >= self.failure_threshold:
self._state = State.OPEN
print(f"[{self.name}] Failure threshold reached ({self._failure_count}). Opening Circuit.")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Allows usage in `with` blocks if manual management is preferred
pass
# Decorator for easy usage
def circuit_breaker(name, failure_threshold=3, recovery_timeout=5):
def decorator(func):
cb = CircuitBreaker(name, failure_threshold, recovery_timeout)
@wraps(func)
def wrapper(*args, **kwargs):
return cb.call(func, *args, **kwargs)
# Attach the breaker instance to the function for inspection if needed
wrapper.breaker = cb
return wrapper
return decorator
# ==========================================
# EXAMPLE USAGE SIMULATION
# ==========================================
# A simulated unreliable service
class UnstableService:
def __init__(self):
self.should_fail = True
def toggle(self):
self.should_fail = not self.should_fail
status = "FAILING" if self.should_fail else "WORKING"
print(f"\n>>> [SYSTEM] Service state toggled to: {status} <<<\n")
def request(self):
if self.should_fail:
raise ConnectionError("Database connection lost")
return "200 OK"
# Instantiate service
service = UnstableService()
# Apply Circuit Breaker Decorator
# We tell the breaker to only catch ConnectionError
@circuit_breaker(name="DatabaseService", failure_threshold=3, recovery_timeout=5)
def protected_request():
return service.request()
def run_simulation():
print("Starting Simulation...")
print("-----------------------")
# 1. Run until failure threshold is reached (Circuit Opens)
for i in range(5):
try:
print(f"Attempt {i+1}: Calling service...")
response = protected_request()
print(f"Attempt {i+1}: Response {response}")
except ConnectionError as e:
print(f"Attempt {i+1}: Caught Expected Error: {e}")
except CircuitBreakerError as e:
print(f"Attempt {i+1}: Caught Circuit Breaker: {e}")
time.sleep(0.5)
# 2. Try to call while Circuit is Open (Should fail fast)
print("\nTrying while circuit is OPEN (should fail instantly)...")
try:
protected_request()
except CircuitBreakerError as e:
print(f"Fast Failure: {e}")
# 3. Wait for recovery timeout (Circuit goes to Half-Open)
print(f"\nWaiting 6 seconds for recovery timeout...")
time.sleep(6)
# 4. Try again (Service is still down, so Half-Open -> Open)
print("Timeout passed. Attempting request (Service is still down)...")
try:
protected_request()
except (ConnectionError, CircuitBreakerError) as e:
print(f"Result: {e}")
# 5. Fix the service and wait for timeout again
service.toggle() # Service is now working
print(f"\nWaiting 6 seconds for recovery timeout again...")
time.sleep(6)
# 6. Try again (Service is UP, so Half-Open -> Closed)
print("Timeout passed. Attempting request (Service is UP)...")
try:
response = protected_request()
print(f"SUCCESS! Response: {response}")
except Exception as e:
print(f"Unexpected Error: {e}")
# 7. Verify Circuit is Closed
print("Circuit state should be CLOSED now. Trying normal request...")
print(f"Result: {protected_request()}")
if __name__ == "__main__":
run_simulation()
How this code works:
- Thread Safety: It uses
threading.RLock (Reentrant Lock). This ensures that if multiple threads try to check the state or update the failure count simultaneously, the data remains consistent.
- State Property: The
@property def state method handles the time logic. Even if the internal state is OPEN, if enough time has passed (recovery_timeout), accessing the property returns HALF_OPEN.
- The Decorator: The
@circuit_breaker decorator allows you to wrap any function easily. You configure the failure threshold (how many times it can crash) and the timeout (how long to wait before retrying).
- Handling Exceptions: The breaker catches specific exceptions (in this example,
ConnectionError). If your code throws a different kind of exception (like a ValueError), the circuit breaker ignores it, letting it bubble up, because usually you only want to trip the breaker on infrastructure/network errors, not code logic errors.
Sample Output Explanation
- Attempts 1-3: The service fails. The breaker counts failures.
- Attempt 3: The threshold is reached. The breaker prints "Opening Circuit".
- Attempt 4: The code tries to call the function. The breaker immediately raises
CircuitBreakerError without touching the service.
- Wait: The simulation sleeps for 6 seconds.
- Retry: The breaker enters
HALF_OPEN. It allows one call. Since the service is still broken, it fails, and the breaker immediately goes back to OPEN.
- Fix & Wait: We toggle the service to "Working" and wait again.
- Final Retry: The breaker enters
HALF_OPEN, allows the call, it succeeds, and the breaker resets to CLOSED.