Circuit breaker
A circuit breaker wrapping every call to a flaky payment provider. It must stop hammering a dependency that is already down, probe carefully for recovery, and be shared safely by every request thread in the process.
The breaker has opened. What is the half-open state for?
- Queueing requests until the dependency returns
- Letting a limited number of probes through to test recovery
- Shortening the timeout on each call
- Failing fast with a cached response
Something has to test whether the dependency is healthy again, and the only real test is a live call. Half-open admits a small number of probes: success closes the breaker, failure opens it for another interval. Without it the breaker either stays open forever or reopens the floodgates all at once.
Assign each responsibility.
- Decide whether this call is allowed through right now
- CircuitBreaker
- Hold the count of recent successes and failures
- FailureWindow
- Own the transition between closed, open and half-open
- CircuitBreaker
- Define the failure threshold and how long the breaker stays open
- BreakerPolicy
- Supply the current time, so tests do not have to sleep
- Clock
The state machine is one object so every transition lives in one readable place — Tier 2 State pattern, applied to reliability. Thresholds are a policy object because a payment provider and a search index want completely different ones. And injecting the clock is what turns "after thirty seconds it goes half-open" into a test that runs in a millisecond instead of one nobody runs.
The breaker is half-open when 200 concurrent requests arrive. How many should reach the dependency?
- All 200 — the breaker is not open
- A small bounded number; the rest fail fast
- Half of them
- One per thread
A dependency that has just come back is at its most fragile, and 200 simultaneous requests is precisely what knocks it over again. Half-open must admit a bounded number of probes and reject the rest immediately — which means the probe count is shared mutable state and needs an atomic counter, not a plain field.
Which outcome should NOT count towards opening the breaker?
- A connection timeout
- A 500 from the provider
- A 400 rejecting a malformed request
- A read timeout after the request was sent
A 400 means your request was wrong and will be wrong every time — the dependency is healthy and answering correctly. Counting it opens the breaker for every other caller because one code path sends bad input. The breaker measures the dependency, not your bugs: only failures a retry could plausibly fix belong in the window.