import time, random def with_backoff(fn, attempts=5): for i in range(attempts): try: return fn() except Exception as e: status = getattr(e, 'status_code', None) if status not in (429, 500, 502, 503, 529) or i == attempts - 1: raise # full jitter: avoids a thundering herd on recovery time.sleep(random.uniform(0, 2 ** i))