Circuit breaker
Rust 1,279 lines (858 code)split
| Part | Code | Comments | Blank | Total | Files |
|---|---|---|---|---|---|
| Rust source | 858 | 315 | 106 | 1,279 | 3 |
| Rust tests | 34 | 0 | 4 | 38 | 1 |
Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.
Install#
The crate lives in the Appwrite repository; depend on it from Git.
[dependencies]
utopia-circuit-breaker = { git = "https://github.com/appwrite/appwrite" }Getting started#
Common tasks with Circuit breaker, each a complete program you can copy and run.
A circuit breaker sits in front of a dependency (a database, a cache, another service) and stops calling it while it keeps failing, so callers get a fallback at once instead of waiting on errors, and the dependency gets room to recover. This library judges a dependency on the share of recent calls that failed, lets a few probes through after a cool-down, and can share its verdict between processes. The breaker is async, so the examples run it on a Tokio runtime. This guide covers the common tasks.
Guard a call
call runs the call while the circuit is closed and returns its value; when the call fails, or the circuit is open, it returns the fallback instead. The call is a future returning a Result; an Err counts as a failure.
use utopia_circuit_breaker::{CircuitBreaker, Options};
let breaker = CircuitBreaker::new(Options::default())?;
let value = tokio::runtime::Builder::new_current_thread().enable_all().build()?.block_on(async {
breaker.call(|| "cached copy", async { Ok::<_, &str>("fresh value") }).await
})?;
assert_eq!(value, "fresh value");Decide when to open
A circuit opens once the window holds at least minimum_throughput calls and the share that failed reaches failure_ratio. A burst of failures among healthy traffic does not open it; sustained failure does.
use utopia_circuit_breaker::{CircuitBreaker, Options, State};
let breaker = CircuitBreaker::new(Options { window: 60, failure_ratio: 0.5, minimum_throughput: 4, ..Options::default() })?;
tokio::runtime::Builder::new_current_thread().enable_all().build()?.block_on(async {
for _ in 0..4 {
breaker.call(|| "fallback", async { Err::<&str, _>("timeout") }).await?;
}
assert_eq!(breaker.state().await?, State::Open);
assert_eq!(breaker.call(|| "fallback", async { Ok::<_, &str>("skipped") }).await?, "fallback");
Ok::<_, utopia_circuit_breaker::Error>(())
})?;Probe for recovery
After timeout seconds an open circuit is half open: up to half_open_permitted_calls probes run at once, success_threshold successes close it, and one failure opens it again. call_with_probe runs a lighter call as the probe.
use utopia_circuit_breaker::{CircuitBreaker, Options, State};
let breaker = CircuitBreaker::new(Options { timeout: 0, success_threshold: 1, ..Options::default() })?;
tokio::runtime::Builder::new_current_thread().enable_all().build()?.block_on(async {
breaker.trip().await?;
let value = breaker
.call_with_probe(|| "fallback", async { Ok::<_, &str>("full query") }, async { Ok("ping") })
.await?;
assert_eq!(value, "ping");
assert_eq!(breaker.state().await?, State::Closed);
Ok::<_, utopia_circuit_breaker::Error>(())
})?;Share the verdict between processes
Breakers with the same key and store share their state: when one opens the circuit, the others see it open. Use Redis across hosts, or a Table within one process. Each breaker still measures its own window.
use std::sync::Arc;
use utopia_circuit_breaker::{CircuitBreaker, Options, SharedTable, State, Table};
let table = SharedTable::default();
let options = Options { key: "users-api".into(), ..Options::default() };
let first = CircuitBreaker::with_cache(options.clone(), Arc::new(Table::new(table.clone(), "breaker:")))?;
let second = CircuitBreaker::with_cache(options, Arc::new(Table::new(table, "breaker:")))?;
tokio::runtime::Builder::new_current_thread().enable_all().build()?.block_on(async {
first.trip().await?;
assert_eq!(second.state().await?, State::Open);
Ok::<_, utopia_circuit_breaker::Error>(())
})?;Report metrics
With a telemetry backend, a breaker counts its calls, fallbacks, failures and transitions, and reports its state as observable gauges read at collection.
use std::sync::Arc;
use utopia_circuit_breaker::{CircuitBreaker, Options};
use utopia_telemetry::{Kind, MemoryTelemetry};
let telemetry = MemoryTelemetry::new();
let breaker = CircuitBreaker::new(Options::default())?;
breaker.set_telemetry(Arc::new(telemetry.clone()));
tokio::runtime::Builder::new_current_thread().enable_all().build()?.block_on(async {
breaker.call(|| "fallback", async { Ok::<_, &str>("ok") }).await
})?;
assert_eq!(telemetry.values(Kind::Counter, "breaker.calls"), Some(vec![1.into()]));Reference#
A circuit breaker stops calling a dependency that keeps failing, so callers get a fallback at once instead of waiting on errors, and the dependency gets room to recover.
A CircuitBreaker starts [State::Closed]: calls go through, and their
outcomes fill a rolling window. Once the window holds enough calls
(minimum_throughput) and the share that failed reaches failure_ratio,
the circuit opens: calls take their fallback without running. After
timeout seconds it is half open, and a limited number of probes go
through at once: success_threshold successes close it, one failure
opens it again.
The verdict (state, when it opened, probe counts) can be shared between
processes through an Adapter (Redis, or a Table in one
process); the window is always measured per process. Breakers report
their calls, fallbacks and transitions to a Telemetry backend, and
their state as observable gauges.
use utopia_circuit_breaker::{CircuitBreaker, Options, State};
let breaker = CircuitBreaker::new(Options { minimum_throughput: 2, ..Options::default() })?;
for _ in 0..2 {
let value = breaker.call(|| "fallback", async { Err::<&str, _>("failed") }).await?;
assert_eq!(value, "fallback");
}
assert_eq!(breaker.state().await?, State::Open);Modules#
Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.
API#
What utopia_circuit_breaker exports at its root.