#backoff #exponential #retry #async

exponential-backoff

An exponential backoff generator with jitter

9 releases (5 stable)

2.0.0 Aug 23, 2024
1.2.1 Aug 15, 2024
1.2.0 Jan 30, 2023
1.1.0 Dec 20, 2021
0.1.0 Jul 11, 2018

#65 in Asynchronous

Download history 7115/week @ 2024-08-21 6239/week @ 2024-08-28 6400/week @ 2024-09-04 6314/week @ 2024-09-11 6704/week @ 2024-09-18 6871/week @ 2024-09-25 10032/week @ 2024-10-02 11648/week @ 2024-10-09 10366/week @ 2024-10-16 12290/week @ 2024-10-23 12345/week @ 2024-10-30 14221/week @ 2024-11-06 12924/week @ 2024-11-13 16367/week @ 2024-11-20 15541/week @ 2024-11-27 16262/week @ 2024-12-04

63,651 downloads per month
Used in 18 crates (9 directly)

MIT/Apache

11KB
107 lines

exponential-backoff

crates.io version downloads docs.rs docs

An exponential backoff generator with jitter. 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 attempts = 3;
let min = Duration::from_millis(100);
let max = Duration::from_secs(10);

for duration in Backoff::new(attempts, min, max) {
    match fs::read_to_string("README.md") {
        Ok(string) => return Ok(string),
        Err(err) => match duration {
            Some(duration) => thread::sleep(duration),
            None => return Err(err),
        }
    }
}

Installation

$ cargo add exponential-backoff

See Also

Further Reading

License

MIT OR Apache-2.0

Dependencies

~28KB