fedimint_core/util/
backoff_util.rs

1use std::time::Duration;
2
3pub use backon::{Backoff, FibonacciBackoff};
4use backon::{BackoffBuilder, FibonacciBuilder};
5
6/// Backoff strategy for background tasks.
7///
8/// Starts at 1s and increases to 60s, never giving up.
9pub fn background_backoff() -> FibonacciBackoff {
10    custom_backoff(Duration::from_secs(1), Duration::from_secs(60), None)
11}
12
13/// A backoff strategy for relatively quick foreground operations.
14///
15/// Starts at 200ms and increases to 5s. Will retry 10 times before giving up,
16/// with a maximum total delay between 20.8s and 22.8s depending on jitter.
17pub fn aggressive_backoff() -> FibonacciBackoff {
18    // Not accounting for jitter, the delays are:
19    // 0.2, 0.2, 0.4, 0.6, 1.0, 1.6, 2.6, 4.2, 5.0, 5.0.
20    //
21    // Jitter adds a random value between 0 and `min_delay` to each delay.
22    // Total jitter is between 0 and (10 * 0.2) = 2.0.
23    //
24    // Maximum possible delay including jitter is 22.8 seconds.
25    custom_backoff(Duration::from_millis(200), Duration::from_secs(5), Some(10))
26}
27
28pub fn aggressive_backoff_long() -> FibonacciBackoff {
29    custom_backoff(Duration::from_millis(200), Duration::from_secs(5), Some(15))
30}
31
32#[cfg(test)]
33pub fn immediate_backoff(max_retries_or: Option<usize>) -> FibonacciBackoff {
34    custom_backoff(Duration::ZERO, Duration::ZERO, max_retries_or)
35}
36
37pub fn custom_backoff(
38    min_delay: Duration,
39    max_delay: Duration,
40    max_retries_or: Option<usize>,
41) -> FibonacciBackoff {
42    FibonacciBuilder::default()
43        .with_jitter()
44        .with_min_delay(min_delay)
45        .with_max_delay(max_delay)
46        .with_max_times(max_retries_or.unwrap_or(usize::MAX))
47        .build()
48}
49
50/// Retry every max 10s for up to one hour, with a more aggressive fibonacci
51/// backoff in the beginning to reduce expected latency.
52///
53/// Starts at 200ms increasing to 10s. Retries 360 times before giving up, with
54/// a maximum total delay between 3527.6s (58m 47.6s) and 3599.6s (59m 59.6s)
55/// depending on jitter.
56pub fn fibonacci_max_one_hour() -> FibonacciBackoff {
57    // Not accounting for jitter, the delays are:
58    // 0.2, 0.2, 0.4, 0.6, 1.0, 1.6, 2.6, 4.2, 6.8, 10.0...
59    //
60    // Jitter adds a random value between 0 and `min_delay` to each delay.
61    // Total jitter is between 0 and (360 * 0.2) = 72.0.
62    //
63    // Maximum possible delay including jitter is 3599.6s seconds.
64    custom_backoff(
65        Duration::from_millis(200),
66        Duration::from_secs(10),
67        Some(360),
68    )
69}
70
71pub fn api_networking_backoff() -> FibonacciBackoff {
72    custom_backoff(Duration::from_millis(250), Duration::from_secs(10), None)
73}