6 releases (2 stable)

1.1.0 Dec 20, 2021
1.0.0 Dec 27, 2020
0.2.2 Jul 12, 2018
0.1.0 Jul 11, 2018

#238 in Rust patterns

Download history 482/week @ 2022-08-11 510/week @ 2022-08-18 433/week @ 2022-08-25 344/week @ 2022-09-01 468/week @ 2022-09-08 526/week @ 2022-09-15 679/week @ 2022-09-22 376/week @ 2022-09-29 570/week @ 2022-10-06 466/week @ 2022-10-13 760/week @ 2022-10-20 723/week @ 2022-10-27 781/week @ 2022-11-03 962/week @ 2022-11-10 854/week @ 2022-11-17 427/week @ 2022-11-24

3,128 downloads per month
Used in 3 crates

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

~370KB