Skip to content
mentoor

Topic 3 of 5 · 5 min read

Retrying with exponential backoff and jitter

Goal: Configure retries that honour retry-after headers, add jitter and stop at a cap, without double-retrying on top of the SDK.

Retry temporary failures with exponential backoff and jitter, honour the retry-after header when it is present, stop at a fixed cap, and never stack your own retries on top of the SDK's. Backoff means each wait is longer than the last. Jitter means each wait has a random part.

Check yourself · 1 of 3

What does adding jitter to a backoff schedule achieve?

Choose one answer

Why it matters

A provider under strain gets worse if every client hammers it at once. The Google SRE book describes retries as a main way an overload spreads. Backoff gives the service room, jitter keeps clients from retrying in step, and a cap keeps a hopeless call from running forever.

The recipe

  1. Retry only retryable errors: 429, 5xx and overload, and connection resets. Never 400, 401, 403, 404 or 413.
  2. Honour retry-after. If the response says wait 20 seconds, wait at least 20 seconds. The MDN page describes the header as seconds or an HTTP date.
  3. Otherwise use backoff: wait base times 2 to the power of the attempt, for example 1, 2, 4, 8 seconds.
  4. Add jitter. AWS's analysis shows plain backoff still makes clients collide in waves. "Full jitter" picks a random wait between 0 and the backoff value.
  5. Cap both the wait and the attempts, for example 30 seconds per wait and 5 attempts, then fail with a clear error.
  6. Retry only safe calls. A generation call can usually be repeated. A call that triggers an action, such as sending an email through a tool, needs an idempotency key or its own check.
import random, time

def call_with_retry(fn, max_attempts=5, base=1.0, cap=30.0):
    for attempt in range(max_attempts):
        try:
            return fn()
        except RetryableError as e:
            if attempt == max_attempts - 1:
                raise
            wait = e.retry_after or random.uniform(0, min(cap, base * 2 ** attempt))
            time.sleep(wait)

Do not retry twice

Official SDKs from Anthropic and OpenAI retry some errors by themselves, with a small default number of attempts. If you wrap the SDK call in your own loop of 5 and the SDK retries 2 more, one failure becomes up to 15 calls. Pick one layer: either set the SDK's max_retries to 0 and own the logic, or leave your code out and tune the SDK setting.

Before and after

Before: while True: try ... except: sleep(1). It retries 400s, never stops and all workers wake together. After: the function above, with the SDK's own retries switched off.

What goes wrong

  • Fixed one-second sleeps. Clients stay in step and keep hitting the limit together.
  • No cap. A job spins for hours on an error that will not clear.
  • Ignoring retry-after. You retry before the server said it would be ready.
  • Layered retries. The multiplication of attempts turns a brownout into a flood.

Examples

Multiplying retries

A service wraps client.messages.create in its own loop of 4 attempts. The SDK already retries 2 times per call. One failing request now makes up to 12 calls and each of them counts toward the rate limit. Setting max_retries=0 on the client leaves a single, visible retry policy.

Full jitter in numbers

Attempt 3 has a backoff ceiling of 8 seconds. Full jitter picks a random wait between 0 and 8 seconds. Two hundred workers that failed together now come back spread across that range instead of all at second 8.

Key points

  • Retry only temporary errors: 429, 5xx, overload and dropped connections.
  • When a response includes retry-after, wait at least that long before the next attempt.
  • Backoff grows the wait each attempt, and jitter randomises it so clients do not retry in lockstep.
  • Cap both the wait and the number of attempts, then fail with a clear error.
  • SDKs retry by default, so a hand-written loop around one multiplies the attempts unless one layer is switched off.

Common mistakes

  • Sleeping a fixed second between attempts, so every worker retries at the same moment.
  • Retrying forever with no cap on attempts or wait time.
  • Retrying calls with side effects without an idempotency check.
  • Wrapping an SDK call in a retry loop without checking the SDK's own retry setting.

Check yourself · 2 of 3

A 429 response includes retry-after: 20. The client's backoff schedule says wait 2 seconds. What should the client do?

Choose one answer

Check yourself · 3 of 3

Your code retries 4 times around an SDK call, and the SDK retries 2 times by default. What is the worst case for one failing request?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic