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
273
274
275
use crate::{RetryDecision, RetryPolicy};
use chrono::Utc;
use rand::distributions::uniform::{UniformFloat, UniformSampler};
use std::{cmp, time::Duration};
const MIN_JITTER: f64 = 0.0;
const MAX_JITTER: f64 = 3.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExponentialBackoff {
pub max_n_retries: u32,
pub min_retry_interval: Duration,
pub max_retry_interval: Duration,
pub backoff_exponent: u32,
}
impl ExponentialBackoff {
pub fn builder() -> ExponentialBackoffBuilder {
<_>::default()
}
}
impl RetryPolicy for ExponentialBackoff {
fn should_retry(&self, n_past_retries: u32) -> RetryDecision {
if n_past_retries >= self.max_n_retries {
RetryDecision::DoNotRetry
} else {
let unjittered_wait_for = self.min_retry_interval
* self
.backoff_exponent
.checked_pow(n_past_retries)
.unwrap_or(u32::MAX);
let jitter_factor =
UniformFloat::<f64>::sample_single(MIN_JITTER, MAX_JITTER, &mut rand::thread_rng());
let jittered_wait_for = unjittered_wait_for.mul_f64(jitter_factor);
let execute_after =
Utc::now() + clip_and_convert(jittered_wait_for, self.max_retry_interval);
RetryDecision::Retry { execute_after }
}
}
}
fn clip_and_convert(duration: Duration, max_duration: Duration) -> chrono::Duration {
chrono::Duration::from_std(cmp::min(duration, max_duration)).unwrap()
}
pub struct ExponentialBackoffBuilder {
min_retry_interval: Duration,
max_retry_interval: Duration,
backoff_exponent: u32,
}
impl Default for ExponentialBackoffBuilder {
fn default() -> Self {
Self {
min_retry_interval: Duration::from_secs(1),
max_retry_interval: Duration::from_secs(30 * 60),
backoff_exponent: 3,
}
}
}
impl ExponentialBackoffBuilder {
pub fn retry_bounds(
mut self,
min_retry_interval: Duration,
max_retry_interval: Duration,
) -> Self {
assert!(
min_retry_interval <= max_retry_interval,
"The maximum interval between retries should be greater or equal than the minimum retry interval."
);
self.min_retry_interval = min_retry_interval;
self.max_retry_interval = max_retry_interval;
self
}
pub fn backoff_exponent(mut self, exponent: u32) -> Self {
self.backoff_exponent = exponent;
self
}
pub fn build_with_max_retries(self, n: u32) -> ExponentialBackoff {
ExponentialBackoff {
min_retry_interval: self.min_retry_interval,
max_retry_interval: self.max_retry_interval,
backoff_exponent: self.backoff_exponent,
max_n_retries: n,
}
}
pub fn build_with_total_retry_duration(self, total_duration: Duration) -> ExponentialBackoff {
let mut out = self.build_with_max_retries(0);
const MEAN_JITTER: f64 = (MIN_JITTER + MAX_JITTER) / 2.0;
let delays = (0u32..).into_iter().map(|n| {
let min_interval = out.min_retry_interval;
let backoff_factor = out.backoff_exponent.checked_pow(n).unwrap_or(u32::MAX);
let n_delay = (min_interval * backoff_factor).mul_f64(MEAN_JITTER);
cmp::min(n_delay, out.max_retry_interval)
});
let mut approx_total = Duration::from_secs(0);
for (n, delay) in delays.enumerate() {
approx_total += delay;
if approx_total >= total_duration {
out.max_n_retries = (n + 1) as _;
break;
} else if delay == out.max_retry_interval {
let remaining_s = (total_duration - approx_total).as_secs_f64();
let additional_tries = (remaining_s / delay.as_secs_f64()).ceil() as usize;
out.max_n_retries = (n + 1 + additional_tries) as _;
break;
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use fake::Fake;
fn get_retry_policy() -> ExponentialBackoff {
ExponentialBackoff {
max_n_retries: 6,
min_retry_interval: Duration::from_secs(1),
max_retry_interval: Duration::from_secs(5 * 60),
backoff_exponent: 3,
}
}
#[test]
fn if_n_past_retries_is_below_maximum_it_decides_to_retry() {
let policy = get_retry_policy();
let n_past_retries = (0..policy.max_n_retries).fake();
assert!(n_past_retries < policy.max_n_retries);
let decision = policy.should_retry(n_past_retries);
matches!(decision, RetryDecision::Retry { .. });
}
#[test]
fn if_n_past_retries_is_above_maximum_it_decides_to_mark_as_failed() {
let policy = get_retry_policy();
let n_past_retries = (policy.max_n_retries..).fake();
assert!(n_past_retries >= policy.max_n_retries);
let decision = policy.should_retry(n_past_retries);
matches!(decision, RetryDecision::DoNotRetry);
}
#[test]
fn maximum_retry_interval_is_never_exceeded() {
let policy = get_retry_policy();
let max_interval = chrono::Duration::from_std(policy.max_retry_interval).unwrap();
let decision = policy.should_retry(policy.max_n_retries - 1);
match decision {
RetryDecision::Retry { execute_after } => {
assert!((execute_after - Utc::now()) <= max_interval)
}
RetryDecision::DoNotRetry => panic!("Expected Retry decision."),
}
}
#[test]
fn overflow_backoff_exponent_does_not_cause_a_panic() {
let policy = ExponentialBackoff {
max_n_retries: u32::MAX,
backoff_exponent: 2,
..get_retry_policy()
};
let max_interval = chrono::Duration::from_std(policy.max_retry_interval).unwrap();
let n_failed_attempts = u32::MAX - 1;
let decision = policy.should_retry(n_failed_attempts);
match decision {
RetryDecision::Retry { execute_after } => {
assert!((execute_after - Utc::now()) <= max_interval)
}
RetryDecision::DoNotRetry => panic!("Expected Retry decision."),
}
}
#[test]
#[should_panic]
fn builder_invalid_retry_bounds() {
ExponentialBackoff::builder().retry_bounds(Duration::from_secs(3), Duration::from_secs(2));
}
}