Designing Circuit Breakers with Hedging
I'm preparing to respond to the user's question about a circuit breaker pattern with hedging. They likely want guidance on various aspects like thresholds, jittered backoff, and success sampling.
I'll include details on how to implement a circuit breaker per endpoint with states like closed, open, and half-open. I'll explain when to hedge duplicate requests, how to set thresholds like error rates or latency, and suggest using adaptive sampling.
Additionally, I’ll give parameters for implementing jittered exponential backoff and success sampling strategies.Explaining Circuit Breaker Mechanics
I'm delving into the user’s inquiry regarding the open criteria for the circuit breaker. I need to clarify that a breaker opens when the failure ratio exceeds a defined threshold or there are consecutive failures, or if latency hits the p99 mark.
For half-open probing, I’ll detail allowing a limited number of probes and sampling successes before closing.
Additionally, I’ll discuss employing jittered exponential backoff during open times, and how hedging works—starting a main request and sending backups if necessary, but only when conditions are right.Understanding Success Sampling
I'm considering how to implement success sampling for the circuit breaker. When in the open state, I can allow periodic test requests, or if closed, I might sample a subset to measure latency and error rates, which can help minimize costs.
The goal is to evaluate success outcomes during the half-open phase to determine whether the circuit breaker should transition back to a closed state. This approach should help in making quicker decisions about the system's health!Proposing the Circuit Breaker Algorithm
I'm outlining a potential algorithm for the circuit breaker. It will maintain a sliding window and track total requests, failures, and timeouts. The circuit will open if certain conditions are met, like a high failure rate or latency.
When it's open, I'll reject fast requests and use fallbacks if needed. After a certain time, it transitions to half-open, allowing limited probes. For success sampling, I think we should randomly sample a percentage of traffic to avoid bias. This way, we're ensuring efficient and effective monitoring of the system!Designing the Circuit Breaker with Hedging
I'm developing a logical request metric for handling hedged duplicates. When I get duplicates, I’ll treat them as a single attempt and focus on the first completion, canceling others without counting them as failures.
I'll also keep separate metrics for each upstream to monitor health. Hedging parameters should include setting delays based on latency and introducing jitter to avoid clustering. I’ll structure the response with sections on state machines, thresholds, and pseudocode.
Moreover, implementing success sampling will help reduce noise while ensuring healthy hosts don’t become overloaded.
Below is a practical way to combine a circuit breaker with hedged requests, including (1) thresholds, (2) jittered backoff, and (3) success sampling (probing) that won’t stampede a recovering dependency.
1) Track health on attempts, not on “logical requests”
With hedging, one user call may create 2+ upstream attempts. Keep two views:
- Per-attempt health metrics (used by the circuit breaker)
Each upstream target (host/zone/cluster) gets its own breaker based on outcomes of attempts sent to it.
- Per-logical-request metrics (used for product SLOs)
“Succeeded if any hedge succeeded before deadline.”
This avoids a common bug: hedging can “hide” an unhealthy replica if you only score the final logical outcome.
Important accounting rule: if you cancel a hedge because another attempt succeeded, record it as canceled (neither success nor failure) so you don’t punish the target for being canceled.
2) Circuit breaker thresholds (open criteria)
Use a rolling window (or EWMA) and require a minimum sample size.
Recommended signals (pick 1–2, not all):
- Error/timeout rate threshold
- Window: 10–60s rolling, or EWMA with half-life ~10–30s
- Open if:
requests_in_window >= minRequests AND
(failures + timeouts) / requests >= failureRateThreshold
Typical starting values:
minRequests = 20 (per-host) or higher if QPS is high
failureRateThreshold = 0.5 (50%) for “hard open”
- Consider a “soft open” at 20–30% to reduce concurrency (see below)
- Consecutive failures threshold (fast trip for sharp outages)
- Open if
consecutiveFailures >= N
- Typical
N = 5–10
- Latency-based trip (optional)
Useful if “slow = effectively down” for your SLA:
- Open if
p99_latency > latencyTripMs for the window and request volume is meaningful
Be careful: latency spikes can be load-related; opening may worsen load elsewhere.
Soft-open (optional but helpful)
Instead of only CLOSED/OPEN, add a “DEGRADED” mode:
- If failure rate is elevated but not catastrophic, shed load (lower concurrency / hedge less / route away) without fully opening.
3) OPEN state with jittered exponential backoff
When a breaker opens, you want fast fail plus a next probe time that spreads clients out.
Use exponential backoff with jitter:
backoff = min(cap, base * 2^k)
- Apply full jitter (good at avoiding herds):
sleep = random(0, backoff)
Typical values:
base = 200ms–1s
cap = 10s–60s
k increments each time the probe fails and the breaker re-opens
Store nextProbeAt = now + sleep.
4) Half-open with “success sampling” (probe gating)
When now >= nextProbeAt, move to HALF_OPEN but do not immediately allow full traffic. Instead, allow only a small, sampled set of probe attempts.
Two common probe admission strategies:
A) Fixed probe budget (simple, robust)
- Allow at most
probeMaxInFlight = 1–5 concurrent probes
- Over a period, require:
- close if
successes >= closeSuccessCount (e.g., 5–20)
- reopen if
failures >= 1 (strict) or if failure rate exceeds threshold
Typical:
probeMaxInFlight = 1 (conservative) or 3
closeSuccessCount = 10
reopenOnAnyFailure = true (common default)
B) Probabilistic success sampling (scales with traffic)
If traffic is high, you can sample a fraction of requests as probes:
- In HALF_OPEN, for each incoming call:
- with probability
pProbe, allow it through as a probe
- otherwise fail fast (or route to fallback/alternate)
Typical:
pProbe = 0.01–0.1 depending on QPS and desired probe rate
Close rule: once you’ve seen enough probe volume, close when success rate is healthy:
- if
probes >= minProbeRequests and probeSuccessRate >= successThreshold
Typical minProbeRequests = 20, successThreshold = 0.9–0.99.
5) Hedging integration (when and how to hedge)
Hedging reduces tail latency but can amplify load and can fight the breaker if uncontrolled.
5.1 When to send a hedge
A standard policy:
- Start primary attempt immediately.
- If it hasn’t completed by
hedgeDelay, start one hedge attempt (max 1–2 hedges total).
Set hedgeDelay from observed latency, e.g.:
hedgeDelay = p95_latency(primaryTarget) (or p90) over the last 1–5 minutes
- Add jitter to avoid synchronized hedges:
hedgeDelay *= random(0.8, 1.2)
5.2 Where to send the hedge
Prefer another replica/zone/host that has a CLOSED (or healthiest) breaker.
- If all alternatives are OPEN, don’t hedge—fail fast or use fallback.
5.3 Hedge budget (critical)
Limit hedging so it doesn’t become a self-inflicted DDoS.
Use a token bucket or ratio cap:
maxHedgeRatio = 0.02–0.10 (2–10% extra attempts)
- Only hedge if:
hedgeTokensAvailable and
- primary breaker is not OPEN and
- global load isn’t already high (optional)
5.4 How results feed the breaker
- Each attempt reports to its target’s breaker as:
success if it returned a valid response
failure if it errored/timed out
canceled if you canceled it after another attempt succeeded
- The logical request completes on first success (or final failure when all attempts fail / deadline hit).
6) Putting it together (state machine sketch)
Breaker states: CLOSED -> OPEN -> HALF_OPEN -> CLOSED (or OPEN again)
Open conditions (CLOSED → OPEN):
(failRate >= threshold && reqs >= minRequests) OR consecutiveFailures >= N
OPEN behavior:
- fail fast (or fallback)
- when
now >= nextProbeAt → HALF_OPEN
HALF_OPEN behavior:
- admit only sampled/budgeted probes
- if enough probe successes → CLOSED
- on probe failure → OPEN with backoff++
Hedging behavior (per request):
- only if hedge budget allows
- only to targets whose breakers allow attempts
- delay based on p90/p95 + jitter
7) Reasonable starter parameters
These are conservative defaults that work in many RPC/HTTP environments:
Breaker
- Window: 30s rolling (or EWMA half-life 20s)
minRequests = 50 (per target)
failureRateThreshold = 0.5
consecutiveFailures = 5
- Backoff:
base=500ms, cap=30s, full jitter
- HALF_OPEN:
probeMaxInFlight=1
closeSuccessCount=10
- reopen on any probe failure
Hedging
maxHedges = 1
hedgeDelay = p95_latency(last 5m) * jitter(0.8–1.2)
maxHedgeRatio = 0.05 (5%)
If you share your context (RPC vs HTTP, typical QPS per host, latency SLO, and whether you have multiple replicas/zones), I can suggest concrete threshold numbers and a clean pseudocode implementation (including the metric math and thread-safe counters).