Skip to main content

bulkhead_basic/
basic.rs

1//! Guard a slow dependency with a concurrency limit.
2//!
3//! `reliakit-bulkhead` only tracks permits; this example shows how you acquire
4//! before work and release after, shedding load when the limit is reached. Run
5//! with:
6//!
7//! ```sh
8//! cargo run -p reliakit-bulkhead --example basic
9//! ```
10
11use reliakit_bulkhead::Bulkhead;
12
13fn main() {
14    // Allow at most three concurrent calls to a downstream service.
15    let mut bulkhead = Bulkhead::new(3);
16
17    // Six requests arrive while none have finished yet.
18    println!("capacity: {}", bulkhead.capacity());
19    for request in 0..6 {
20        if bulkhead.try_acquire_one() {
21            println!(
22                "request {request}: admitted ({} in flight)",
23                bulkhead.in_flight()
24            );
25        // ... start the work; release the permit when it completes ...
26        } else {
27            println!("request {request}: rejected (bulkhead full), shed load");
28        }
29    }
30
31    // Two of the in-flight operations finish and return their permits.
32    bulkhead.release(2);
33    println!(
34        "\nafter two completions: {} available",
35        bulkhead.available()
36    );
37
38    // Room exists again, so the next request is admitted.
39    if bulkhead.try_acquire_one() {
40        println!("retry: admitted ({} in flight)", bulkhead.in_flight());
41    }
42}