The Retry: Easy to Misuse
Concepts covered: Retry & Failure Handling
A retry is a loop that runs a failed step again. Writing one takes 5 lines, which is why most retry bugs come from loops written in a hurry. Every retry loop makes 4 decisions, whether the author noticed making them: which errors trigger another attempt, how many attempts are allowed, how long to wait between them, and what happens when the attempts run out.
The loop that looks fine
while True:
try:
page = fetch_page(url)
break
except Exception:
passThis loop answers all 4 questions badly. except Exception retries every error, including the KeyError from a renamed column and the 401 from an expired key, both of which will fail identically forever. There's no pause, so a failing service receives a new request every few milliseconds from this one worker. There is no limit, so the task runs until someone kills it, and the orchestrator shows it as running rather than failed, which means no alert fires. And pass discards the exception, so when someone finally looks, there is no record of what went wrong.
The bounded version
import time
import requests
RETRYABLE_STATUS = {500, 502, 503, 504}
MAX_ATTEMPTS = 5
WAIT_SECONDS = 2
def is_transient(err):
if isinstance(err, (requests.ConnectionError, requests.Timeout)):
return True
if isinstance(err, requests.HTTPError):
return err.response.status_code in RETRYABLE_STATUS
return False
def fetch_with_retry(url):
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.RequestException as err:
if not is_transient(err) or attempt == MAX_ATTEMPTS:
raise
print(f"attempt {attempt} failed: {err}")
time.sleep(WAIT_SECONDS)is_transient encodes the first section's classification: connection errors, timeouts and the listed 5xx statuses are retried, nothing else. Status 429 is left out on purpose, because it needs the pause the service names in its Retry-After header, covered in the last section. MAX_ATTEMPTS is the budget: 5 attempts means 1 original call plus 4 retries. A permanent error or a spent budget hits the bare raise, which re-throws the original exception, so the task fails with the real traceback. Only a transient error with attempts left reaches time.sleep. The step is a read, so retrying a 500 or a timeout is safe. Around an appending write both are ambiguous, and the loop would drop 500 from RETRYABLE_STATUS and requests.Timeout from is_transient.
| Attempt | Starts at | Result | What the loop does |
|---|---|---|---|
| 1 | 0 s | Timeout after 10 s | Sleep 2 s |
| 2 | 12 s | Timeout after 10 s | Sleep 2 s |
| 3 | 24 s | Timeout after 10 s | Sleep 2 s |
| 4 | 36 s | Timeout after 10 s | Sleep 2 s |
| 5 | 48 s | Timeout after 10 s | Raise; the task fails at 58 s |
The table shows the worst case: every attempt times out. The loop spends 50 seconds inside calls and 8 seconds sleeping, and raises at 58 seconds. If the orchestrator kills the task at 30 seconds, attempt 3 is cut off, the real error is never raised, and the task is marked as a timeout. Each orchestrator retry starts a fresh loop at attempt 1, so with 3 orchestrator retries, 4 runs make 12 calls instead of 5, and none ends with the real traceback. The task timeout has to exceed the loop's worst case, which you compute rather than guess.
- Do
- Name the exact exception classes and status codes that count as transient
- Set a fixed attempt budget and re-raise the real error when it is spent
- Sleep between attempts, even in the smallest loop
- Log each failed attempt with its number and the error
- Avoid
- Catch Exception and retry whatever lands in it
- Retry inside while True with no exit
- Swallow the last error with pass or a silent None
- Set the task timeout shorter than the loop's worst case
This loop wraps a CSV parse. What happens when the file has a malformed row that parse_csv rejects with ValueError?
def load_rows(path):
for attempt in range(3):
try:
return parse_csv(path)
except Exception:
time.sleep(5)- It parses 3 times, sleeps 15 seconds in total, then returns None and the caller continues as if it loaded nothing
- It raises ValueError on the first attempt, because a parse error is outside the loop's retryable list
- It parses 3 times, sleeps 15 seconds in total, then raises the last ValueError up to the caller
- It loops until the file is fixed, because range(3) restarts each time the exception is caught
About this lesson
This section is part of the Failure Handling: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.