A circuit breaker is the piece of resilience plumbing that stops a failing dependency from taking down everything that calls it. The idea is borrowed straight from electrical engineering: when a downstream service starts failing, you trip the breaker and stop sending it traffic for a while, failing fast locally instead of piling up threads and timeouts waiting on something that is already dead. After a cooldown you send a cautious probe or two; if they succeed you close the breaker and resume normal traffic, if they fail you stay open and wait again. This is the single most effective defense against cascading failure in a microservice architecture, and every serious resilience library - Hystrix, resilience4j, Polly, Envoy’s outlier detection - implements some version of it.
The classic implementation is purely local: each process keeps its own rolling window of success/failure counts per dependency and trips its own breaker independently. That works, and for many systems it is the right answer. But it has a structural weakness that shows up exactly when you have a large fleet. Each of your 500 instances learns that payments is down only from its own traffic, so each one has to independently accumulate enough failures to trip. During the learning window, 500 instances are all still hammering a dying dependency. And when the breaker opens, every one of those 500 instances independently decides to send a recovery probe the moment its cooldown elapses - so the recovering service, which just came back with cold caches and a single warm replica, gets slammed by 500 simultaneous probes and falls over again. That is a thundering herd, and a purely local breaker causes it by construction.
So the design problem here is not “build a circuit breaker” - that state machine is textbook. It is: share failure signal across the whole fleet so instances trip together on aggregated evidence, and coordinate the recovery so that exactly one instance probes at a time, while tolerating network partitions without latching the entire fleet open forever. That coordination, done without a central lock on the request hot path, is the entire game. Let me do this the way I would in an interview: requirements, sizing, architecture, then take the genuinely hard parts - fleet-wide failure aggregation, single-prober recovery coordination, and partition tolerance - from the naive version, break them, and evolve.
Functional Requirements (FR)
In scope:
- Per-dependency circuit breaking. Track health per (caller service, downstream dependency, optionally endpoint/route) and maintain a breaker state machine - CLOSED, OPEN, HALF_OPEN - for each. Decisions must be queryable on the request hot path in microseconds, locally, with no network call per request.
- Fleet-wide failure aggregation. Combine success/failure observations from all instances of a caller service into a shared view of each dependency’s health, so the breaker trips on aggregated evidence rather than each instance learning in isolation. A dependency failing for the fleet should trip the breaker fleet-wide fast, not instance-by-instance.
- Coordinated recovery (single prober). When a breaker is OPEN and the cooldown elapses, exactly one instance in the fleet transitions to HALF_OPEN and sends a small, bounded number of recovery probes. The outcome (probe succeeded -> CLOSED, probe failed -> back to OPEN) is propagated to the whole fleet so the others do not independently probe. No thundering herd of probes at a recovering service.
- Fast convergence. A state change (trip, or recover) must propagate to all instances within roughly one probe interval, so the fleet acts as one breaker rather than hundreds of slightly-out-of-sync breakers.
- Configurable policy. Per-dependency thresholds: failure-rate trigger (e.g. >50% errors over a rolling window with a minimum request volume), rolling-window size, open-state cooldown, number of half-open probes, and what counts as a “failure” (5xx, timeout, connection refused, but usually not a 4xx caller error).
- Graceful degradation / fallback hook. When a breaker is OPEN, the call fails fast and the caller runs its configured fallback (cached value, default, queued retry, degraded response). The breaker service decides whether to allow the call; the fallback is the application’s.
Explicitly out of scope (state this to bound the problem):
- Being the proxy / making the downstream call. We are the decision and coordination layer. The actual RPC, retries, timeouts, and fallbacks live in the client library or sidecar. We tell it “allow” or “reject,” we do not carry the traffic.
- General service discovery and load balancing. We assume the caller already knows its dependencies and their endpoints. Picking which replica to call is the load balancer’s job; we only track aggregate health.
- Rate limiting / quota. A breaker protects against failure, not against overload-by-success. Throttling healthy-but-saturated dependencies is a separate concern (though outlier ejection overlaps).
- Per-request distributed tracing. We emit metrics and state, not spans. Tracing is a consumer of our signal, not part of it.
The single decision that drives everything: the breaker decision must be local and lock-free on the hot path, while the breaker state is a shared, eventually-consistent, fleet-wide value maintained out of band. Put a network round-trip or a central lock on every request and you have added the exact fragility (shared synchronous dependency, latency, SPOF) that circuit breakers exist to prevent. Every hard part below is about reconciling “decide locally in nanoseconds” with “agree globally in under a probe interval.”
Non-Functional Requirements (NFR)
- Hot-path decision latency: effectively zero. The allow/reject check happens on every outbound call. It must be an in-memory read of local state - sub-microsecond, no syscall, no network. If checking the breaker can itself be slow or fail, the breaker is worse than useless.
- State convergence latency: under one probe interval. A trip or a recovery must reach the whole fleet within ~1-3 seconds (configurable, tied to the probe interval). The fleet should behave as one breaker; the window where instances disagree must be smaller than the cooldown so they do not fight each other.
- Availability: the breaker service must never be a hard dependency. If the coordination layer (gossip, or a backing store) is unreachable, each instance must fail safe to local-only circuit breaking and keep serving. The breaker degrades to the classic per-instance behavior, never to “cannot make any calls.” This decoupling is a core property, not a nicety.
- Scale: ~1,000 instances per caller service, ~50 downstream dependencies each, so ~50,000 breaker states to track per service; thousands of services in the org. Request volume through the hot-path check: millions of RPS per large service (every outbound call checks a breaker).
- Consistency: eventual, bounded. Breaker state is eventually consistent across instances - brief disagreement is acceptable and expected. What must be strongly coordinated is narrower: the “I am the one prober” decision during HALF_OPEN, where two probers is a tolerable degradation but a hundred is the thundering herd we are preventing.
- Partition tolerance: no fleet-wide latch-open. Under a network partition that splits the gossip mesh, each partition must continue making sane local decisions and must eventually re-converge. The failure mode to design out: a partition causing the breaker to stay OPEN forever even after the dependency recovers, because no one is coordinating probes across the split.
- Durability: low. Breaker state is ephemeral and self-healing - it is recomputed continuously from live traffic. A node restarting with an empty breaker table simply relearns within one window. We persist configuration, not runtime state.
Back-of-the-Envelope Estimation (BoE)
Let me ground the numbers, because they push the design toward gossip-based aggregation rather than a central store on the hot path.
Fleet and breaker-state size:
Caller instances per large service ~1,000
Dependencies per service ~50
Breaker states to track (per service) 1,000 instances x 50 deps = 50,000 views
but the SHARED state is per-dependency, so:
Distinct shared breaker states ~50 (one per dependency, fleet-aggregated)
Per-breaker state size ~200 bytes (counts, window, state enum, epoch)
Total shared state per service 50 x 200 B = 10 KB -> trivially fits in RAM
The shared state is tiny. There are only ~50 dependencies, so only ~50 fleet-wide breaker values to agree on per caller service. This is a crucial realization: we are not aggregating 50,000 things, we are aggregating 1,000 instances’ observations into ~50 values. The data is small; the hard part is the coordination, not the volume.
Hot-path check load (why it must be local):
Outbound RPS per large instance ~5,000 calls/sec
Breaker checks 1 per outbound call = 5,000 checks/sec/instance
Fleet-wide checks 1,000 x 5,000 = 5,000,000 checks/sec
If each check were a network call to a central store:
5M RPS of pure "can I make this call" traffic -> a bigger, more fragile
system than the one we are protecting. Impossible. MUST be a local RAM read.
Five million breaker checks per second across the fleet is the number that kills any “ask a central service per request” design before it starts. The check is a local read of an in-memory enum. Full stop.
Observation / aggregation load (the real coordination traffic):
Each call produces a success/failure observation.
Aggregating every single observation fleet-wide = 5M observations/sec of gossip
-> way too much. Must aggregate LOCALLY first, then share SUMMARIES.
Local rollup: each instance keeps per-dep rolling counters, updated per call
(in-process, free).
Gossip payload: each instance periodically (every ~1s) shares a compact
per-dependency summary: {dep, successes, failures, window, state, epoch}
~50 deps x ~40 bytes = ~2 KB per instance per gossip round.
So the trick is a two-level aggregation: per-call counting is purely local and free; only compact per-dependency summaries are gossiped, once per interval, not per call. That turns 5M observations/sec into ~1,000 instances each emitting a 2 KB summary every second.
Gossip bandwidth:
Gossip round interval ~1 s
Fanout per round each node gossips to ~3-5 random peers
Payload per message ~2 KB (50 dep summaries)
Per-node gossip egress ~5 peers x 2 KB = 10 KB/s (negligible)
Convergence time (epidemic) O(log N) rounds. For N=1,000, log2(1000)=~10
at ~1 round/sec with fanout 5 -> full fleet
convergence in ~2-4 seconds. Tunable by
raising fanout/round frequency to hit the
"< one probe interval" target.
Epidemic gossip converges in a logarithmic number of rounds, so a 1,000-node fleet reaches everyone in a few rounds. With a 1-second round and fanout 5 we are comfortably inside a 3-5 second probe interval. If we need faster, we raise fanout or shorten the round; the knobs are explicit.
Recovery probe math (the thundering-herd we are preventing):
Naive (local breakers): all 1,000 instances open at ~same time, all probe when
cooldown elapses -> up to 1,000 simultaneous probes at a
service that just came back with 1 warm replica -> re-death.
Coordinated: exactly 1 prober sends ~3 probes. The recovering service
sees ~3 requests, not ~3,000. 300x reduction in probe load.
The whole point in one number: coordinated recovery turns up to ~1,000 simultaneous probes into ~3. That 300x reduction is the difference between a clean recovery and a re-death loop where the dependency comes up, gets stampeded, falls over, and the fleet re-opens - forever.
The key insight from the numbers: the state is tiny and the hot-path check must be a local RAM read, so the entire design is about cheaply agreeing on ~50 small values across ~1,000 nodes within a few seconds, and electing one prober - not about moving data volume. That points squarely at local decisioning + gossip aggregation + a lightweight election, not a central database on the request path.
High-Level Design (HLD)
The architecture is a library/sidecar that lives in every caller instance, plus a gossip layer that shares compact health summaries across the fleet, plus an optional control/config plane for policy and observability. There is deliberately no synchronous central component on the request path.
Three logical layers:
- Local breaker engine (in every instance, on the hot path). Holds the per-dependency rolling counters and the current breaker state (CLOSED/OPEN/HALF_OPEN). Answers
allow(dep)?in a local memory read. Records every call’s outcome into a local sliding window. This is what the application calls on every outbound request. - Fleet aggregation layer (gossip, off the hot path). Periodically summarizes each dependency’s local counts and gossips them to a few random peers. Merges incoming summaries into a fleet-wide view per dependency. Runs the state-transition logic (trip when aggregated failure rate crosses threshold; coordinate recovery). This is the distributed brain.
- Control plane (off path, slow-moving). Stores breaker configuration (thresholds, windows, cooldowns per dependency), serves a dashboard of current breaker states across the fleet, and lets operators force-open or force-close a breaker (a kill switch / manual override). Not on the request path; a config store plus a read model.
Operator config / kill switch Dashboards / alerting
(thresholds, cooldowns, force-open) (fleet breaker states)
│ ▲
▼ │ (read model)
┌──────────────────────── CONTROL PLANE (off path) ─────────────────┐
│ config store (per-dep policy) + state read-model (observ.) │
└───────────────┬───────────────────────────────┬──────────────────┘
push policy │ │ scrape/report state
▼ │
┌─ CALLER SERVICE FLEET (N ~ 1,000 instances) ───────────────────────────────┐
│ │
│ ┌─ instance i ──────────────────────────────┐ ┌─ instance j ────────┐ │
│ │ app code │ │ app code │ │
│ │ │ allow(payments)? ── LOCAL RAM read ──┤ │ │ allow(...)? │ │
│ │ ▼ (hot path, sub-microsecond) │ │ ▼ │ │
│ │ ┌────────────────────┐ │ │ ┌───────────────┐ │ │
│ │ │ Local breaker engine│ per-dep windows, │ │ │ breaker engine│ │ │
│ │ │ state: CLOSED/OPEN/│ counts, state │ │ └──────┬────────┘ │ │
│ │ │ HALF_OPEN + epoch │ │ │ │ │ │
│ │ └─────────┬──────────┘ │ │ │ │ │
│ │ │ summarize per ~1s │ │ │ │ │
│ │ ▼ │ │ ▼ │ │
│ │ ┌────────────────────┐ GOSSIP (random │ │ ┌───────────────┐ │ │
│ │ │ Gossip agent │◄──peer exchange,───┼───┼─►│ Gossip agent │ │ │
│ │ │ merge fleet view │ fanout ~5/round) │ │ │ │ │ │
│ │ └────────────────────┘ │ │ └───────────────┘ │ │
│ └────────────────────────────────────────────┘ └────────────────────┘ │
│ ▲ ▲ │
│ └───┴── every instance gossips with ~5 random peers per second │
│ -> epidemic convergence of the ~50 per-dep summaries │
└────────────────────────────────┬───────────────────────────────────────────┘
│ actual RPCs (allowed calls only)
▼
┌────────────────────────┐
│ downstream dependency │ (e.g. "payments")
│ (the thing we protect │
│ both the caller AND │
│ the dependency from) │
└────────────────────────┘
Hot-path request flow (every outbound call, local only):
- App is about to call
payments. It asks the local breaker engineallow("payments")?. - The engine reads the local state enum. If CLOSED -> allow. If OPEN -> reject immediately (fail fast), app runs its fallback. If HALF_OPEN -> allow only if this instance is the elected prober and the probe budget is not exhausted; otherwise reject.
- If allowed, the app makes the real RPC. On completion it reports the outcome back:
record("payments", success|failure|timeout). - The engine updates its local rolling window counters for
payments. No network involved in any of this. This is the entire hot path.
Aggregation flow (background, ~1s cadence):
- Once per gossip round, the gossip agent snapshots each dependency’s local counters into a compact summary
{dep, successes, failures, windowStart, localState, epoch}. - It merges its view with summaries received from peers (sum the counts across instances for the current window, take the max epoch per dependency to resolve state).
- It picks ~5 random peers and sends them its merged per-dependency summaries. It also receives theirs. Epidemic spread means every instance’s observations reach the whole fleet in O(log N) rounds.
- After merging, the engine recomputes the aggregated failure rate per dependency. If it crosses the trip threshold (and minimum volume), it transitions the dependency to OPEN and bumps the epoch - which then spreads via gossip, tripping the whole fleet.
Recovery flow (coordinated, single prober):
- A dependency is OPEN. Each instance, from the gossiped state, knows the OPEN epoch and the timestamp it started. When
now >= openedAt + cooldown, the fleet is eligible to probe. - A deterministic election picks exactly one prober for this OPEN epoch (details in the deep dive - a hash of epoch against the live member list). Only the elected instance moves its local state to HALF_OPEN and allows a bounded number of probe calls; everyone else stays OPEN.
- The prober sends ~3 probes. If they succeed, it transitions to CLOSED, bumps the epoch, and gossips the new CLOSED state - the fleet converges to CLOSED and resumes traffic. If they fail, it transitions back to OPEN with a fresh
openedAt(extending cooldown, optionally with exponential backoff), bumps the epoch, and gossips - the fleet stays open and waits. - If the elected prober dies mid-probe, the next cooldown window elects a different instance (the member list changed, or a timeout re-triggers election), so a dead prober does not latch the fleet open.
Component Deep Dive
Three hard parts, each taken naive-first: (1) fleet-wide failure-rate aggregation without flooding the network; (2) single-prober recovery coordination without a central lock; (3) partition tolerance so a split brain never latches the fleet OPEN forever. I break each before fixing it. The hot-path state machine itself I treat as known and keep brief.
The breaker state machine (the known part, stated once)
failure-rate >= threshold (and min volume)
┌────────┐ ─────────────────────────────────────────► ┌────────┐
│ CLOSED │ │ OPEN │
│ allow │ ◄───────────────────────────────────────── │ reject │
└────────┘ probe success (prober only) └───┬────┘
▲ │ cooldown elapsed
│ probe success │ + elected prober
│ ▼
│ ┌──────────────┐
└──────────────────────────────────────────── │ HALF_OPEN │
│ prober sends │
probe failure -> back to OPEN │ ~3 probes │
(fresh cooldown, backoff) └──────────────┘
CLOSED: allow traffic, count outcomes. OPEN: reject fast, run fallback, wait out cooldown. HALF_OPEN: exactly one instance tests the waters with a few probes. The distributed version’s novelty is entirely in how the fleet agrees on which state each dependency is in and who probes - not in the three boxes.
1. Fleet-wide failure-rate aggregation
The goal: trip on the fleet’s combined evidence, fast, without turning 5M observations/sec into gossip traffic.
Naive A: each instance breaks purely locally (no sharing)
The classic Hystrix model. Each instance keeps its own rolling window and trips independently.
Where it breaks:
- Slow, uneven tripping. A low-traffic instance that sends
payments2 calls/sec takes a long time to accumulate enough failures to cross the minimum-volume threshold, so it keeps calling a dead dependency long after high-traffic instances have tripped. The fleet trips raggedly over many seconds, and the stragglers keep loading the failing dependency. - No shared recovery signal. Each instance opens and later probes on its own schedule. This is exactly what produces the recovery thundering herd (addressed in part 2) - there is no shared notion of “the dependency is OPEN for the fleet.”
- Per-instance noise. One instance that happens to hit a single bad replica trips its breaker on a local anomaly that is not fleet-wide. Aggregated evidence would have smoothed that out.
Local-only is simple and robust (no coordination to fail), which is why it is the correct fallback mode. But as the primary mode at fleet scale it “works” only in the sense that it is slow and herd-prone.
Naive B: every observation goes to a central store that computes the rate
Each instance POSTs every success/failure to a central aggregator (or writes to Redis), which maintains the fleet-wide rate and which everyone reads.
Where it breaks:
- 5M writes/sec of observation traffic (from the BoE) to a central store, plus everyone reading the computed state. You have built a bigger, hotter, more failure-prone system than the one you are protecting, and put it synchronously adjacent to the hot path.
- It is a SPOF and a shared synchronous dependency - the precise anti-pattern circuit breakers exist to eliminate. If the aggregator is slow or down, either every call blocks (catastrophe) or you fail open and you are back to local-only anyway.
- Hot key. A single popular dependency’s counter is one hot key hammered by the whole fleet; it will not shard cleanly because the aggregate is inherently a single value per dependency.
The root cause of both naive versions: A shares nothing (slow, herd-prone); B shares everything through a central point (SPOF, hot key, hot-path coupling). We want the sharing of B with the decentralization and hot-path-freedom of A.
Better: two-level aggregation - local counting, gossiped summaries, merged fleet view
- Level 1, local counting (per call, free). Each instance maintains, per dependency, a rolling-window counter structure - a ring of time buckets (e.g. 10 buckets of 1s = a 10s window) holding success and failure counts. Updated in-process on every
record(). No network. This is the same structure a local-only breaker uses. - Level 2, gossiped summaries (per round, cheap). Once per gossip round (~1s), each instance emits one compact summary per dependency:
{dep, successes, failures, windowId, localState, epoch, instanceId}. ~40 bytes x ~50 deps = ~2 KB. This is a summary of a window, not a stream of events - orders of magnitude less than per-observation sharing. - Merge into a fleet view. Each instance keeps, per dependency, a map of
instanceId -> latest summary(with a TTL so dead instances age out). The fleet-wide rate for a dependency is the sum of failures over the sum of (successes+failures) across all live instances’ current-window summaries. Because gossip is epidemic, every instance’s summary reaches everyone in O(log N) rounds, so all instances compute nearly the same aggregate within a few seconds. - Trip on the aggregate. When the merged failure rate crosses the threshold with sufficient merged volume, the instance transitions that dependency to OPEN locally and bumps its epoch. That OPEN+epoch spreads by gossip (state is part of each summary), and within a couple of rounds the whole fleet is OPEN. One instance noticing is enough to trip the fleet, because the notice propagates.
Level 1 (local, per call): Level 2 (gossip, per ~1s round):
record(payments, fail) summary = {payments, s=120, f=380,
-> bucket[now].fail++ win=4412, state=CLOSED, epoch=7}
(ring of 10 x 1s buckets) send to 5 random peers; receive theirs
allow(payments)? merge: fleetView[payments] =
-> read local state enum sum over live instances of (s, f)
(sub-microsecond, no network) rate = f/(s+f) = e.g. 0.76 > 0.5 threshold
-> transition payments to OPEN, epoch=8
(spreads via next gossip rounds)
Why this wins: per-call work stays local and free; only tiny per-dependency summaries cross the network, once per round; and epidemic gossip gives fleet-wide aggregation with no central point. The fleet trips together on combined evidence within a few seconds, and there is no SPOF, no hot key, nothing synchronous on the request path. The CRDT-ish merge (sum current-window counts, max epoch for state) is associative and commutative, so merge order does not matter and the view converges.
One subtlety: windowing across instances. Counts are summed only within the same logical window (aligned by windowId, a floor of wall-clock time to the bucket size). This needs loosely synchronized clocks (NTP, within tens of ms - easy) so that “the last 10 seconds” means the same interval everywhere. Summaries from a stale window are discarded on merge. This keeps the aggregate from mixing old and new evidence.
2. Single-prober recovery coordination (the thundering-herd fix)
This is the crux of the assignment: when OPEN cooldown elapses, exactly one instance probes, and the result spreads so the others do not.
Naive: every instance probes when its own cooldown elapses
The local-only behavior. Each instance, on opening, starts a cooldown timer; when it fires, it goes HALF_OPEN and sends a probe.
Where it breaks:
- Thundering herd by construction. Because the fleet tripped at roughly the same time (especially with gossip aggregation making them trip together), all ~1,000 cooldown timers fire within a narrow window, and all ~1,000 instances probe simultaneously. The recovering dependency - one warm replica, cold caches - gets ~1,000 requests at once, falls over, every probe fails, every instance re-opens, and the loop repeats forever. The dependency can never recover because every recovery attempt is a stampede. This is the exact failure the assignment names.
- Wasted load even on success. Even if the dependency survives, you sent 1,000 probes to learn one bit (“is it up?”). 999 were pure waste.
Naive: a distributed lock - whoever grabs the lock probes
Put a lock in a central store (Redis SETNX, etcd, ZooKeeper). An instance, on cooldown elapse, tries to acquire probe-lock:payments; whoever wins probes.
Where it breaks:
- Reintroduces a central synchronous dependency on the recovery path - the same SPOF/anti-pattern we rejected for aggregation. If the lock store is partitioned from the fleet, no one can acquire the lock, and the breaker latches OPEN forever - precisely the partition failure mode the assignment says to avoid.
- Lock liveness is hard. If the lock holder dies mid-probe, you need a lease/TTL and fencing to avoid a dead holder blocking recovery or two holders probing. Workable, but it is a lot of distributed-locking machinery bolted onto a system whose whole premise is “no central dependency on the path.”
Better: deterministic election over the gossiped membership, per OPEN epoch
Use the state the gossip layer already maintains - the live member list and the current OPEN epoch - to let every instance independently compute the same answer to “who probes?” with no coordination round at all.
- Deterministic prober selection. When a dependency is OPEN at epoch
E, every instance computesprober = members[ hash(dep, E) mod len(members) ], wheremembersis the sorted list of live instance IDs from the gossip membership view. Because every instance has (approximately) the same membership view and the same(dep, E), they all independently pick the same prober. Only the instance whose own ID equalsprobertransitions to HALF_OPEN when the cooldown elapses; everyone else stays OPEN and keeps rejecting. No lock, no election round - just a shared function over shared state. - Bounded probe budget. The elected prober sends a small fixed number of probes (e.g. 3). On success it goes CLOSED, bumps epoch to
E+1, and gossips CLOSED. On failure it goes back to OPEN, sets a freshopenedAtwith exponential backoff on the cooldown, bumps epoch toE+1, and gossips OPEN. Either way the epoch advances, which (a) propagates the outcome and (b) re-randomizes the next prober - so a repeatedly-failing dependency rotates the prober each round rather than punishing one instance. - Dead-prober safety via re-election on epoch timeout. If the elected prober crashes before producing a result, its summaries stop arriving and it ages out of the membership view (TTL). Independently, every instance runs a probe-deadline timer: if an OPEN epoch’s cooldown elapsed and no CLOSED/re-OPEN for that epoch has been observed within a grace period (say 2x the expected probe time), the epoch is considered stalled, instances bump to a new epoch, and the deterministic function selects a new prober (the member list no longer contains the dead one, or the epoch change reshuffles). So a prober dying delays recovery by one grace period, it never latches the fleet open.
- Convergence keeps the herd at ~1. Because the OPEN state and epoch propagate before cooldowns elapse (convergence < probe interval, from the NFR), non-prober instances already know “we are OPEN at epoch E and I am not the prober” by the time their own timers would fire. They never probe. The recovering dependency sees ~3 requests, not ~3,000.
Dependency "payments" OPEN at epoch E, cooldown elapsing across the fleet:
Every instance computes independently:
prober = members[ hash("payments", E) mod N ] # same answer everywhere
│
┌───────────────────────────┼───────────────────────────┐
▼ ▼ ▼
instance-417 instance-02 instance-993
id == prober? NO id == prober? YES id == prober? NO
stay OPEN, reject -> HALF_OPEN stay OPEN, reject
send 3 probes to payments
│
┌──────────────┴───────────────┐
probes succeed probes fail
state=CLOSED, epoch=E+1 state=OPEN, openedAt=now,
gossip CLOSED cooldown*=backoff, epoch=E+1
│ gossip OPEN (new prober next round)
▼
fleet converges CLOSED in ~2-3 gossip rounds, traffic resumes
If instance-02 dies mid-probe:
no CLOSED/re-OPEN for epoch E within grace period
-> instances bump to E+1, recompute prober over the (now smaller) member list
-> a NEW prober is selected. Fleet never latches OPEN on a dead prober.
Why this wins: the gossip layer already gives us a shared membership list and a shared epoch, so prober election is a pure function of state everyone already has - no lock, no central store, no coordination message. The epoch is both the propagation vehicle for the outcome and the randomizer for prober rotation and dead-prober recovery. Two instances might briefly disagree on membership and both probe (a harmless degradation - 2 probes, not 1,000), but the system can never produce a herd or latch open.
3. Partition tolerance - never latch the fleet OPEN forever
Gossip meshes partition. The design must keep making sane decisions on both sides of a split and re-converge cleanly, and above all must not stay OPEN after the dependency has recovered.
Naive: treat the gossip view as ground truth and require fleet-wide agreement to close
If closing a breaker required a quorum or fleet-wide consensus, then a partition (where no side has a majority view, or the prober is on the other side) means no one can legitimately close the breaker, and it stays OPEN until the partition heals - even though the dependency is perfectly healthy. The assignment calls this out explicitly as the thing to avoid.
Where it breaks:
- Latched-open under partition. The dependency recovers, but the coordination layer is split, so the “close” decision cannot be made, and every instance keeps failing fast against a healthy dependency. The breaker has become the outage.
- Over-trusting a partial view. An instance in a small partition sees only a few peers’ summaries and might compute a wildly wrong aggregate (too little volume, or a skewed sample) yet act on it as if it were the fleet’s view.
Better: local authority as the floor, gossip as an accelerant, epoch-ordered convergence
The governing principle: gossip makes the breaker trip faster and recover more cheaply, but every instance retains the authority and the responsibility to decide locally. The shared state is an optimization layered over a self-sufficient local breaker, never a prerequisite for action.
- Local decisioning never blocks on gossip. Each instance always has its own local rolling window from its own traffic. If gossip goes silent (partition, or the whole gossip layer failing), the instance falls back to local-only circuit breaking: it trips and recovers on its own evidence, exactly like classic Hystrix. It keeps serving. The fleet degrades gracefully to N independent breakers - slower and herd-prone, but correct and live. This is the fail-safe mandated by the NFR.
- Partition-local probing prevents latch-open. Because prober election is computed over the membership view each instance currently has, each partition independently elects a prober from its own members and probes on its own cooldown. So the dependency recovering is detected within each partition independently - neither side needs the other to close the breaker. A partition can recover its own breaker. There is no global “close” that a split can block. This is the direct answer to “tolerate partitions without latching OPEN.”
- Epoch-ordered merge on heal. When the partition heals and summaries flow again, the two sides may hold different states for a dependency. Resolution is deterministic: the highest epoch wins, because epoch is bumped on every real transition and encodes recency of decision. If one side closed the breaker (higher epoch, CLOSED) and the other is still OPEN at a lower epoch, the CLOSED state propagates and the fleet converges to CLOSED - the correct outcome, since someone verified recovery with a real probe. Ties (same epoch, divergent state - rare) break toward the safer state (OPEN) and force a fresh probe, so we never wrongly close on a tie.
- Bounded staleness via summary TTL. Summaries carry a timestamp; a summary older than a few rounds is ignored and its instance ages out of the fleet view. So after a partition, stale counts from the other side do not pollute the aggregate - only fresh, post-heal evidence is merged. This stops a healed partition from re-tripping on ancient data.
- Split-brain probe cost is bounded and acceptable. Under a partition, each side elects its own prober, so the dependency may see one probe per partition instead of one globally - typically 2-3 probes total, not thousands. We accept “one prober per partition” as a bounded, safe degradation; it is the price of never latching open, and it is nowhere near a herd.
Partition splits the gossip mesh; "payments" has actually recovered:
Partition A (600 instances) Partition B (400 instances)
sees members = A-set sees members = B-set
elects prober_A = hash(dep,E) % 600 elects prober_B = hash(dep,E) % 400
prober_A probes -> success prober_B probes -> success
state=CLOSED, epoch=E+1 (within A) state=CLOSED, epoch=E+1 (within B)
-> traffic resumes in A -> traffic resumes in B
Neither side waited for the other. Dependency saw ~2 probes total, not thousands.
NO latch-open: each partition recovered its own breaker.
Partition heals:
summaries flow; both sides CLOSED -> trivially converge.
(If one side were still OPEN at lower epoch, the higher-epoch CLOSED wins.)
Why this wins: by making local authority the floor and gossip a best-effort accelerant, no partition can ever prevent an instance (or a partition) from deciding and acting. Prober election over the local membership view means recovery is detected per-partition, so the dependency recovering always un-trips the breaker somewhere, and epoch-ordered merge carries that “it is healthy” signal across the heal. The system trades a little extra probe traffic under partition (one prober per side) for the guarantee that it never latches the fleet OPEN against a healthy dependency - which is exactly the trade the assignment asks for.
API Design & Data Schema
Two very different surfaces: the in-process library API (hot path, what app code calls) and the control-plane API (off path, config and observability). There is deliberately no synchronous network API on the request path.
Library / hot-path API (in-process, per call)
# ---- the two calls every outbound request makes (local, no network) ----
allow(dependency: string, route?: string) -> Decision
# returns ALLOW | REJECT (and if REJECT, the state so the app can log/fallback)
# ALLOW: breaker CLOSED, or HALF_OPEN and this instance is the elected prober
# with probe budget remaining.
# REJECT: breaker OPEN, or HALF_OPEN but not the prober. App runs its fallback.
# Pure local read of the breaker state enum. Sub-microsecond. Cannot block or fail.
record(dependency: string, outcome: SUCCESS | FAILURE | TIMEOUT, route?: string)
# called after the RPC completes. Updates the local rolling-window buckets.
# FAILURE/TIMEOUT count as failures; a downstream 4xx (caller error) does NOT.
# Also local-only. The gossip layer picks these counts up asynchronously.
# ---- optional: wrap() convenience that does allow/record around a call ----
wrap(dependency, fn) -> result | throws OpenCircuitError
# if allow() rejects -> throw OpenCircuitError immediately (caller catches ->fallback)
# else run fn(), record() the outcome, return/rethrow.
Gossip wire message (instance to instance, off path)
GossipMessage (UDP/TCP to ~5 random peers per ~1s round):
{
sender_id: "inst-02a7",
sent_at_ms: 1764300000123,
members: [ {id, last_seen_ms}, ... ], # membership (for the view + TTL)
summaries: [
{ dep: "payments",
window_id: 4412, # floor(now / bucket_size); aligns counts
successes: 120,
failures: 380,
state: OPEN, # CLOSED | OPEN | HALF_OPEN
epoch: 8, # bumped on every transition; max wins on merge
opened_at_ms:1764299995000 # for cooldown math on OPEN
},
... (~50 deps)
]
}
# Merge rule: per dep, sum (successes, failures) over live senders in the SAME
# window_id; for state take the summary with the MAX epoch (ties -> safer=OPEN).
Control-plane API (operator + dashboards, off path)
PUT /config/{service}/{dependency}
body: { failure_rate_threshold: 0.5, min_request_volume: 20,
window_seconds: 10, open_cooldown_ms: 3000, half_open_probes: 3,
cooldown_backoff: 2.0, max_cooldown_ms: 60000 }
-> policy pushed to the fleet (watched/pulled by instances; off the hot path)
GET /state/{service}/{dependency}
-> { state: OPEN, epoch: 8, aggregated_failure_rate: 0.76,
live_instances: 1000, opened_at_ms: ..., current_prober: "inst-02a7" }
# served from the observability read-model (instances report state via gossip->scrape)
POST /override/{service}/{dependency}
body: { action: FORCE_OPEN | FORCE_CLOSE | CLEAR, ttl_seconds: 300 }
-> manual kill switch. FORCE_OPEN sheds a known-bad dependency instantly fleet-wide;
FORCE_CLOSE pins it closed (e.g. a false-positive trip). Propagates via gossip
as a high-epoch pinned state. TTL so an override is not forgotten.
The load-bearing parts: allow()/record() are local and infallible - that is the whole hot-path contract; the gossip epoch is the entire coordination primitive (propagation + prober election + merge ordering in one monotonic number); and the override API is the human escape hatch when the automation is wrong.
Data / storage schema
The breaker service is near-stateless for runtime state - breaker counts and states live in RAM and are continuously recomputed from live traffic. The only durable store is configuration and an observability read-model.
Per-instance in-memory state (ephemeral, rebuilt from traffic + gossip):
local_breaker[dependency] {
state enum # CLOSED | OPEN | HALF_OPEN <- read by allow() hot path
epoch int64 # current epoch for this dep
opened_at_ms int64 # when OPEN started (cooldown math)
buckets ring[10] # 10 x 1s: { window_id, successes, failures } (local)
probe_budget int # remaining probes if HALF_OPEN and I am prober
}
fleet_view[dependency] {
per_instance map<instanceId, {window_id, successes, failures, last_seen_ms}> # TTL'd
merged_state enum # highest-epoch state seen
merged_epoch int64
agg_rate float # sum(failures)/sum(successes+failures) over live, same window
}
membership {
members map<instanceId, last_seen_ms> # live set; TTL ages out dead nodes
}
Configuration store (durable, strongly consistent, off path):
breaker_config (key: service + dependency) # SQL or a config system (etcd/Consul)
service string
dependency string
failure_rate_threshold float # e.g. 0.5
min_request_volume int # don't trip on 2 requests
window_seconds int
open_cooldown_ms int
half_open_probes int
cooldown_backoff float # exponential backoff multiplier on repeated fail
max_cooldown_ms int
override enum? # FORCE_OPEN | FORCE_CLOSE | null (+ ttl)
PRIMARY KEY (service, dependency)
Observability read-model (durable-ish, time-series, off path):
breaker_state_history (append-only, for dashboards/alerting)
ts, service, dependency, state, epoch, agg_rate, live_instances, prober_id
# fed by instances periodically reporting their merged view (scrape or push).
# a time-series DB (Prometheus-style) or a wide-column store - write-heavy, append-only.
Store choice: no database on the hot path; configuration in a strongly-consistent config store; runtime state purely in-memory and gossip-replicated; observability in a time-series store. Reasons:
- Runtime breaker state is ephemeral and self-healing, recomputed every window from live traffic. Persisting it buys nothing - on restart an instance relearns within one window (~10s) from its own traffic and converges from gossip. A database here would add latency and a failure dependency to a path that must be local and infallible. So: RAM + gossip, no DB.
- Configuration is small, read-mostly, and must be consistent (every instance should use the same thresholds). That is a strongly-consistent config store’s sweet spot (etcd/Consul, or a SQL table fronted by a cache). It is off the hot path - instances watch/pull config, they do not read it per request.
- Observability is write-heavy, append-only, time-ranged - a textbook time-series workload. It is a consumer of breaker state, completely off the request and coordination paths, so its availability never affects breaking decisions.
The shape mirrors the mesh-control-plane pattern: a stateless, self-healing runtime layer over a small strongly-consistent config store, with observability as a side consumer - because the one thing that must never have a slow or failing dependency is the decision to break a circuit.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Per-request breaker check (breaks first if done wrong). At ~5M checks/sec fleet-wide, any network or lock on allow() is fatal.
Fix: allow() is a local in-memory read of a single state enum - no syscall, no lock (an atomic/relaxed read of a word), no network. The breaker state is updated out of band by the gossip thread; the hot path only reads it. This is the non-negotiable design constraint everything else bends around.
2. Gossip traffic exploding with per-observation sharing. Sharing every success/failure is 5M messages/sec. Fix: two-level aggregation - count per call locally (free), gossip only compact per-dependency summaries once per round (~2 KB/instance/sec). Traffic is O(instances x deps), not O(requests).
3. Convergence too slow to beat the probe interval. If state takes longer than a cooldown to spread, instances fight (some OPEN, some probing). Fix: epidemic gossip with tuned fanout and round frequency - O(log N) rounds means ~2-4s for 1,000 nodes at fanout 5 / 1s rounds. Raise fanout or shorten rounds to hit a tighter target. Keep the cooldown comfortably larger than convergence time so the fleet always agrees on state before any timer fires.
4. Recovery thundering herd (the headline failure). Every instance probing on cooldown stampedes the recovering dependency into re-death.
Fix: deterministic single-prober election over the gossiped membership and OPEN epoch - every instance computes the same hash(dep, epoch) mod members and only the chosen one probes. ~3 probes reach the dependency, not ~3,000. Epoch bump rotates the prober each round and re-elects around a dead one.
5. Partition latching the fleet OPEN against a healthy dependency. A split that blocks a fleet-wide “close” leaves the breaker as the outage. Fix: local authority as the floor - each instance/partition elects its own prober over its local membership view and recovers independently; epoch-ordered merge (highest epoch wins, ties -> safer OPEN) carries the “healthy” signal across the heal; summary TTL discards stale cross-partition counts. A partition costs one extra prober per side, never a latch-open.
6. Hot dependency skewing the aggregate / prober load. A very popular dependency has huge counts and its prober takes real probe load. Fix: the aggregate is a rate, so volume does not distort it (we normalize failures over total). Prober load is ~3 calls - negligible - and rotates by epoch so no single instance is the perpetual prober for a flapping dependency. Exponential cooldown backoff on repeated probe failure keeps a persistently-dead dependency from being re-probed too often.
7. Clock skew corrupting windowed aggregation. Summing counts across instances assumes a shared notion of “this window.”
Fix: align windows by window_id = floor(now / bucket_size) with NTP-synced clocks (tens of ms is plenty at second-scale buckets), and discard summaries from non-current windows on merge. Skew within a bucket is harmless; gross skew drops the stale summary rather than mixing epochs of evidence.
8. Gossip layer itself failing (the coordination SPOF risk). If the whole gossip plane dies, do we stop breaking? Fix: fail safe to local-only breaking. No gossip -> each instance uses its own window and trips/recovers independently (classic Hystrix). Slower and herd-prone, but live and correct. The gossip layer is an accelerant, never a hard dependency - the system is designed to degrade to the naive-but-robust mode, not to fail.
9. Flapping dependency causing state thrash. A dependency hovering at the threshold trips and closes repeatedly, churning epochs and gossip. Fix: hysteresis - a higher bar to close than to open (require probes to clearly succeed, and a short stabilization period CLOSED before fully trusting), plus cooldown backoff so repeated trips lengthen the OPEN period. The breaker settles instead of oscillating.
10. A bad override or config push. A FORCE_OPEN left on, or a threshold set to 0, could wrongly shed a healthy dependency fleet-wide. Fix: TTLs on overrides (they expire and must be renewed, so none is forgotten), config validation at the control plane (reject nonsensical thresholds), and the override surfaced loudly on the dashboard. The automation’s job is to break circuits; the human escape hatch must be visible and self-expiring.
Wrap-Up
The trade-offs that define this design:
- Decide locally, agree globally. The breaker decision is a lock-free local RAM read on a 5M-RPS hot path; the breaker state is a shared, eventually-consistent value maintained by gossip off the path. Conflating the two - putting a network call or central lock on every request - would rebuild the exact synchronous SPOF that circuit breakers exist to kill.
- Two-level aggregation beats both naive extremes. Local-only breakers are robust but slow and herd-prone; a central aggregator is fast but a SPOF and a hot key. Counting per call locally and gossiping only compact per-dependency summaries gives fleet-wide evidence with no central point and negligible traffic.
- The epoch is the whole coordination primitive. One monotonic number per dependency does triple duty: it propagates the outcome via gossip, it deterministically elects the single prober (
hash(dep, epoch) mod members), and it orders the merge on partition heal (highest epoch wins). Single-prober election over shared state replaces a distributed lock entirely - ~3 probes reach a recovering dependency instead of ~3,000. - Local authority as the floor is what tolerates partitions. Because every instance (and every partition) can elect its own prober and recover on its own evidence, no split can ever latch the fleet OPEN against a healthy dependency. The cost is one extra prober per partition - a bounded, safe degradation, deliberately traded for never-latch-open.
- Stateless and self-healing over a small config store. Runtime breaker state is ephemeral, recomputed from live traffic every window; only configuration is durable and strongly consistent, and observability is a side consumer. The decision to break a circuit must never wait on, or fail because of, a slow database.
One-line summary: every caller instance runs a lock-free local breaker whose allow/reject decision is a sub-microsecond RAM read, while a gossip layer sums compact per-dependency failure summaries into a fleet-wide rate to trip all instances together, and a monotonic epoch per dependency both deterministically elects exactly one recovery prober (killing the thundering herd) and orders state on partition heal - so the fleet converges within one probe interval, degrades to robust local-only breaking if gossip dies, and never latches OPEN against a dependency that has actually recovered.
Comments