Circuit Breaker Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circuit Breaker runs in O(1) time and O(1) space, in Rust as in every other language.
- ✓There is no breaker in std. The tower ecosystem is the idiomatic home for this in Rust: a breaker is a Layer wrapping a Service, composing with tower::timeout, tower::limit and tower::retry so the whole resilience stack is one typed service.
- ✓Implement or adopt the breaker as a tower Layer so it composes with the rest of the stack and applies once at the boundary rather than at each call site.
- ✓The Rust trap: A breaker built with a Mutex around its state serialises every call through one lock in the CLOSED state, which is the hot path, under high concurrency the breaker itself becomes the bottleneck it exists to prevent, so the state machine should use atomics for the common transitions.
- ✓A well-implemented closed-state check is one or two relaxed atomic loads, on the order of a nanosecond, so the breaker is genuinely free when things are healthy.
What Circuit Breaker actually is
Circuit Breaker in Rust: what you actually reach for
Rust implementation
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
pub enum BreakerError<E> {
Open, // rejected without calling the dependency
Inner(E),
}
pub struct Breaker {
failures: AtomicU32,
threshold: u32,
opened_at_ms: AtomicU64, // 0 == closed
reset_after: Duration,
half_open_permits: AtomicU32,
start: Instant,
}
impl Breaker {
pub fn new(threshold: u32, reset_after: Duration) -> Self {
Self {
failures: AtomicU32::new(0),
threshold,
opened_at_ms: AtomicU64::new(0),
reset_after,
half_open_permits: AtomicU32::new(1), // CAP the trial calls
start: Instant::now(),
}
}
fn now_ms(&self) -> u64 { self.start.elapsed().as_millis() as u64 }
/// Closed-state fast path: two relaxed atomic loads, no lock.
pub fn allow(&self) -> bool {
let opened = self.opened_at_ms.load(Ordering::Relaxed);
if opened == 0 {
return true;
}
if self.now_ms().saturating_sub(opened) < self.reset_after.as_millis() as u64 {
return false;
}
// HALF-OPEN: admit a bounded number of trials, never the whole backlog.
self.half_open_permits
.fetch_update(Ordering::AcqRel, Ordering::Acquire,
|p| if p > 0 { Some(p - 1) } else { None })
.is_ok()
}
pub fn on_success(&self) {
self.failures.store(0, Ordering::Relaxed);
self.opened_at_ms.store(0, Ordering::Relaxed);
self.half_open_permits.store(1, Ordering::Relaxed);
}
pub fn on_failure(&self) {
if self.failures.fetch_add(1, Ordering::Relaxed) + 1 >= self.threshold {
self.opened_at_ms.store(self.now_ms().max(1), Ordering::Relaxed);
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Circuit Breaker?
There is no breaker in std. The tower ecosystem is the idiomatic home for this in Rust: a breaker is a Layer wrapping a Service, composing with tower::timeout, tower::limit and tower::retry so the whole resilience stack is one typed service. failsafe is a standalone crate with configurable failure policies. The tower approach means the breaker applies uniformly to every call through that service.
What is the most common Rust mistake when implementing Circuit Breaker?
A breaker built with a Mutex around its state serialises every call through one lock in the CLOSED state, which is the hot path, under high concurrency the breaker itself becomes the bottleneck it exists to prevent, so the state machine should use atomics for the common transitions. The second trap is unlimited HALF-OPEN concurrency: if every waiting task is admitted the moment the reset timer fires, the recovering dependency receives the full backlog at once and fails again, so the number of trial calls must be capped explicitly.
How does Circuit Breaker actually perform in Rust?
A well-implemented closed-state check is one or two relaxed atomic loads, on the order of a nanosecond, so the breaker is genuinely free when things are healthy. Because Rust async tasks are so cheap, the caller-side exhaustion this pattern prevents shows up as unbounded task and connection growth rather than thread starvation, the remedy is the same, and pairing the breaker with a concurrency limit is what actually bounds it. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.