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.
14pub fn aggressive_backoff() -> FibonacciBackoff {
15    custom_backoff(Duration::from_millis(200), Duration::from_secs(5), Some(14))
16}
17
18pub fn aggressive_backoff_long() -> FibonacciBackoff {
19    custom_backoff(Duration::from_millis(200), Duration::from_secs(5), Some(25))
20}
21
22#[cfg(test)]
23pub fn immediate_backoff(max_retries_or: Option<usize>) -> FibonacciBackoff {
24    custom_backoff(Duration::ZERO, Duration::ZERO, max_retries_or)
25}
26
27pub fn custom_backoff(
28    min_delay: Duration,
29    max_delay: Duration,
30    max_retries_or: Option<usize>,
31) -> FibonacciBackoff {
32    FibonacciBuilder::default()
33        .with_jitter()
34        .with_min_delay(min_delay)
35        .with_max_delay(max_delay)
36        .with_max_times(max_retries_or.unwrap_or(usize::MAX))
37        .build()
38}
39
40/// Retry every max 10s for up to one hour, with a more aggressive fibonacci
41/// backoff in the beginning to reduce expected latency.
42///
43/// Starts at 200ms increasing to 10s. Retries 360 times before giving up, with
44/// a maximum total delay between 3527.6s (58m 47.6s) and 3599.6s (59m 59.6s)
45/// depending on jitter.
46pub fn fibonacci_max_one_hour() -> FibonacciBackoff {
47    // Not accounting for jitter, the delays are:
48    // 0.2, 0.2, 0.4, 0.6, 1.0, 1.6, 2.6, 4.2, 6.8, 10.0...
49    //
50    // Jitter adds a random value between 0 and `min_delay` to each delay.
51    // Total jitter is between 0 and (360 * 0.2) = 72.0.
52    //
53    // Maximum possible delay including jitter is 3599.6s seconds.
54    custom_backoff(
55        Duration::from_millis(200),
56        Duration::from_secs(10),
57        Some(360),
58    )
59}
60
61pub fn api_networking_backoff() -> FibonacciBackoff {
62    custom_backoff(Duration::from_millis(250), Duration::from_secs(10), None)
63}