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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A circuit breaker prevents cascading failures by refusing calls once a downstream dependency looks unhealthy.
- 2Encoding the reset deadline inside the Open state lets time-based transitions happen without a background timer.
- 3Wrapping shared state in a Mutex and locking only around reads and updates keeps the async operation itself off the lock.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-circuit-breaker-in-rust-explained-rust-53c8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.