Failure Handling: Beginner
One question, 3 answers
A permanent failure is one where the answer is no. The cause is in the request itself or in the code, and waiting changes nothing: the file you asked for does not exist, the API key expired last week, a record carries the string N/A where the schema expects an integer, a function raised KeyError on a column the source renamed. The second attempt fails for the same reason as the first, and so does the fiftieth.
| What the task sees | Typical cause | Category | First response |
|---|---|---|---|
| Connection reset by peer | A network hop dropped the socket | Transient | Retry after a pause |
| 503 Service Unavailable | The service is restarting or overloaded | Transient | Retry after a pause |
| 429 Too Many Requests | You exceeded the service's rate limit | Transient | Retry after the pause the service asks for |
| 401 Unauthorized | The credential is wrong or expired | Permanent | Stop, alert, rotate the credential |
| 404 Not Found | The resource or endpoint does not exist | Permanent | Stop and alert |
| ValueError parsing a row | The data does not match the expected shape | Permanent | Set the row aside, continue |
| Timeout after 30 s | Slow network, slow server, or a lost response | Ambiguous | Retry only if the step is idempotent |
| 500 Internal Server Error | The server raised an unhandled error | Ambiguous | Retry a few times, then stop |
The response follows the category
- ▸Transient: retry a limited number of times, with a pause between attempts
- ▸Permanent: stop immediately, keep the error, alert a person
- ▸Ambiguous and the step is idempotent: treat it as transient
- ▸Ambiguous and the step is not idempotent: treat it as permanent until verified
requests.Timeout class or a 503 status is stable and can be matched in code.A nightly task that loads a partner's daily order file raised a different error on each of 4 nights. Which of these should the task stop on at once, rather than retry?
The loop that looks fine
This 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
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.
MAX_ATTEMPTS = 5 means the step runs at most 5 times. A budget described as '5 retries' means 6 runs, and the off-by-1 argument it starts costs more than the extra attempt.| 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 |
- 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
- 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?
How a herd keeps a service down
Backoff spaces the waves, jitter spreads each one
A team adds exponential backoff (1 s, 2 s, 4 s, 8 s) to 500 workers but no jitter. The API they call handles 200 calls per second and goes down for 300 milliseconds. What happens on the first retry wave?
Exponential backoff is a formula, and you should be able to run it in your head before you trust a library to run it for you. After the n-th consecutive failure, the wait before the next attempt is wait = min(cap, base * 2 ** (n - 1)). base is the wait after the first failure. The exponent doubles it with each further failure. cap is the ceiling the wait can never exceed. With the animation's settings, base is 1 second and cap is 60 seconds.
Libraries differ on whether the first failure is numbered 0 or 1. Check which before comparing numbers; the shape of the curve is the same either way.
| Failure number | base * 2^(n-1) | After the 60 s cap | Cumulative sleep |
|---|---|---|---|
| 1 | 1 s | 1 s | 1 s |
| 2 | 2 s | 2 s | 3 s |
| 3 | 4 s | 4 s | 7 s |
| 4 | 8 s | 8 s | 15 s |
| 5 | 16 s | 16 s | 31 s |
| 6 | 32 s | 32 s | 63 s |
| 7 | 64 s | 60 s | 123 s |
| 8 | 128 s | 60 s | No sleep: attempt 8 was the last of the budget |
The cap keeps the wait finite
Jitter: a random point inside the window
Full jitter replaces the computed wait with a random draw between 0 and that wait: sleep = random.uniform(0, min(cap, base * 2 ** (n - 1))). The capped value becomes the top of a window rather than the wait itself. After the third failure a worker no longer sleeps 4 seconds; it sleeps somewhere between 0 and 4 seconds, and the 100 workers in a wave each draw their own number. Here are 3 workers that failed at the same moment, across their first 4 failures.
| Failure | Window (0 to) | Worker A draws | Worker B draws | Worker C draws |
|---|---|---|---|---|
| 1 | 1 s | 0.8 s | 0.2 s | 0.5 s |
| 2 | 2 s | 1.7 s | 0.4 s | 1.1 s |
| 3 | 4 s | 0.3 s | 3.6 s | 2.2 s |
| 4 | 8 s | 6.9 s | 1.5 s | 4.8 s |
This function is the whole policy. Call it with the number of consecutive failures so far, sleep for what it returns, and stop calling it once the attempt budget is spent. The retry loop from the previous section needs 1 change: replace the constant WAIT_SECONDS with backoff_seconds(attempt).
A retry policy uses base 0.5 s, cap 30 s and full jitter. A worker has failed for the 6th consecutive time. Which statement about its next sleep is right?
| Category | Example | Why a retry cannot help | Route to |
|---|---|---|---|
| Bad record | A row with `shipped_at = 'yesterday'` in a timestamp column | The row is the same on every attempt | Quarantine storage, then continue |
| Rejected credential | 401 after the partner rotated the API key | The key stays wrong until a person replaces it | Stop, alert, rotate the credential |
| Code bug | `TypeError` because a function received a list instead of a dict | The code is the same on every attempt | Fail the task, alert the owner |
| Missing resource | 404 for an endpoint removed in the partner's v3 API | The endpoint will not come back | Fail the task, alert the owner |
| Rate limit | 429 with a `Retry-After: 120` header | It will help, after the pause the service names | Retry after exactly that pause |
Bad records go to quarantine
A nightly file holds 2 million orders, and 12 of them have a text string in the amount column. Failing the whole task over 12 rows blocks 1,999,988 good rows from reaching the warehouse, and retrying the task re-reads the same 12 bad rows. Instead, catch the parse error per row, write the bad row to a quarantine table alongside the error message, the source file name and the time, and keep going. Good rows load as usual. The quarantine table is a storage location with a schema, so it can be queried, and the task raises an alert when the quarantine count crosses a threshold, say 100 rows.
Rows that parse take the top path into orders. Rows that fail to parse take the bottom path, and an alert fires when the quarantine count crosses its threshold.
The except here catches ValueError and nothing wider. A KeyError from a renamed column is a bug in the mapping rather than a bad row, and it should stop the task so the mapping gets fixed, instead of quarantining 2 million rows one at a time. The error field in each quarantine row is what lets someone fix the source or the parser tomorrow.
Rejected credentials go to a person
Bugs fail fast
A TypeError, KeyError, AttributeError or ZeroDivisionError from the pipeline's own code is the same on the hundredth attempt as on the first. The right response is the one Python gives by default: let it propagate, let the task fail, let the orchestrator alert the owner with the traceback. The bounded loop from earlier does this already, because is_transient returns False for anything outside its list. A loop that catches Exception turns a 1 line bug into a task that sleeps for 2 minutes before reporting the same traceback it had at second 0.
A task that pulls invoices from a partner API starts receiving 403 Forbidden on every call at 02:00. Its retry loop uses backoff with a 60 s cap and 8 attempts. What should the task do differently?
> A marketplace's nightly settlement DAG has 250 workers, each pulling one seller's payout file from a bank API that serves 100 calls per second. At 01:40 the bank deploys and returns 503 for 20 seconds. At 01:45 a new seller's file arrives with 30 rows whose payout_date reads TBD. At 02:10 the bank rotates the API key without warning and every call returns 401.
TBD rows are permanent failures at the row level: the parser quarantines them with the error and file name, loads the seller's other rows, and the alert stays quiet because 30 is under the threshold.is_transient returns False, the task fails on the first one instead of sleeping through 8 attempts, and the alert names the credential so the owner rotates it and reruns.Sort every failure into transient, permanent or ambiguous, then retry, back off, or stop, and know which one before it happens.
- Category
- Pipeline Architecture
- Difficulty
- beginner
- Duration
- 25 minutes
- Challenges
- 10 hands-on challenges
Topics covered: Transient vs Permanent Failures, The Retry: Easy to Misuse, Naive Retries and Thundering Herd, Computing Exponential Backoff, When NOT to Retry
Lesson Sections
- Transient vs Permanent Failures (concepts: Retry & Failure Handling)
A task fails when a call it makes returns an error or never returns at all. The error says what happened; it does not say what to do next. That decision comes down to one question: if the task ran the same step again in 10 seconds, would it succeed? Each of the 3 possible answers calls for a different response. One question, 3 answers A transient failure is one where the answer is yes. The cause sits outside your code and passes on its own: a network connection dropped halfway through a request,
- The Retry: Easy to Misuse (concepts: 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 The bounded version The table shows the worst case: every attempt times out. The loop spends 50 seconds inside cal
- Naive Retries and Thundering Herd (concepts: Retry & Failure Handling)
The bounded loop is correct for 1 worker, and pipelines rarely have 1. Picture 100 workers running it, with the wait set to 1 second and a budget of 8 attempts, pulling settlement pages from a payments API that serves 40 calls per second. At the 30 second mark the API restarts and answers nothing for 200 milliseconds. Every call in flight fails, every worker sleeps the same 1 second, and all 100 retries arrive at the same instant. The API is healthy again, but 100 calls land in a window built fo
- Computing Exponential Backoff (concepts: Retry & Failure Handling)
Libraries differ on whether the first failure is numbered 0 or 1. Check which before comparing numbers; the shape of the curve is the same either way. Doubling beats adding a second each time because a linear ramp of 1, 2, 3, 4 seconds grows too slowly to matter: after 10 failures a worker is still calling every 10 seconds, and 100 such workers still send 10 calls per second into a service that may need a minute of quiet. Doubling reaches a full minute between calls by the seventh failure. The c
- When NOT to Retry (concepts: Retry & Failure Handling)
A retry is the wrong tool for records that can't be processed, credentials that are rejected, and bugs in the pipeline's own code, which together account for nearly all the cases where retrying hurts. A retry on any of them produces the same error again, only later, with the alert delayed by the full length of the backoff schedule. Each category has its own destination. Bad records go to quarantine Rejected credentials go to a person A 401 or 403 means the service understood the request and refu