← Back to Python, page 4

python-0064 · Hard senior

Design a retrying HTTP client wrapper for calls to a flaky third-party API.

Retry only idempotent requests and transient failures (timeouts, connection errors, 429 and 5xx), with exponential backoff and jitter, a maximum number of attempts and an overall deadline. Respect Retry-After headers, use idempotency keys for POSTs, log each retry, and add a circuit breaker so a dead dependency does not consume all workers.

Full answer
python
import random

class Transient(Exception): pass

def call_with_retry(fn, attempts=4, base=0.001, sleep=lambda s: None):
    for attempt in range(attempts):
        try:
            return fn()
        except Transient as e:
            if attempt == attempts - 1:
                raise
            delay = random.uniform(0, base * 2 ** attempt)
            print(f"attempt {attempt + 1} failed ({e}); retrying after jittered backoff")
            sleep(delay)

calls = {"n": 0}
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise Transient("503")
    return "ok"
print(call_with_retry(flaky))

def bad_request():
    raise ValueError("400 bad request")
try:
    call_with_retry(bad_request)
except ValueError as e:
    print("not retried:", e)

Output:

text
attempt 1 failed (503); retrying after jittered backoff
attempt 2 failed (503); retrying after jittered backoff
ok
not retried: 400 bad request

The sketch retries a fake call that fails twice with a transient error and then succeeds; delays follow exponential backoff with full jitter, scaled down so the run is fast. A non-retryable error (a 400-style ValueError) fails immediately without retries.

Design points for production:

  • Classify errors: network errors, timeouts, HTTP 429, 502, 503 and 504 are retryable; 400, 401, 403 and 404 are not.
  • Backoff: delay = random.uniform(0, base * 2**attempt) (full jitter) prevents synchronised retry storms.
  • Limits: cap attempts and total time, and pass a timeout to every request.
  • Idempotency: retry POSTs only with an idempotency key the server honours.
  • Circuit breaker: after many consecutive failures, fail fast for a cool-down period.
  • Observability: count retries and failures per endpoint.

Libraries such as tenacity, or the retry options in urllib3 and httpx transports, implement much of this.

python
import random

class Transient(Exception): pass

def call_with_retry(fn, attempts=4, base=0.001, sleep=lambda s: None):
    for attempt in range(attempts):
        try:
            return fn()
        except Transient as e:
            if attempt == attempts - 1:
                raise
            delay = random.uniform(0, base * 2 ** attempt)
            print(f"attempt {attempt + 1} failed ({e}); retrying after jittered backoff")
            sleep(delay)

calls = {"n": 0}
def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise Transient("503")
    return "ok"
print(call_with_retry(flaky))

def bad_request():
    raise ValueError("400 bad request")
try:
    call_with_retry(bad_request)
except ValueError as e:
    print("not retried:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Retry only transient errors
  • Exponential backoff with jitter
  • Cap attempts and total time
  • Idempotency keys for non-idempotent calls
  • Circuit breakers stop cascades

Common mistakes

  • Retrying every error, including 4xx
  • Retrying without jitter or limits

Follow-ups

  • How does a circuit breaker decide to close again?
  • How would you test retry logic?

Tips

  • Name the retryable status codes