Skip to main content

base/interface/
backoff.rs

1//! `BackoffPolicy` — whether a failed request is tried again, and how long the
2//! caller waits first.
3//!
4//! Every wire protocol the engine speaks needs this decision, and answers kept
5//! per client drift apart — most damagingly on jitter: without it, every
6//! client that hits the same rate limit retries in lockstep.
7//!
8//! # What is protocol-specific and what is not
9//!
10//! Reading a `retry-after` header is protocol work: the header exists on one
11//! side and not the other, and its spelling is part of the wire format. So
12//! parsing stays in the client. What the number *means* — whether to honour
13//! it, whether the attempt budget is spent, how long to actually sleep — is
14//! not protocol work, and that is what moves here. A client's whole
15//! contribution is to describe the failure it just had, in the four kinds
16//! below, plus whatever the provider itself asked for.
17//!
18//! # The attempt budget is the policy's, not the caller's
19//!
20//! Bounding a retry loop by comparing an attempt counter against the ladder's
21//! length would put "how many times" in the caller and "how long" in the
22//! table. They are one decision. The policy is asked after every
23//! failure and answers [`Backoff::GiveUp`] when it is done, so a deployment
24//! that wants four retries, or none, changes one thing rather than two.
25
26use std::time::Duration;
27
28/// Why an attempt failed, reduced to what a backoff decision can act on.
29#[non_exhaustive]
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum RequestFailure {
32    /// The provider said "too many requests".
33    RateLimited,
34    /// The provider said it is busy and to come back.
35    Overloaded,
36    /// Nothing usable came back: connection reset, DNS, TLS.
37    Transport,
38    /// Anything else — a rejected key, a malformed request, a stream that died
39    /// after the provider had already started billing it.
40    Other,
41}
42
43/// One failed attempt, as the policy sees it.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct FailedAttempt {
46    /// How many attempts already failed before this one. The first failure is
47    /// `0`, which is also the index into a ladder of delays.
48    pub index: u32,
49    pub failure: RequestFailure,
50    /// What the provider asked for, when it said: the `retry-after` both
51    /// clients parse. Many providers never send one, and a policy that only
52    /// ever sees `None` still works.
53    pub server_hint: Option<Duration>,
54}
55
56/// What the caller should do about it.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Backoff {
59    /// Stop. The failure reaches the caller as it stands.
60    GiveUp,
61    /// Sleep this long, then send the same request again.
62    WaitThenRetry(Duration),
63}
64
65/// Whether a failed request is tried again, and after how long.
66pub trait BackoffPolicy: Send + Sync {
67    fn after_failure(&self, attempt: &FailedAttempt) -> Backoff;
68}
69
70/// The engine's own answer: a ladder of delays, jittered, deferring to the
71/// provider when it names a delay itself.
72pub struct LadderBackoff {
73    /// One delay per retry, in milliseconds. Its length is the retry budget.
74    pub steps: Vec<u64>,
75    /// How far either side of a step the actual delay may land, as a fraction.
76    pub jitter_ratio: f32,
77}
78
79impl LadderBackoff {
80    /// Six steps covering roughly a minute — what both clients shipped with.
81    pub const DEFAULT_STEPS: &'static [u64] = &[1_000, 2_000, 4_000, 8_000, 16_000, 32_000];
82    pub const DEFAULT_JITTER: f32 = 0.25;
83    /// A provider asking for longer than this is not going to be waited for.
84    pub const MAX_SERVER_HINT: Duration = Duration::from_secs(60);
85
86    pub fn new() -> Self {
87        Self::from_millis(Self::DEFAULT_STEPS.to_vec())
88    }
89
90    /// A ladder of the caller's own. Tests use it to collapse a minute of
91    /// waiting into a few milliseconds.
92    pub fn from_millis(steps: Vec<u64>) -> Self {
93        Self {
94            steps,
95            jitter_ratio: Self::DEFAULT_JITTER,
96        }
97    }
98}
99
100impl Default for LadderBackoff {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106impl BackoffPolicy for LadderBackoff {
107    fn after_failure(&self, attempt: &FailedAttempt) -> Backoff {
108        if attempt.failure == RequestFailure::Other {
109            return Backoff::GiveUp;
110        }
111        let Some(step) = self.steps.get(attempt.index as usize) else {
112            return Backoff::GiveUp;
113        };
114        // A provider that names its own delay knows something the ladder does
115        // not, but it does not get to extend the budget — the step it replaces
116        // is still spent.
117        match attempt.server_hint {
118            Some(hint) if hint > Self::MAX_SERVER_HINT => Backoff::GiveUp,
119            Some(hint) => Backoff::WaitThenRetry(after_hint(hint)),
120            None => Backoff::WaitThenRetry(jittered(*step, self.jitter_ratio)),
121        }
122    }
123}
124
125/// Spread a delay by `±ratio` so that clients which failed together do not
126/// return together.
127///
128/// The randomness is the sub-second part of the wall clock rather than a real
129/// generator: this is jitter, not a nonce, and the alternative is a `rand`
130/// dependency in the crate at the bottom of the graph.
131fn jittered(base_ms: u64, ratio: f32) -> Duration {
132    let unit = unit_noise();
133    let signed = (unit - 0.5) * 2.0;
134    let delta_ms = (base_ms as f32 * ratio * signed) as i64;
135    let base = i64::try_from(base_ms).unwrap_or(i64::MAX);
136    let final_ms = base.saturating_add(delta_ms).max(0) as u64;
137    Duration::from_millis(final_ms)
138}
139
140/// The server's hint is a floor: retrying earlier is another rejection, so the
141/// spread only goes upward, by up to a tenth of the hint.
142fn after_hint(hint: Duration) -> Duration {
143    hint + hint.mul_f32(0.1 * unit_noise())
144}
145
146fn unit_noise() -> f32 {
147    use std::time::SystemTime;
148    let nanos = SystemTime::now()
149        .duration_since(SystemTime::UNIX_EPOCH)
150        .map(|d| d.subsec_nanos())
151        .unwrap_or(0);
152    (nanos % 1_000_000) as f32 / 1_000_000.0
153}
154
155/// Never retries anything.
156///
157/// The second implementation, and a configuration a host really runs: put a
158/// retrying LLM gateway in front of the engine and the engine's own ladder
159/// stops being resilience and starts being a minute of invisible latency on
160/// top of the gateway's. An interactive deployment that would rather show the
161/// error than sit silently for a minute wants the same thing.
162pub struct NoBackoff;
163
164impl BackoffPolicy for NoBackoff {
165    fn after_failure(&self, _attempt: &FailedAttempt) -> Backoff {
166        Backoff::GiveUp
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    fn at(index: u32, failure: RequestFailure) -> FailedAttempt {
175        FailedAttempt {
176            index,
177            failure,
178            server_hint: None,
179        }
180    }
181
182    fn wait_ms(b: Backoff) -> u64 {
183        match b {
184            Backoff::WaitThenRetry(d) => d.as_millis() as u64,
185            Backoff::GiveUp => panic!("expected a retry, got GiveUp"),
186        }
187    }
188
189    #[test]
190    fn a_server_hint_beyond_the_cap_gives_up_instead_of_wrapping() {
191        let p = LadderBackoff::new();
192        for secs in [61, 3_600, u64::MAX] {
193            let attempt = FailedAttempt {
194                index: 0,
195                failure: RequestFailure::RateLimited,
196                server_hint: Some(Duration::from_secs(secs)),
197            };
198            assert_eq!(p.after_failure(&attempt), Backoff::GiveUp, "{secs}s");
199        }
200        let at_cap = FailedAttempt {
201            index: 0,
202            failure: RequestFailure::RateLimited,
203            server_hint: Some(LadderBackoff::MAX_SERVER_HINT),
204        };
205        assert!(wait_ms(p.after_failure(&at_cap)) >= 45_000);
206    }
207
208    #[test]
209    fn jitter_of_a_huge_base_saturates() {
210        assert!(jittered(u64::MAX, 0.25) >= Duration::from_millis(i64::MAX as u64 / 2));
211    }
212
213    /// The ladder is six numbers a reader has no way to check against intent,
214    /// and the sixth-to-seventh boundary is where retrying stops. Both are
215    /// pinned here because both clients depend on them being what they were.
216    #[test]
217    fn the_ladder_is_one_to_thirty_two_seconds_and_then_stops() {
218        let p = LadderBackoff::new();
219        let expected = [1_000u64, 2_000, 4_000, 8_000, 16_000, 32_000];
220        for (i, base) in expected.iter().enumerate() {
221            let ms = wait_ms(p.after_failure(&at(i as u32, RequestFailure::Overloaded)));
222            let slack = (*base as f64 * LadderBackoff::DEFAULT_JITTER as f64) as u64;
223            assert!(
224                ms >= base - slack && ms <= base + slack,
225                "step {i}: {ms}ms is not within ±25% of {base}ms"
226            );
227        }
228        assert_eq!(
229            p.after_failure(&at(6, RequestFailure::Overloaded)),
230            Backoff::GiveUp,
231            "six delays is six retries"
232        );
233    }
234
235    #[test]
236    fn a_failure_that_will_not_get_better_is_not_retried() {
237        assert_eq!(
238            LadderBackoff::new().after_failure(&at(0, RequestFailure::Other)),
239            Backoff::GiveUp
240        );
241    }
242
243    #[test]
244    fn rate_limits_overload_and_transport_failures_all_retry() {
245        let p = LadderBackoff::new();
246        for failure in [
247            RequestFailure::RateLimited,
248            RequestFailure::Overloaded,
249            RequestFailure::Transport,
250        ] {
251            assert!(
252                matches!(p.after_failure(&at(0, failure)), Backoff::WaitThenRetry(_)),
253                "{failure:?} should retry"
254            );
255        }
256    }
257
258    /// A provider that names a delay overrides the ladder for that step —
259    /// but does not buy an extra one, and its delay is a floor.
260    #[test]
261    fn a_server_hint_replaces_the_step_without_extending_the_budget() {
262        let p = LadderBackoff::new();
263        let hinted = |index| FailedAttempt {
264            index,
265            failure: RequestFailure::RateLimited,
266            server_hint: Some(Duration::from_secs(7)),
267        };
268        for _ in 0..200 {
269            let ms = wait_ms(p.after_failure(&hinted(0)));
270            assert!(
271                (7_000..=7_700).contains(&ms),
272                "{ms}ms is not the hinted 7s plus at most 10%"
273            );
274        }
275        assert_eq!(p.after_failure(&hinted(6)), Backoff::GiveUp);
276    }
277
278    /// Jitter has to actually spread, or it is a constant with extra steps.
279    #[test]
280    fn jitter_stays_inside_the_band_it_promises() {
281        for _ in 0..200 {
282            let ms = jittered(1_000, 0.25).as_millis() as u64;
283            assert!((750..=1_250).contains(&ms), "{ms}ms escaped the ±25% band");
284        }
285        assert_eq!(jittered(1_000, 0.0), Duration::from_millis(1_000));
286    }
287
288    #[test]
289    fn a_deployment_behind_its_own_gateway_can_refuse_to_wait_at_all() {
290        for failure in [
291            RequestFailure::RateLimited,
292            RequestFailure::Overloaded,
293            RequestFailure::Transport,
294            RequestFailure::Other,
295        ] {
296            assert_eq!(NoBackoff.after_failure(&at(0, failure)), Backoff::GiveUp);
297        }
298    }
299}