Skip to main content

backoff_basic/
basic.rs

1//! Drive a retry loop with an exponential backoff policy and full jitter.
2//!
3//! `reliakit-backoff` only computes delays; this example shows how you decide
4//! when to wait and where randomness comes from. Run with:
5//!
6//! ```sh
7//! cargo run -p reliakit-backoff --example basic
8//! ```
9
10use std::time::Duration;
11
12use reliakit_backoff::{full_jitter, Backoff};
13
14fn main() {
15    // 100ms base, double each attempt, capped at 2s, up to 5 retries.
16    let policy = Backoff::exponential(Duration::from_millis(100), 2)
17        .with_max_delay(Duration::from_secs(2))
18        .with_max_retries(5);
19
20    // A tiny deterministic PRNG stands in for a real RNG so the example output
21    // is reproducible. In real code use `rand`, `getrandom`, or a hardware RNG.
22    let mut seed: u32 = 0x9e37_79b9;
23    let mut next_rand = move || {
24        seed ^= seed << 13;
25        seed ^= seed >> 17;
26        seed ^= seed << 5;
27        seed
28    };
29
30    println!("attempt  base-delay  jittered-delay");
31    for (attempt, base) in policy.delays().enumerate() {
32        let jittered = full_jitter(base, next_rand());
33        println!("{attempt:>7}  {base:>10?}  {jittered:>14?}");
34        // In a real loop you would: sleep(jittered); if try_operation().is_ok() { break; }
35    }
36
37    println!("\nretry limit reached; giving up");
38}