Retry with Exponential Backoff (Rust)
Topics: resilience, backoff, closures
Problem
Implement a generic retry helper:
pub struct Config { pub max_attempts: u32, pub base_delay: Duration, pub max_delay: Duration }
pub fn backoff_delay(cfg: &Config, attempt: u32) -> Duration;
pub fn retry<T, E, F: FnMut() -> Result<T, E>>(cfg: &Config, f: F) -> Result<T, E>;
retry calls f up to cfg.max_attempts times. It returns the first Ok. If f keeps
failing, it sleeps backoff_delay(cfg, attempt) between attempts and returns the last Err
once attempts are exhausted.
backoff_delay(cfg, attempt) (attempt is 1-based) is base_delay * 2^(attempt-1), capped at
max_delay.
backoff_delay(base=1ms, max=10s, attempt=1) // 1ms
backoff_delay(base=1ms, max=10s, attempt=4) // 8ms
backoff_delay(base=1ms, max=5ms, attempt=10) // 5ms (capped)
Unlike the Go version, this port uses a deterministic backoff (no random jitter) so the delay
schedule is exactly testable, and exposes backoff_delay separately. Cancellation is left out
(no context in std Rust).
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.