Circuit Breaker with Hedging: A Resilient Request Pattern
Ah, a classic reliability puzzle in distributed systems! You're describing an advanced circuit breaker enhanced with hedging requests, incorporating thresholds for tripping, jittered backoff for retries, and success sampling for efficient health checks. This combo is gold for high-latency, failure-prone services (e.g., microservices, APIs). It prevents cascades while accelerating tail latencies.
I'll break it down step-by-step, then provide a high-level design and pseudocode (in Python-like pseudocode for clarity).
1. Core Concepts
Circuit Breaker: Monitors request outcomes (success/failure/latency). States: Closed (normal), Open (block/fail-fast), Half-Open (probe to recover).
Hedging: When a request exceeds a latency threshold, fire duplicate "hedge" requests. Cancel hedges on first success. Reduces p99 latency without always duplicating.
Here's a thread-safe class (use atomic counters, e.g., via concurrent.futures or Redis for distributed).
python
5. Half-Open Success Sampling
In _execute for Half-Open:
python
if state == 'HALF_OPEN' and random.random() > self.sample_rate:
raise Exception("Skip probe") # Only sample X% of requests
# Else: proceed, and on success: if successes_in_window > threshold, self.state = 'CLOSED'
Distributed: Use Redis/ETCD for shared state (e.g., via CircuitBreakerRegistry).
Libs: Resilience4j (Java), Polly (C#), pybreaker + tenacity (Python), or build on Istio/Envoy.
Testing: Chaos Monkey + latency injection.
Edge Cases: Timeouts on hedges, idempotency required, volume limits.
This design mirrors patterns from Netflix Hystrix/Atlas, AWS, or "Release It!" by Michael Nygard. Need code for a specific lang, tweaks, or diagrams? The game is afoot—fire away! 🕵️♂️
import time
import random
import threading
from collections import deque, defaultdict
from dataclasses import dataclass
@dataclass
class RequestResult:
success: bool
latency_ms: float
class HedgedCircuitBreaker:
def __init__(self, window_size=100, failure_threshold=0.5, ...): # All params above
self.states = {'CLOSED', 'OPEN', 'HALF_OPEN'} # Enum-like
self.state = 'CLOSED'
self.lock = threading.Lock()
self.window = deque(maxlen=window_size) # Sliding window of results
self.failure_count = 0
self.last_failure_time = 0
self.open_timeout = 30_000 # ms
def execute(self, fn, *args, max_retries=3, **kwargs):
for attempt in range(max_retries):
with self.lock:
state = self._get_state()
if state == 'OPEN':
if time.time() * 1000 - self.last_failure_time < self.open_timeout:
raise Exception("Circuit open")
self._to_half_open()
# Send primary request with hedging
hedge_tasks = []
start = time.time() * 1000
try:
future = self._send_request(fn, *args, **kwargs) # Async executor
if (time.time() * 1000 - start) > self.hedge_threshold:
# Hedge: duplicate requests
for _ in range(self.max_hedges):
hedge = self._send_request(fn, *args, **kwargs)
hedge_tasks.append(hedge)
# Wait for first success
result = future.result(timeout=self.timeout / 1000)
for h in hedge_tasks:
h.cancel() # Cancel hedges
latency = time.time() * 1000 - start
self._record_result(True, latency)
return result
except Exception as e:
latency = time.time() * 1000 - start
self._record_result(False, latency)
if self._should_trip():
self._trip_open()
# Jittered backoff
backoff = min(self.max_backoff, self.backoff_base * (2 ** attempt))
jitter = backoff * (random.random() - 0.5) # ±50%
time.sleep((backoff + jitter) / 1000)
def _record_result(self, success: bool, latency: float):
self.window.append(RequestResult(success, latency))
if not success:
self.failure_count += 1
def _should_trip(self):
if len(self.window) < 20: return False # Warmup
fail_rate = sum(1 for r in self.window if not r.success) / len(self.window)
consec_fails = sum(1 for r in list(self.window)[-5:] if not r.success) >= 5
high_latency = sum(1 for r in self.window if r.latency_ms > self.p95_threshold) / len(self.window) > 0.05
return fail_rate > self.failure_threshold or consec_fails or high_latency
def _trip_open(self):
self.state = 'OPEN'
self.last_failure_time = time.time() * 1000
def _get_state(self):
if self.state == 'OPEN' and (time.time() * 1000 - self.last_failure_time > self.open_timeout):
return 'HALF_OPEN'
return self.state
def _to_half_open(self):
self.state = 'HALF_OPEN'
def _send_request(self, fn, *args, **kwargs):
# Placeholder for executor (e.g., ThreadPoolExecutor)
pass # Implement with asyncio or concurrent.futures