rust 74 lines · 8 steps

Building a circuit breaker in Rust

A concurrency-safe circuit breaker that trips open after repeated failures and probes recovery after a timeout.

Explained by highlit
1use std::sync::Mutex;
2use std::time::{Duration, Instant};
3 
4#[derive(Debug, Clone, Copy, PartialEq)]
5enum State {
6 Closed,
7 Open { until: Instant },
8 HalfOpen,
9}
10 
11pub struct CircuitBreaker {
12 inner: Mutex<Inner>,
13 failure_threshold: u32,
14 reset_timeout: Duration,
15}
16 
17struct Inner {
18 state: State,
19 consecutive_failures: u32,
20}
21 
22#[derive(Debug, thiserror::Error)]
23pub enum BreakerError<E> {
24 #[error("circuit breaker is open")]
25 Open,
26 #[error(transparent)]
27 Inner(E),
28}
29 
30impl CircuitBreaker {
31 pub fn new(failure_threshold: u32, reset_timeout: Duration) -> Self {
32 Self {
33 inner: Mutex::new(Inner { state: State::Closed, consecutive_failures: 0 }),
34 failure_threshold,
35 reset_timeout,
36 }
37 }
38 
39 pub async fn call<F, Fut, T, E>(&self, op: F) -> Result<T, BreakerError<E>>
40 where
41 F: FnOnce() -> Fut,
42 Fut: std::future::Future<Output = Result<T, E>>,
43 {
44 {
45 let mut inner = self.inner.lock().unwrap();
46 if let State::Open { until } = inner.state {
47 if Instant::now() >= until {
48 inner.state = State::HalfOpen;
49 } else {
50 return Err(BreakerError::Open);
51 }
52 }
53 }
54 
55 match op().await {
56 Ok(value) => {
57 let mut inner = self.inner.lock().unwrap();
58 inner.consecutive_failures = 0;
59 inner.state = State::Closed;
60 Ok(value)
61 }
62 Err(err) => {
63 let mut inner = self.inner.lock().unwrap();
64 inner.consecutive_failures += 1;
65 if inner.consecutive_failures >= self.failure_threshold
66 || inner.state == State::HalfOpen
67 {
68 inner.state = State::Open { until: Instant::now() + self.reset_timeout };
69 }
70 Err(BreakerError::Inner(err))
71 }
72 }
73 }
74}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A circuit breaker prevents cascading failures by refusing calls once a downstream dependency looks unhealthy.
  2. 2Encoding the reset deadline inside the Open state lets time-based transitions happen without a background timer.
  3. 3Wrapping shared state in a Mutex and locking only around reads and updates keeps the async operation itself off the lock.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a circuit breaker in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code