Calculate the delay for a given attempt number (0-indexed) Uses exponential backoff: `base_delay * 2^attempt`, capped at `max_delay`. Adds jitter of ±25% to avoid thundering herd.
(&self, attempt: u32)
| 67 | /// Uses exponential backoff: `base_delay * 2^attempt`, capped at `max_delay`. |
| 68 | /// Adds jitter of ±25% to avoid thundering herd. |
| 69 | pub fn delay_for_attempt(&self, attempt: u32) -> Duration { |
| 70 | let exp_delay = self.base_delay_ms.saturating_mul(1u64 << attempt.min(10)); |
| 71 | let capped = exp_delay.min(self.max_delay_ms); |
| 72 | |
| 73 | // Add jitter: ±25% |
| 74 | let jitter_range = capped / 4; |
| 75 | let jitter = if jitter_range > 0 { |
| 76 | // Use system time nanos + attempt as entropy for non-deterministic jitter, |
| 77 | // so different clients/attempts spread their retries to avoid thundering herd. |
| 78 | let entropy = std::time::SystemTime::now() |
| 79 | .duration_since(std::time::UNIX_EPOCH) |
| 80 | .map(|d| d.subsec_nanos() as u64) |
| 81 | .unwrap_or(0); |
| 82 | let jitter_offset = (entropy ^ (attempt as u64).wrapping_mul(0x517cc1b727220a95)) |
| 83 | % (jitter_range * 2 + 1); |
| 84 | capped - jitter_range + jitter_offset |
| 85 | } else { |
| 86 | capped |
| 87 | }; |
| 88 | |
| 89 | Duration::from_millis(jitter) |
| 90 | } |
| 91 | |
| 92 | /// Parse `Retry-After` header value to get a delay duration. |
| 93 | /// |