Retry with Backoff Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Retry with Backoff runs in O(attempts) time and O(1) space, in Python as in every other language.
- ✓There is no retry helper in the standard library, but urllib3.util.Retry is available through requests via an HTTPAdapter and covers HTTP well, including respect for the Retry-After header.
- ✓Use tenacity with wait_exponential_jitter and an explicit retry_if_exception_type allowlist so only transient errors are retried; retrying every exception means a permanent bug retries three times before failing, tripling the damage and the latency.
- ✓The Python trap: urllib3 Retry does NOT retry POST by default, because allowed_methods contains only the idempotent verbs, which is correct and surprises people who assume their configuration is working.
- ✓The overhead of the retry machinery is irrelevant; the number that matters is worst-case total latency, which is the sum of every sleep plus every attempt timeout, and it must fit inside the caller deadline or you have simply moved the timeout.
What Retry with Backoff actually is
Retry with Backoff in Python: what you actually reach for
Python implementation
import random
import requests
from tenacity import (
retry, stop_after_attempt, stop_after_delay,
wait_exponential_jitter, retry_if_exception_type,
)
@retry(
# Cap ATTEMPTS and total TIME: either alone is insufficient.
stop=(stop_after_attempt(5) | stop_after_delay(20)),
wait=wait_exponential_jitter(initial=0.2, max=10, jitter=2),
# Allowlist: retrying a permanent bug just triples the damage.
retry=retry_if_exception_type((requests.ConnectionError, requests.Timeout)),
reraise=True,
)
def fetch(url: str) -> requests.Response:
r = requests.get(url, timeout=3) # per-attempt timeout is MANDATORY
if r.status_code in (429, 500, 502, 503, 504):
r.raise_for_status()
return r
# Full jitter by hand, the AWS-recommended form:
def full_jitter_delay(attempt: int, base: float = 0.2, cap: float = 10.0) -> float:
return random.uniform(0, min(cap, base * (2 ** attempt)))
# urllib3's Retry does NOT retry POST by default (allowed_methods is
# idempotent-only). That default is correct, do not widen it without
# an idempotency key.Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(attempts)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Retry with Backoff?
There is no retry helper in the standard library, but urllib3.util.Retry is available through requests via an HTTPAdapter and covers HTTP well, including respect for the Retry-After header. tenacity is the general-purpose library: the @retry decorator composes stop_after_attempt, wait_exponential_jitter and retry_if_exception_type. random.uniform plus time.sleep is all a hand-rolled version needs.
What is the most common Python mistake when implementing Retry with Backoff?
urllib3 Retry does NOT retry POST by default, because allowed_methods contains only the idempotent verbs, which is correct and surprises people who assume their configuration is working. Overriding it to include POST without an idempotency key is how duplicate charges happen. The backoff_factor arithmetic also surprises: the sleep is backoff_factor multiplied by two raised to the power of the retry number minus one, so the default factor of 0 means NO delay at all between retries, which is a retry storm generator rather than a backoff.
How does Retry with Backoff actually perform in Python?
The overhead of the retry machinery is irrelevant; the number that matters is worst-case total latency, which is the sum of every sleep plus every attempt timeout, and it must fit inside the caller deadline or you have simply moved the timeout. With full jitter the expected total is roughly half the un-jittered sum. Always cap the per-attempt timeout, since retrying a call that hangs for thirty seconds cannot help. Time complexity is O(attempts) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.