8 releases (4 stable)

1.3.0 Jul 5, 2024
1.2.0 Aug 22, 2022
1.1.0 Jul 17, 2021
1.0.0 Aug 17, 2020
0.1.0 Sep 3, 2018

#37 in Asynchronous

Download history 77331/week @ 2024-07-29 72069/week @ 2024-08-05 97351/week @ 2024-08-12 106807/week @ 2024-08-19 99790/week @ 2024-08-26 87350/week @ 2024-09-02 124729/week @ 2024-09-09 101009/week @ 2024-09-16 128262/week @ 2024-09-23 120375/week @ 2024-09-30 157642/week @ 2024-10-07 127374/week @ 2024-10-14 155472/week @ 2024-10-21 150438/week @ 2024-10-28 156623/week @ 2024-11-04 153706/week @ 2024-11-11

617,280 downloads per month
Used in 8 crates (5 directly)

MIT license

75KB
1.5K SLoC

Failsafe

Сrate Вocumentation CircleCI Appveyor

A circuit breaker implementation which used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.

Features

  • Working with both Fn() -> Result and Future (optional via default futures-support feature).
  • Backoff strategies: constant, exponential, equal_jittered, full_jittered
  • Failure detection policies: consecutive_failures, success_rate_over_time_window
  • Minimum rust version: 1.59

Usage

Add this to your Cargo.toml:

failsafe = "1.3.0"

Example

Using default backoff strategy and failure accrual policy.

use failsafe::{Config, CircuitBreaker, Error};

// A function that sometimes failed.
fn dangerous_call() -> Result<(), ()> {
  if thread_rng().gen_range(0, 2) == 0 {
    return Err(())
  }
  Ok(())
}

// Create a circuit breaker which configured by reasonable default backoff and
// failure accrual policy.
let circuit_breaker = Config::new().build();

// Call the function in a loop, after some iterations the circuit breaker will
// be in a open state and reject next calls.
for n in 0..100 {
  match circuit_breaker.call(|| dangerous_call()) {
    Err(Error::Inner(_)) => {
      eprintln!("{}: fail", n);
    },
    Err(Error::Rejected) => {
       eprintln!("{}: rejected", n);
       break;
    },
    _ => {}
  }
}

Or configure custom backoff and policy:

use std::time::Duration;
use failsafe::{backoff, failure_policy, CircuitBreaker};

// Create an exponential growth backoff which starts from 10s and ends with 60s.
let backoff = backoff::exponential(Duration::from_secs(10), Duration::from_secs(60));

// Create a policy which failed when three consecutive failures were made.
let policy = failure_policy::consecutive_failures(3, backoff);

// Creates a circuit breaker with given policy.
let circuit_breaker = Config::new()
  .failure_policy(policy)
  .build();

Dependencies

~0.6–5.5MB
~19K SLoC