1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use rand::Rng;
use std::time::Duration;
/// Defines the retry strategy to use when scheduling retry attempts.
///
/// This enum specifies how delays between retries are calculated.
#[derive(Debug)]
pub enum RetryStrategy {
/// A linear retry strategy where the delay between retries remains constant.
///
/// For example, if the delay is set to 2 seconds, each retry will wait exactly 2 seconds.
Linear,
/// An exponential backoff strategy where the delay increases exponentially with each retry.
///
/// For example, with a base delay of 2 seconds, retries might wait 2s, 4s, 8s, etc.
ExponentialBackoff,
/// An exponential backoff with jitter strategy where the delay increases exponentially but includes
/// a random "jitter" factor to prevent synchronized retries in distributed systems.
///
/// The `jitter_factor` is a small fraction (typically 0.0 to 0.5) that defines the range of randomness
/// as a percentage of the base delay. For example, with a base delay of 2 seconds and a jitter factor
/// of 0.25 (25%), retries might wait:
/// - Retry 1: ~2s (e.g., 1.5s to 2.5s)
/// - Retry 2: ~4s (e.g., 3.0s to 5.0s)
/// - Retry 3: ~8s (e.g., 6.0s to 10.0s)
/// - And so on...
///
/// The jitter helps avoid the "thundering herd" problem where many clients retry simultaneously.
ExponentialBackoffWithJitter { jitter_factor: f64 },
/// A Fibonacci backoff strategy where the delay between retries follows the Fibonacci sequence.
///
/// In this strategy, each delay is the sum of the two preceding delays, typically starting with
/// a base unit (e.g., 1 second). For example, if the base delay is 1 second, the retry delays
/// would be 1s, 1s, 2s, 3s, 5s, 8s, 13s, etc. This provides a gentler increase compared to
/// exponential backoff, balancing retry frequency and resource usage.
///
/// ### Example
/// - Retry 1: 1 second
/// - Retry 2: 1 second
/// - Retry 3: 2 seconds
/// - Retry 4: 3 seconds
/// - Retry 5: 5 seconds
/// - And so on...
FibonacciBackoff,
/// An arithmetic progression strategy where the delay increases linearly based on a coefficient.
///
/// For example, with a coefficient of 3 and a base delay of 1s:
/// - Retry 1: 3s
/// - Retry 2: 6s
/// - Retry 3: 9s
/// - And so on...
ArithmeticProgression { coefficient: usize },
}
/// Configuration for retrying operations.
///
/// This struct defines the parameters for retrying an operation, including
/// the maximum number of attempts, the delay between retries, and the retry strategy.
impl RetryStrategy {
/// Calculates the delay duration for a specific retry attempt based on the retry strategy.
///
/// # Arguments
/// * `base_delay` - The base duration to use as the starting point for delay calculations.
/// * `attempt` - The current attempt number (1-based index for retries).
///
/// # Returns
/// A `Duration` representing the time to wait before the next retry attempt.
pub(crate) fn calculate_delay(&self, base_delay: Duration, attempt: usize) -> Duration {
match self {
RetryStrategy::Linear => base_delay,
RetryStrategy::ExponentialBackoff => {
if attempt == 0 {
base_delay
} else {
base_delay * 2u32.pow((attempt - 1) as u32)
}
}
RetryStrategy::FibonacciBackoff => {
if attempt < 2 {
base_delay
} else {
let mut prev = base_delay;
let mut curr = base_delay;
for _ in 2..=attempt {
let next = prev + curr;
prev = curr;
curr = next;
}
curr
}
}
RetryStrategy::ArithmeticProgression { coefficient } => {
base_delay * (*coefficient as u32 * attempt as u32)
}
RetryStrategy::ExponentialBackoffWithJitter { jitter_factor } => {
let base_secs = base_delay.as_secs_f64();
let exp_delay = base_secs * 2f64.powi((attempt - 1) as i32);
let jitter_amount = base_secs * jitter_factor;
let jitter = rand::rng().random_range(-jitter_amount..=jitter_amount);
let final_delay = (exp_delay + jitter).max(0.0);
Duration::from_secs_f64(final_delay)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_linear_strategy() {
let base_delay = Duration::from_secs(2);
let linear = RetryStrategy::Linear;
// Test that Linear strategy returns a constant delay
assert_eq!(
linear.calculate_delay(base_delay, 0),
Duration::from_secs(2)
); // Initial attempt
assert_eq!(
linear.calculate_delay(base_delay, 1),
Duration::from_secs(2)
); // First retry
assert_eq!(
linear.calculate_delay(base_delay, 2),
Duration::from_secs(2)
); // Second retry
assert_eq!(
linear.calculate_delay(base_delay, 3),
Duration::from_secs(2)
); // Third retry
}
#[test]
fn test_exponential_backoff_strategy() {
let base_delay = Duration::from_secs(2);
let expo = RetryStrategy::ExponentialBackoff;
// Test that ExponentialBackoff increases delay exponentially
assert_eq!(expo.calculate_delay(base_delay, 0), Duration::from_secs(2));
assert_eq!(expo.calculate_delay(base_delay, 1), Duration::from_secs(2));
assert_eq!(expo.calculate_delay(base_delay, 2), Duration::from_secs(4));
assert_eq!(expo.calculate_delay(base_delay, 3), Duration::from_secs(8));
assert_eq!(expo.calculate_delay(base_delay, 4), Duration::from_secs(16));
}
#[test]
fn test_exponential_backoff_strategy_mill() {
let base_delay = Duration::from_millis(2000); // Start from 2000ms (2s)
let expo = RetryStrategy::ExponentialBackoff;
// Test that ExponentialBackoff increases delay exponentially (milliseconds)
assert_eq!(
expo.calculate_delay(base_delay, 0),
Duration::from_millis(2000)
); // Initial attempt
assert_eq!(
expo.calculate_delay(base_delay, 1),
Duration::from_millis(2000)
); // 2^0 * 2000ms
assert_eq!(
expo.calculate_delay(base_delay, 2),
Duration::from_millis(4000)
); // 2^1 * 2000ms
assert_eq!(
expo.calculate_delay(base_delay, 3),
Duration::from_millis(8000)
); // 2^2 * 2000ms
assert_eq!(
expo.calculate_delay(base_delay, 4),
Duration::from_millis(16000)
); // 2^3 * 2000ms
}
#[test]
fn test_fibonacci_backoff_strategy() {
let base_delay = Duration::from_secs(1);
let fib = RetryStrategy::FibonacciBackoff;
assert_eq!(fib.calculate_delay(base_delay, 0), Duration::from_secs(1));
assert_eq!(fib.calculate_delay(base_delay, 1), Duration::from_secs(1));
assert_eq!(fib.calculate_delay(base_delay, 2), Duration::from_secs(2));
assert_eq!(fib.calculate_delay(base_delay, 3), Duration::from_secs(3));
assert_eq!(fib.calculate_delay(base_delay, 4), Duration::from_secs(5));
assert_eq!(fib.calculate_delay(base_delay, 5), Duration::from_secs(8));
}
#[test]
fn test_fibonacci_backoff_strategy_millis() {
let base_delay = Duration::from_millis(2000); // 2000ms = 2s
let fib = RetryStrategy::FibonacciBackoff;
assert_eq!(
fib.calculate_delay(base_delay, 0),
Duration::from_millis(2000)
); // 1st: 2000ms
assert_eq!(
fib.calculate_delay(base_delay, 1),
Duration::from_millis(2000)
); // 2nd: 2000ms
assert_eq!(
fib.calculate_delay(base_delay, 2),
Duration::from_millis(4000)
); // 3rd: 4000ms
assert_eq!(
fib.calculate_delay(base_delay, 3),
Duration::from_millis(6000)
); // 4th: 6000ms
assert_eq!(
fib.calculate_delay(base_delay, 4),
Duration::from_millis(10000)
); // 5th: 10000ms
assert_eq!(
fib.calculate_delay(base_delay, 5),
Duration::from_millis(16000)
); // 6th: 16000ms
}
#[test]
fn test_arithmetic_progression_strategy() {
let base_delay = Duration::from_secs(2);
let ap = RetryStrategy::ArithmeticProgression { coefficient: 3 };
assert_eq!(ap.calculate_delay(base_delay, 1), Duration::from_secs(6));
assert_eq!(ap.calculate_delay(base_delay, 2), Duration::from_secs(12));
assert_eq!(ap.calculate_delay(base_delay, 3), Duration::from_secs(18));
}
#[test]
fn test_exponential_backoff_with_jitter_strategy() {
let base_delay = Duration::from_secs(2);
let jitter = RetryStrategy::ExponentialBackoffWithJitter {
jitter_factor: 0.25,
}; // 25% jitter
let attempt_1 = jitter.calculate_delay(base_delay, 1);
let attempt_2 = jitter.calculate_delay(base_delay, 2);
let attempt_3 = jitter.calculate_delay(base_delay, 3);
// Check ranges (jitter is ±25% of base delay, i.e., ±0.5s, applied to exponential delay)
assert!(
attempt_1 >= Duration::from_secs_f64(1.5) && attempt_1 <= Duration::from_secs_f64(2.5)
);
assert!(
attempt_2 >= Duration::from_secs_f64(3.5) && attempt_2 <= Duration::from_secs_f64(4.5)
);
assert!(
attempt_3 >= Duration::from_secs_f64(7.5) && attempt_3 <= Duration::from_secs_f64(8.5)
);
}
#[test]
fn test_exponential_backoff_with_small_jitter() {
let base_delay = Duration::from_secs(2);
let jitter = RetryStrategy::ExponentialBackoffWithJitter { jitter_factor: 0.1 }; // 10% jitter
let attempt_1 = jitter.calculate_delay(base_delay, 1);
let attempt_2 = jitter.calculate_delay(base_delay, 2);
let attempt_3 = jitter.calculate_delay(base_delay, 3);
// Check tighter ranges (jitter is ±10% of base delay, i.e., ±0.2s)
assert!(
attempt_1 >= Duration::from_secs_f64(1.8) && attempt_1 <= Duration::from_secs_f64(2.2)
);
assert!(
attempt_2 >= Duration::from_secs_f64(3.8) && attempt_2 <= Duration::from_secs_f64(4.2)
);
assert!(
attempt_3 >= Duration::from_secs_f64(7.8) && attempt_3 <= Duration::from_secs_f64(8.2)
);
}
}