Crate tower_circuitbreaker

Crate tower_circuitbreaker 

Source
Expand description

§DEPRECATED: Use tower-resilience instead

This crate has been superseded by tower-resilience, which provides a comprehensive suite of resilience patterns including circuit breakers, bulkheads, retries, time limiters, caching, and rate limiting.

§Migration

Old (tower-circuitbreaker):

[dependencies]
tower-circuitbreaker = "0.1"

New (tower-resilience):

[dependencies]
tower-resilience = "0.2"
# Or use the individual crate:
tower-resilience-circuitbreaker = "0.3"

API Changes:

// Old API
use tower_circuitbreaker::circuit_breaker_builder;
let cb = circuit_breaker_builder::<String, ()>()
    .failure_rate_threshold(0.5)
    .build();

// New API
use tower_resilience::circuitbreaker::CircuitBreakerLayer;
let cb = CircuitBreakerLayer::<String, ()>::builder()
    .failure_rate_threshold(0.5)
    .build();

For more information, see:


§Original Documentation

A Tower middleware implementing circuit breaker behavior to improve the resilience of asynchronous services.

§Features

  • Circuit breaker states: Closed, Open, Half-Open
  • Configurable failure rate threshold and sliding window size
  • Customizable failure_classifier to define what counts as a failure
  • Metrics support via the metrics feature flag
  • Tracing support via the tracing feature flag

§Example

use tower_circuitbreaker::circuit_breaker_builder;
use tower::ServiceBuilder;
use tower::service_fn;
use tower::Service;
use std::time::Duration;

#[tokio::main]
async fn main() {
    // Build a circuit breaker layer with custom settings
    let circuit_breaker_layer = circuit_breaker_builder::<_, ()>()
        .failure_rate_threshold(0.3)
        .sliding_window_size(50)
        .wait_duration_in_open(Duration::from_secs(10))
        .build();

    // Create a minimal service that echoes the request
    let my_service = service_fn(|req| async move { Ok::<_, ()>(req) });

    // Wrap the service with the circuit breaker
    let mut service = ServiceBuilder::new()
        .layer(circuit_breaker_layer)
        .service(my_service);

    // Use the service
    let response = Service::call(&mut service, "hello").await.unwrap();
    assert_eq!(response, "hello");

    // Error handling example
    match Service::call(&mut service, "hello").await {
        Ok(resp) => println!("got {}", resp),
        Err(e) if e.is_circuit_open() => println!("circuit open"),
        Err(e) => eprintln!("service error: {:?}", e.into_inner()),
    }
}

§Feature Flags

  • metrics: enables metrics collection using the metrics crate.
  • tracing: enables logging and tracing using the tracing crate.

Structs§

CircuitBreaker
A Tower Service that applies circuit breaker logic to an inner service.

Enums§

CircuitBreakerError
Errors returned by the CircuitBreaker service.
CircuitState
Represents the state of the circuit breaker.

Functions§

circuit_breaker_builder
Returns a new builder for a CircuitBreakerLayer.