Retries with Backoff and Jitter
medium · fake clock
Simulate one request's retries. outcomes is a list of booleans supplied by a fake API (True means success). max_attempts >= 0, base >= 0, cap >= 0, and jitter is a list of nonnegative integer delays with at least max_attempts entries. Attempt 0 is at time 0. After failed attempt i, delay min(cap, base * 2**i) + jitter[i] before the next attempt. Stop on success, max_attempts, or exhausted outcomes; do not schedule a sleep after the final attempt. Return {'attempt_times': timestamps, 'success': boolean}. No network, randomness, or real sleeping.
Examples (JSON; null means Python None):
Input: {"outcomes": [false, false, true], "max_attempts": 3, "base": 2, "cap": 10, "jitter": [1, 0, 5]}
Output: {"attempt_times": [0, 3, 7], "success": true}
Input: {"outcomes": [false, false, false], "max_attempts": 2, "base": 5, "cap": 3, "jitter": [0, 2]}
Output: {"attempt_times": [0, 3], "success": false}
Starter code
def retry_backoff(outcomes: list[bool], max_attempts: int, base: int, cap: int, jitter: list[int]) -> dict:
"""Replay bounded retries against fake outcomes and supplied jitter."""
pass
Loading editor…
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler