Sub topic 5
Exponential Backoff
This chapter assumes you can write Python functions with exceptions, and that you know which HTTP statuses are temporary and which are permanent. The earlier chapters on error categories and retryable errors cover that classification. Here you decide how long to wait between attempts once you have chosen to retry.
Why wait at all
A retry sent immediately after a failure usually meets the same condition that caused the failure. A server that returned 503 is overloaded. A rate-limited key is still over its limit. An instant retry adds load to a service that is already struggling, and it burns one of your limited attempts for no gain.
Waiting gives the problem time to clear. The difficulty is that you don't know how long that takes. A brief network blip may clear in 100 milliseconds, while a provider incident may take minutes.
The idea
Exponential backoff increases the wait after each consecutive failure by a constant factor, usually 2. The first retry waits briefly, so quick recoveries cost little. If failures continue, the waits grow quickly, so a longer outage receives fewer requests.
The formula for the wait before retry number attempt (where the first failed call is attempt 1) is:
delay = min(cap, base * factor ** (attempt - 1))baseis the first delay, for example 0.5 seconds.factoris the growth rate per attempt, usually 2.capis the longest single wait you will allow, for example 30 seconds.attemptcounts failed attempts so far, starting at 1.
The cap matters. Without it, the seventh delay in a base-0.5 schedule is 32 seconds, and the tenth is 256 seconds. That is far longer than most users or request deadlines will tolerate.
A delay schedule
The function below computes the delay for a given attempt. Run it to see the schedule before you wire it into a loop.
def backoff_delay(attempt, base=0.5, factor=2.0, cap=30.0):
"""Return seconds to wait after the given failed attempt (1-based)."""
return min(cap, base * factor ** (attempt - 1))
for attempt in range(1, 9):
print(attempt, backoff_delay(attempt))With the defaults, the delays are:
| Failed attempt | Uncapped delay (s) | Delay used (s) |
|---|---|---|
| 1 | 0.5 | 0.5 |
| 2 | 1 | 1 |
| 3 | 2 | 2 |
| 4 | 4 | 4 |
| 5 | 8 | 8 |
| 6 | 16 | 16 |
| 7 | 32 | 30 |
| 8 | 64 | 30 |
From attempt 7 onward the schedule is flat at the cap. This is the shape you want: fast growth early, then a steady slow poll.
The control flow
The loop has one decision at each failure: whether another attempt is allowed. If it is, sleep and try again. The decision about whether the error is retryable comes first, and the attempt limit comes second.
A complete retry loop
This version retries a function that raises TemporaryError. It is deliberately independent of any HTTP library so you can run it as written. The sleep parameter lets you replace the real sleep with a stub, which keeps demos and tests fast.
import time
class TemporaryError(Exception):
"""Stands in for a timeout, a 429, or a 5xx response."""
def backoff_delay(attempt, base=0.5, factor=2.0, cap=30.0):
return min(cap, base * factor ** (attempt - 1))
def call_with_backoff(func, max_attempts=5, base=0.5, factor=2.0,
cap=30.0, sleep=time.sleep):
for attempt in range(1, max_attempts + 1):
try:
return func()
except TemporaryError as exc:
if attempt == max_attempts:
raise # no attempts left: surface the last error
delay = backoff_delay(attempt, base, factor, cap)
print(f"attempt {attempt} failed ({exc}); sleeping {delay:.1f}s")
sleep(delay)
calls = {"n": 0}
def flaky():
calls["n"] += 1
if calls["n"] < 4:
raise TemporaryError("503 Service Unavailable")
return "ok"
print(call_with_backoff(flaky, sleep=lambda s: None))The output shows three failures with delays of 0.5, 1.0, and 2.0 seconds, then ok on the fourth call. Because sleep is replaced by a no-op, the script finishes instantly.
Three details in the loop are easy to get wrong:
- Do not sleep after the last attempt. The
if attempt == max_attempts: raisecheck comes before the sleep. Otherwise the caller waits for a delay that leads nowhere. - Re-raise the original exception. A bare
raisekeeps the traceback and the real cause, which you need when diagnosing outages. - Keep the attempt number 1-based consistently. The formula uses
attempt - 1as the exponent. If you pass a 0-based counter, the first delay becomesbase * 0.5and every wait is half what you intended.
Choosing base, factor, and cap
There is no universal setting. These guidelines fit typical LLM API use:
- Base: 0.5 to 1 second. LLM calls already take seconds, so a sub-100-millisecond base gives no useful recovery time.
- Factor: 2. A factor of 3 or more reaches the cap in very few attempts, which makes the growth almost pointless.
- Cap: 10 to 60 seconds. For interactive requests, choose the lower end. For background batch jobs, a higher cap is acceptable.
Compare exponential growth with the alternatives:
| Strategy | Delays (base 1 s, 5 retries) | Weakness |
|---|---|---|
| No wait | 0, 0, 0, 0, 0 | Hammers a failing service |
| Fixed wait | 1, 1, 1, 1, 1 | Keeps the same pressure however long the outage lasts |
| Linear | 1, 2, 3, 4, 5 | Backs off too slowly for long outages |
| Exponential | 1, 2, 4, 8, 16 | Total wait grows fast, so the cap and attempt limit must bound it |
Worst-case time
Backoff makes a call slower in the failing case, so calculate the worst case before you ship it. With 5 attempts, base 0.5, factor 2, there are 4 sleeps: 0.5 + 1 + 2 + 4 = 7.5 seconds of waiting.
That is not the full cost. Each attempt can also run until its timeout. If each attempt has a 30-second timeout, the worst case is 5 × 30 + 7.5 = 157.5 seconds. A user will not wait that long. This is why an overall deadline, covered in the timeouts and retry-limits chapters, must sit above the loop.
Common errors
- Retrying permanent errors. Backoff only helps when waiting can change the outcome. A 400 or 401 fails identically on every attempt, with longer pauses in between.
- Stacked retry layers. If the SDK retries 2 times and your loop retries 5 times around it, one logical request can produce up to 3 × 5 = 15 HTTP calls. Check what the client library already does before adding your own loop.
- Float overflow with unbounded attempts.
2.0 ** 1100raisesOverflowErrorin Python. A boundedmax_attemptsavoids this. If you ever loop without a limit, compute the exponent with a ceiling, such asmin(attempt - 1, 30). - Blocking an event loop.
time.sleepinside async code freezes every other task. In async code, useawait asyncio.sleep(delay). - Ignoring what the server says. A fixed schedule can be shorter than the wait the provider asked for. The Retry-After chapter shows how to combine the two.
Remaining limitation
Pure exponential backoff is deterministic. If 500 clients fail at the same moment, say during a provider incident, they all wait 0.5 seconds and retry together, then all wait 1 second and retry together again. Each wave arrives as a spike. Backoff spreads load over time for a single client but does not spread it across clients. The next chapter fixes this with jitter.
Exercise
A client uses base = 1 second, factor = 3, cap = 20 seconds, and max_attempts = 5. List the sleep durations between attempts and the total time spent sleeping if all five attempts fail.
Show answer
Delays are min(20, 1 3 * (attempt - 1)) after failed attempts 1 to 4: 1, 3, 9, and min(20, 27) = 20 seconds. No sleep follows attempt 5, because attempts are used up and the error is raised. The total sleeping time is 1 + 3 + 9 + 20 = 33 seconds.
Exercise
Your SDK client is configured with max_retries=3, and you wrap its calls in your own loop that makes up to 4 attempts. What is the largest number of HTTP requests one logical call can send, and what should you change?
Show answer
Each of your 4 attempts can trigger the SDK's original call plus 3 retries, which is 4 requests. Four attempts therefore send up to 4 × 4 = 16 requests. Remove one layer, preferably by relying on the SDK's retry settings and deleting your loop, or set the SDK's max_retries to 0 and keep a single loop.