Sub topic 10
Handling failures with retries and backoff
This chapter assumes you know the pipeline from earlier chapters: producers publish events, queues hold them, and channel workers call third-party providers such as an email API or a push gateway. It also assumes you can read short Python snippets. Here you will see what to do when a provider call fails.
Why failures are normal
A notification worker depends on networks and on services you do not run. Timeouts, brief provider outages, and rate-limit responses happen every day. If a worker drops a notification on the first error, users miss password resets and shipping updates. If it retries without care, it can overload a provider that is trying to recover.
A good retry policy answers four questions:
- Is this failure worth retrying?
- How long should the worker wait before the next attempt?
- When should it stop?
- Where does the message go after it stops?
Classify the failure first
Retrying a failure that can never succeed wastes capacity and delays other messages. Sort every provider response into one of three groups.
| Response | Class | Action |
|---|---|---|
| Network timeout, connection reset, HTTP 500, 502, 503, 504 | Transient | Retry with backoff |
| HTTP 429 (too many requests) | Transient, with a hint | Retry, and wait at least the `Retry-After` value |
| HTTP 400, malformed payload | Permanent | Do not retry, record the failure |
| HTTP 401 or 403, bad credentials | Permanent for this message, but a configuration problem | Do not retry, alert the on-call engineer |
| Token unregistered or phone number invalid | Permanent for this recipient | Do not retry, clean up the address |
Your provider adapter should translate each provider's codes into your own error types. The rest of the worker then deals with only two kinds of error, transient and permanent. A permanent error on a device token also feeds the token-management work covered in the chapter on device tokens.
Exponential backoff with jitter
Exponential backoff doubles the wait after each failure. The first retry comes quickly, in case the problem was a blip, and later retries give the provider more room. A cap keeps the wait from growing without limit.
Backoff alone has a flaw. If 10,000 workers fail at the same moment, they all wait 0.5 seconds and then all retry at once. The provider sees the same spike again. Jitter adds randomness so the retries spread out. The version below uses full jitter, where each delay is a random value between zero and the current ceiling.
With base=0.5 and cap=30, the ceiling after the k-th failure is min(30, 0.5 * 2^(k-1)):
| Failure number | Delay ceiling (seconds) |
|---|---|
| 1 | 0.5 |
| 2 | 1 |
| 3 | 2 |
| 4 | 4 |
| 5 | 8 |
| 6 | 16 |
| 7 and later | 30 |
A retry helper you can run
The helper below retries only TransientError. A PermanentError is not caught, so it propagates at once. If the provider supplied a retry_after value, the helper never waits less than that. The sleep parameter lets a test replace real waiting with a stub.
import random
import time
class TransientError(Exception):
"""A failure worth retrying, such as a timeout or a 5xx from a provider."""
def __init__(self, message="", retry_after=None):
super().__init__(message)
self.retry_after = retry_after
class PermanentError(Exception):
"""A failure that retrying cannot fix, such as a 400 or an invalid token."""
def send_with_retry(send, max_attempts=5, base=0.5, cap=30.0, sleep=time.sleep):
for attempt in range(1, max_attempts + 1):
try:
return send()
except TransientError as err:
if attempt == max_attempts:
raise
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
if err.retry_after is not None:
delay = max(delay, err.retry_after)
sleep(delay)
calls = {"n": 0}
def flaky_send():
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("provider timeout")
return "accepted"
waits = []
result = send_with_retry(flaky_send, sleep=waits.append)
print(result, "after", calls["n"], "calls")
print("waited", len(waits), "times")The run prints accepted after 3 calls and waited 2 times. The exact wait values differ on every run because of the jitter.
Do not sleep inside the worker
The helper above is fine for a short in-process retry or two. For longer delays it has a cost: a worker that sleeps for 30 seconds does nothing else for 30 seconds. At scale, a provider outage would leave every worker asleep and the queue would back up.
Production systems usually move the wait out of the worker:
- The worker catches the transient error and publishes the message back to the queue with a delivery delay. Many queues support this directly, for example a per-message delay or a visibility timeout.
- The message carries an
attemptcounter, so the next worker knows which delay to apply. - Separate retry queues for short, medium, and long delays keep a flood of retries from blocking fresh traffic.
The worker is then free to take the next message immediately.
Stopping: attempt limits, deadlines, and dead-letter queues
An unlimited retry loop turns one bad message into permanent load. Set two limits.
- Maximum attempts. Five to eight is common. After that, give up on the channel.
- A deadline tied to usefulness. A one-time login code that expires in five minutes is worthless after six. A "your order shipped" email stays useful for hours. Store an
expires_aton the event and drop it once it has passed, even if attempts remain.
When a message hits either limit, move it to a dead-letter queue (DLQ). A DLQ is a separate queue that holds messages the system gave up on. It keeps them for inspection, alerting, and manual or automated replay once the cause is fixed. Also write a final failed status for the notification so that delivery tracking shows the outcome.
If the primary channel fails for good, some systems fall back to another one the user has enabled, such as SMS after a push failure. Treat this as a product decision. Fallback to a more intrusive or more expensive channel should apply only to important notification types.
Failure paths in one picture
Pitfalls
- Retries at several layers multiply. If the SDK retries three times, your worker retries five times, and the queue redelivers four times, one failure produces up to 60 calls. Pick one layer to own retries and turn the others off or keep them minimal.
- Timeouts are ambiguous. A timeout means you did not get an answer. The provider may have accepted and sent the message anyway. Retrying after a timeout can therefore produce a duplicate. Retries are only safe when paired with the idempotency keys covered in the next chapter.
- Retrying during a long outage. If a provider is down for an hour, every message burns all its attempts quickly and lands in the DLQ. A circuit breaker helps. After many consecutive failures, the worker stops calling that provider for a short period, holds messages, and probes occasionally. Many teams also fail over to a second provider for the same channel.
- Ignoring
Retry-After. When a provider tells you how long to wait, shorter waits only earn more 429 responses. - No jitter on scheduled retries. Fixed delays recreate the synchronized spike you were trying to avoid.
Summary
Classify each failure as transient or permanent and retry only the transient ones. Use capped exponential backoff with jitter, and honor Retry-After when the provider sends it. Requeue with a delay instead of sleeping in the worker. Bound retries by attempt count and by message expiry. Send exhausted messages to a dead-letter queue and record a final status.
Exercise
A worker sends a push notification and the call times out. The worker retries and the second call succeeds. Later the user reports receiving the same push twice. Explain how this can happen despite correct retry logic, and name the technique that prevents it.
Show answer
A timeout means the worker got no answer, not that the provider did nothing. The provider may have accepted and delivered the first request, with only the response lost or delayed. The retry then sends a second copy. The fix is idempotency: attach a stable key (for example event id, user id, and channel) to each send and skip or deduplicate any send whose key was already claimed. The next chapter covers this.
Exercise
Your retry policy uses base=1 second, cap=60 seconds, and full jitter. What is the maximum possible delay before the 5th retry, and why is jitter better than a fixed 16-second delay when 5,000 workers fail together?
Show answer
The ceiling after the 5th failure is min(60, 1 * 2^4) = 16 seconds, so the delay is a random value between 0 and 16 seconds. With a fixed 16-second delay, all 5,000 workers retry at the same instant and hit the recovering provider with the same spike. With jitter, the retries spread across the 0 to 16 second window, so the provider sees a smoother load.