use std::time::Duration;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestFailure {
RateLimited,
Overloaded,
Transport,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FailedAttempt {
pub index: u32,
pub failure: RequestFailure,
pub server_hint: Option<Duration>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backoff {
GiveUp,
WaitThenRetry(Duration),
}
pub trait BackoffPolicy: Send + Sync {
fn after_failure(&self, attempt: &FailedAttempt) -> Backoff;
}
pub struct LadderBackoff {
pub steps: Vec<u64>,
pub jitter_ratio: f32,
}
impl LadderBackoff {
pub const DEFAULT_STEPS: &'static [u64] = &[1_000, 2_000, 4_000, 8_000, 16_000, 32_000];
pub const DEFAULT_JITTER: f32 = 0.25;
pub const MAX_SERVER_HINT: Duration = Duration::from_secs(60);
pub fn new() -> Self {
Self::from_millis(Self::DEFAULT_STEPS.to_vec())
}
pub fn from_millis(steps: Vec<u64>) -> Self {
Self {
steps,
jitter_ratio: Self::DEFAULT_JITTER,
}
}
}
impl Default for LadderBackoff {
fn default() -> Self {
Self::new()
}
}
impl BackoffPolicy for LadderBackoff {
fn after_failure(&self, attempt: &FailedAttempt) -> Backoff {
if attempt.failure == RequestFailure::Other {
return Backoff::GiveUp;
}
let Some(step) = self.steps.get(attempt.index as usize) else {
return Backoff::GiveUp;
};
match attempt.server_hint {
Some(hint) if hint > Self::MAX_SERVER_HINT => Backoff::GiveUp,
Some(hint) => Backoff::WaitThenRetry(after_hint(hint)),
None => Backoff::WaitThenRetry(jittered(*step, self.jitter_ratio)),
}
}
}
fn jittered(base_ms: u64, ratio: f32) -> Duration {
let unit = unit_noise();
let signed = (unit - 0.5) * 2.0;
let delta_ms = (base_ms as f32 * ratio * signed) as i64;
let base = i64::try_from(base_ms).unwrap_or(i64::MAX);
let final_ms = base.saturating_add(delta_ms).max(0) as u64;
Duration::from_millis(final_ms)
}
fn after_hint(hint: Duration) -> Duration {
hint + hint.mul_f32(0.1 * unit_noise())
}
fn unit_noise() -> f32 {
use std::time::SystemTime;
let nanos = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
(nanos % 1_000_000) as f32 / 1_000_000.0
}
pub struct NoBackoff;
impl BackoffPolicy for NoBackoff {
fn after_failure(&self, _attempt: &FailedAttempt) -> Backoff {
Backoff::GiveUp
}
}
#[cfg(test)]
mod tests {
use super::*;
fn at(index: u32, failure: RequestFailure) -> FailedAttempt {
FailedAttempt {
index,
failure,
server_hint: None,
}
}
fn wait_ms(b: Backoff) -> u64 {
match b {
Backoff::WaitThenRetry(d) => d.as_millis() as u64,
Backoff::GiveUp => panic!("expected a retry, got GiveUp"),
}
}
#[test]
fn a_server_hint_beyond_the_cap_gives_up_instead_of_wrapping() {
let p = LadderBackoff::new();
for secs in [61, 3_600, u64::MAX] {
let attempt = FailedAttempt {
index: 0,
failure: RequestFailure::RateLimited,
server_hint: Some(Duration::from_secs(secs)),
};
assert_eq!(p.after_failure(&attempt), Backoff::GiveUp, "{secs}s");
}
let at_cap = FailedAttempt {
index: 0,
failure: RequestFailure::RateLimited,
server_hint: Some(LadderBackoff::MAX_SERVER_HINT),
};
assert!(wait_ms(p.after_failure(&at_cap)) >= 45_000);
}
#[test]
fn jitter_of_a_huge_base_saturates() {
assert!(jittered(u64::MAX, 0.25) >= Duration::from_millis(i64::MAX as u64 / 2));
}
#[test]
fn the_ladder_is_one_to_thirty_two_seconds_and_then_stops() {
let p = LadderBackoff::new();
let expected = [1_000u64, 2_000, 4_000, 8_000, 16_000, 32_000];
for (i, base) in expected.iter().enumerate() {
let ms = wait_ms(p.after_failure(&at(i as u32, RequestFailure::Overloaded)));
let slack = (*base as f64 * LadderBackoff::DEFAULT_JITTER as f64) as u64;
assert!(
ms >= base - slack && ms <= base + slack,
"step {i}: {ms}ms is not within ±25% of {base}ms"
);
}
assert_eq!(
p.after_failure(&at(6, RequestFailure::Overloaded)),
Backoff::GiveUp,
"six delays is six retries"
);
}
#[test]
fn a_failure_that_will_not_get_better_is_not_retried() {
assert_eq!(
LadderBackoff::new().after_failure(&at(0, RequestFailure::Other)),
Backoff::GiveUp
);
}
#[test]
fn rate_limits_overload_and_transport_failures_all_retry() {
let p = LadderBackoff::new();
for failure in [
RequestFailure::RateLimited,
RequestFailure::Overloaded,
RequestFailure::Transport,
] {
assert!(
matches!(p.after_failure(&at(0, failure)), Backoff::WaitThenRetry(_)),
"{failure:?} should retry"
);
}
}
#[test]
fn a_server_hint_replaces_the_step_without_extending_the_budget() {
let p = LadderBackoff::new();
let hinted = |index| FailedAttempt {
index,
failure: RequestFailure::RateLimited,
server_hint: Some(Duration::from_secs(7)),
};
for _ in 0..200 {
let ms = wait_ms(p.after_failure(&hinted(0)));
assert!(
(7_000..=7_700).contains(&ms),
"{ms}ms is not the hinted 7s plus at most 10%"
);
}
assert_eq!(p.after_failure(&hinted(6)), Backoff::GiveUp);
}
#[test]
fn jitter_stays_inside_the_band_it_promises() {
for _ in 0..200 {
let ms = jittered(1_000, 0.25).as_millis() as u64;
assert!((750..=1_250).contains(&ms), "{ms}ms escaped the ±25% band");
}
assert_eq!(jittered(1_000, 0.0), Duration::from_millis(1_000));
}
#[test]
fn a_deployment_behind_its_own_gateway_can_refuse_to_wait_at_all() {
for failure in [
RequestFailure::RateLimited,
RequestFailure::Overloaded,
RequestFailure::Transport,
RequestFailure::Other,
] {
assert_eq!(NoBackoff.after_failure(&at(0, failure)), Backoff::GiveUp);
}
}
}