Sub topic 5
Exponential Backoff
This chapter assumes you can read basic Python, know what HTTP status codes and headers are, and have called an LLM API before. It also assumes you can already tell retryable errors (408, 429, 5xx, network failures) from permanent ones (400, 401, 404).
Why wait longer each time
A temporary failure often needs time to clear. A server may be overloaded, or a rate-limit window may need to reset. If you retry at once, or at a fixed short interval, you add load to a service that is already struggling, and you probably fail again.
Exponential backoff doubles the wait after each failed attempt. The delay for attempt n is:
delay = base * 2 ** (n - 1)With base = 0.5 seconds, the delays are 0.5, 1, 2, 4, 8, and so on. Early retries are quick, which suits brief glitches. Later retries are slower, which gives a longer outage room to recover.
Capping the delay
The doubling never stops on its own. After ten attempts the delay would be about four minutes. Add a cap so a single wait never exceeds a value you choose:
delay = min(cap, base * 2 ** (n - 1))With cap = 30, the delays are 0.5, 1, 2, 4, 8, 16, 30, 30, and so on.
def backoff_delay(attempt: int, base: float = 0.5, cap: float = 30.0) -> float:
"""Return the exponential delay in seconds for a 1-based attempt number."""
return min(cap, base * 2 ** (attempt - 1))
for attempt in range(1, 9):
print(attempt, backoff_delay(attempt))Putting it in a loop
A loop applies the delay only to errors worth retrying. This sketch uses a generic function that raises an exception you mark as retryable:
import time
class RetryableError(Exception):
pass
def call_with_backoff(func, max_attempts=5, base=0.5, cap=30.0):
for attempt in range(1, max_attempts + 1):
try:
return func()
except RetryableError:
if attempt == max_attempts:
raise
time.sleep(min(cap, base * 2 ** (attempt - 1)))The last attempt re-raises the error instead of sleeping. Waiting after the final failure would only delay the error report.
Common errors
- Retrying permanent errors. A 400 or 401 will fail the same way every time. Backoff only helps when the failure is temporary.
- No cap. Without a cap, a long outage produces waits of minutes or hours.
- No attempt limit. Backoff slows retries but does not bound them. Pair it with a maximum attempt count.
- Sleeping after the last attempt. This wastes time before the caller sees the error.
- Blocking an async program. Inside
async defcode, useawait asyncio.sleep(...). Callingtime.sleep(...)freezes the whole event loop.
Choosing values
| Setting | Typical starting point | Effect |
|---|---|---|
| `base` | 0.5 to 1 second | Sets how soon the first retry happens |
| `cap` | 30 to 60 seconds | Limits the longest single wait |
| `max_attempts` | 3 to 6 | Limits total effort |
Choose these so the worst-case total wait fits your overall deadline. With base = 0.5, cap = 30, and five attempts, the waits add up to at most 0.5 + 1 + 2 + 4 = 7.5 seconds, plus the time each request takes.
Exercise
With base = 1, cap = 10, and max_attempts = 6, what delays does the loop sleep between attempts, and what is their total?
Show answer
Six attempts allow five sleeps, because the loop does not sleep after the last attempt. The uncapped delays are 1, 2, 4, 8, 16. The cap limits the last one to 10, so the delays are 1, 2, 4, 8, 10. The total is 25 seconds.
Exercise
Why is time.sleep a problem inside an async retry loop, and what should you use instead?
Show answer
time.sleep blocks the whole event loop, so every other task stops while one request waits. Use await asyncio.sleep(delay), which pauses only the current task.