Sub topic 10
Handling failures with retries and backoff
This chapter assumes you know how queues and workers decouple producers from delivery, and that you can read short Python snippets. Providers such as push gateways, SMS carriers and email APIs fail often enough that every channel worker needs a retry policy.
Transient and permanent failures
Retrying helps only when the failure is temporary. Sort each failure into one of two groups before you decide what to do.
| Failure | Example | Action |
|---|---|---|
| Transient | Timeout, connection reset, HTTP 429, HTTP 5xx | Retry with backoff |
| Permanent | Invalid phone number, unregistered device token, HTTP 400 | Do not retry. Record it and stop |
Retrying a permanent failure wastes capacity and can get your account flagged by the provider. If the provider honors a Retry-After header on a 429, wait at least that long.
Exponential backoff with jitter
Backoff means waiting longer after each failed attempt. With exponential backoff the wait limit doubles each time: 0.5 s, 1 s, 2 s, 4 s, and so on, up to a cap.
Without randomness, every worker that failed at the same moment retries at the same moment. This can overload a provider that is trying to recover. Jitter adds randomness to spread the retries out. The "full jitter" version below picks a random delay between zero and the current limit.
import random
import time
class TransientError(Exception):
"""A failure worth retrying, such as a timeout or a 5xx from a provider."""
def send_with_retry(send, max_attempts=5, base=0.5, cap=30.0):
for attempt in range(1, max_attempts + 1):
try:
return send()
except TransientError:
if attempt == max_attempts:
raise
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
time.sleep(delay)The send argument is a function that makes one provider call. It raises TransientError for failures worth retrying. Any other exception passes straight through, so permanent errors are not retried.
Where retries fit in the pipeline
The code above sleeps inside the worker. That works for a few short retries. For longer waits it ties up a worker doing nothing. A common alternative is to put the message back on a delay queue with a visible-after time, so the worker moves on to other messages. After the final attempt, move the message to a dead-letter queue (a holding queue for messages that failed for good) so that someone can inspect it.
Common errors
- Retrying without limits. Always set a maximum number of attempts, and often a total time budget too. An SMS about a login code is useless after ten minutes.
- Retrying without idempotency. A timeout does not tell you whether the provider received the request. A retry can therefore send a duplicate. Use a deduplication key, covered in the next chapter, together with retries.
- No jitter. Plain exponential backoff still produces synchronized waves of retries.
- Retrying every error. Treat 4xx responses (except 429) as permanent.
Exercise
A worker sends an SMS and the provider returns HTTP 400 with the message "invalid phone number". Should the worker retry? What should it do instead?
Show answer
No. A 400 for an invalid number is a permanent failure, so retrying cannot succeed. The worker should record the failure for delivery tracking, stop processing the message, and may mark the user's phone number as invalid.
Exercise
Why does the code pick random.uniform(0, limit) rather than sleeping exactly limit seconds?
Show answer
If many workers fail together and all sleep the same time, they all retry together and can overload the recovering provider again. A random delay spreads the retries over time.