Crates.io | exponential-backoff |
lib.rs | exponential-backoff |
version | 2.0.0 |
source | src |
created_at | 2018-07-11 15:30:03.089507 |
updated_at | 2024-08-23 14:33:40.48582 |
description | An exponential backoff generator with jitter. |
homepage | |
repository | https://github.com/yoshuawuyts/exponential-backoff |
max_upload_size | |
id | 73777 |
size | 30,215 |
An exponential backoff generator with jitter. Serves as a building block to implement custom retry functions.
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.
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),
}
}
}
$ cargo add exponential-backoff
MIT OR Apache-2.0