Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add jitter to constant backoff #47

Merged
merged 1 commit into from
Feb 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ name = "backon"
version = "0.4.0"

[dependencies]
futures = "0.3"
fastrand = "1.9.0"
futures-core = "0.3.26"
pin-project = "1"
rand = "0.8"
tokio = { version = "1", features = ["time"] }

[dev-dependencies]
Expand Down
28 changes: 26 additions & 2 deletions src/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ use crate::backoff::BackoffBuilder;
pub struct ConstantBuilder {
delay: Duration,
max_times: Option<usize>,
jitter: bool,
}

impl Default for ConstantBuilder {
fn default() -> Self {
Self {
delay: Duration::from_secs(1),
max_times: Some(3),
jitter: false,
}
}
}
Expand All @@ -58,6 +60,12 @@ impl ConstantBuilder {
self.max_times = Some(max_times);
self
}

/// Set jitter on
pub fn with_jitter(mut self) -> Self {
self.jitter = true;
self
}
}

impl BackoffBuilder for ConstantBuilder {
Expand All @@ -69,6 +77,7 @@ impl BackoffBuilder for ConstantBuilder {
max_times: self.max_times,

attempts: 0,
jitter: self.jitter,
}
}
}
Expand All @@ -80,6 +89,7 @@ pub struct ConstantBackoff {
max_times: Option<usize>,

attempts: usize,
jitter: bool,
}

impl Default for ConstantBackoff {
Expand All @@ -88,6 +98,7 @@ impl Default for ConstantBackoff {
delay: Duration::from_secs(1),
max_times: Some(3),
attempts: 0,
jitter: false,
}
}
}
Expand All @@ -96,14 +107,18 @@ impl Iterator for ConstantBackoff {
type Item = Duration;

fn next(&mut self) -> Option<Self::Item> {
let delay = || match self.jitter {
true => self.delay + self.delay.mul_f32(fastrand::f32()),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In default case it's a little strange to set delay(1s) + jitter(1s in some cases), so double the main delay. But maybe it's ok.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can add jitter range for user in the future, let's merge first.

false => self.delay,
};
match self.max_times {
None => Some(self.delay),
None => Some(delay()),
Some(max_times) => {
if self.attempts >= max_times {
None
} else {
self.attempts += 1;
Some(self.delay)
Some(delay())
}
}
}
Expand Down Expand Up @@ -146,4 +161,13 @@ mod tests {
assert_eq!(Some(Duration::from_secs(1)), exp.next());
assert_eq!(None, exp.next());
}

#[test]
fn test_constant_with_jitter() {
let mut it = ConstantBuilder::default().with_jitter().build();

let dur = it.next().unwrap();
fastrand::seed(7);
assert!(dur > Duration::from_secs(1));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's hard to test random things, this should be something like delay <= dur < delay + rng

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you willing to start a new PR for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe for unit test is enough. I will try to find a better solution, but I'm not sure.

}
}
10 changes: 2 additions & 8 deletions src/exponential.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use std::time::Duration;

use rand::Rng;

use crate::backoff::BackoffBuilder;

/// ExponentialBuilder is used to build a [`ExponentialBackoff`]
Expand Down Expand Up @@ -149,9 +147,7 @@ impl Iterator for ExponentialBackoff {

// If jitter is enabled, add random jitter based on min delay.
if self.jitter {
cur += self
.min_delay
.mul_f32(rand::thread_rng().gen_range(0.0..1.0));
cur += self.min_delay.mul_f32(fastrand::f32());
}

Some(cur)
Expand All @@ -167,9 +163,7 @@ impl Iterator for ExponentialBackoff {

// If jitter is enabled, add random jitter based on min delay.
if self.jitter {
cur += self
.min_delay
.mul_f32(rand::thread_rng().gen_range(0.0..1.0));
cur += self.min_delay.mul_f32(fastrand::f32());
}

Some(cur)
Expand Down
2 changes: 1 addition & 1 deletion src/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::task::Context;
use std::task::Poll;
use std::time::Duration;

use futures::ready;
use futures_core::ready;
use pin_project::pin_project;

use crate::backoff::BackoffBuilder;
Expand Down