Expand description
Clock-agnostic circuit breaker.
A circuit breaker protects a caller from a failing dependency: once failures pile up it “opens” and rejects calls immediately (failing fast) instead of hammering a service that is already down, then periodically lets a trial call through to test recovery.
CircuitBreaker is a small, Copy state machine. It does not read the
clock, sleep, or allocate — you pass the current time in on each call as a
plain u64 in whatever monotonic unit you choose (milliseconds is typical).
That keeps it usable from synchronous code, any async runtime, and no_std
/ embedded targets, and makes its behavior fully deterministic in tests.
§States
failures >= failure_threshold
Closed ───────────────────────────────▶ Open
▲ │
│ successes >= success_threshold │ cooldown elapsed
│ ▼
└────────────── HalfOpen ◀──────────────┘
│
│ any failure
└──────────────▶ Open- Closed — calls flow normally. Consecutive failures are counted; once
they reach
failure_thresholdthe breaker trips to Open. - Open — calls are rejected immediately. After
cooldowntime units the nextallowmoves it to HalfOpen. - HalfOpen — trial calls are allowed.
success_thresholdconsecutive successes close the breaker; the first failure reopens it.
§Example
use reliakit_circuit::{CircuitBreaker, State};
// Trip after 3 consecutive failures; stay open for 30_000 ms.
let mut cb = CircuitBreaker::new(3, 30_000);
// A run of failures opens the breaker.
for _ in 0..3 {
assert!(cb.allow(0)); // still Closed, calls allowed
cb.on_failure(0);
}
assert_eq!(cb.state(), State::Open);
assert!(!cb.allow(1_000)); // rejected while Open (cooldown not elapsed)
// After the cooldown, one trial call is allowed (HalfOpen).
assert!(cb.allow(31_000));
assert_eq!(cb.state(), State::HalfOpen);
// A success closes it again.
cb.on_success();
assert_eq!(cb.state(), State::Closed);Structs§
- Circuit
Breaker - A circuit breaker: a small,
Copystate machine that decides whether calls to a dependency should be allowed, based on their recent success/failure history and a caller-supplied clock.
Enums§
- State
- The state of a
CircuitBreaker.