Circuit Breaker (Rust)
Topics: networking, resilience, state machine
Problem
Implement a circuit breaker with Closed → Open → Half-Open states:
pub enum BreakerError { Open, Inner(String) }
impl Breaker {
pub fn new(max_failures: u32, cooldown: Duration) -> Self;
pub fn do_call<F: FnOnce() -> Result<(), String>>(&self, f: F) -> Result<(), BreakerError>;
}
- Closed: run
f. A success resets the failure counter; max_failures consecutive failures
trip the breaker Open.
- Open: reject calls with
Err(Open) without running f, until cooldown elapses.
- Half-Open: after the cooldown, allow exactly one probe call through; all other concurrent
callers get
Err(Open). If the probe succeeds the breaker closes; if it fails it reopens.
The single-probe guarantee must hold under concurrency: while a probe is in flight, every other
caller is rejected.
Hint: hold the phase, failure count, opened-at Instant, and a probe_in_flight flag behind one
Mutex; make the admission decision under the lock, then run f unlocked.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.