7 releases (3 stable)

1.2.0 Jan 30, 2023
1.1.0 Dec 20, 2021
1.0.0 Dec 27, 2020
0.2.2 Jul 12, 2018
0.1.0 Jul 11, 2018

#274 in Rust patterns

Download history 892/week @ 2023-11-20 910/week @ 2023-11-27 1035/week @ 2023-12-04 1159/week @ 2023-12-11 1834/week @ 2023-12-18 892/week @ 2023-12-25 1708/week @ 2024-01-01 1731/week @ 2024-01-08 2189/week @ 2024-01-15 1698/week @ 2024-01-22 1957/week @ 2024-01-29 2664/week @ 2024-02-05 3040/week @ 2024-02-12 3273/week @ 2024-02-19 3293/week @ 2024-02-26 3591/week @ 2024-03-04

13,271 downloads per month
Used in 9 crates (4 directly)

MIT/Apache

11KB
111 lines

exponential-backoff

crates.io version build status downloads docs.rs docs

Exponential backoff generator. Serves as a building block to implement custom retry functions.

Why?

When an network requests times out, often the best way to solve it is to try again. But trying again straight away might at best cause some network overhead, and at worst a full fledged DDOS. So we have to be responsible about it.

A good explanation of retry strategies can be found on the Stripe blog.

Usage

Here we try and read a file from disk, and try again if it fails. A more realistic scenario would probably to perform an HTTP request, but the approach should be similar.

use exponential_backoff::Backoff;
use std::{fs, thread, time::Duration};

let retries = 8;
let min = Duration::from_millis(100);
let max = Duration::from_secs(10);
let backoff = Backoff::new(retries, min, max);

for duration in &backoff {
    match fs::read_to_string("README.md") {
        Ok(string) => return Ok(string),
        Err(err) => match duration {
            Some(duration) => thread::sleep(duration),
            None => return err,
        }
    }
}

Installation

$ cargo add exponential-backoff

See Also

Further Reading

License

MIT OR Apache-2.0

Dependencies

~315KB