Sub topic 9
Handling timeouts, failures, and retries
This chapter assumes you know basic HTTP, relational transactions and unique constraints, and the idempotency-key pattern from the previous chapters. You should also be able to read short Python snippets.
Why timeouts are the hard case
A network call can end in three ways: success, a clear failure, or silence. Silence is the dangerous one. If your service sends a charge to a PSP (payment service provider) and the connection times out, you do not know whether the PSP processed it. The money may have moved, or it may not.
Treat a timeout as an unknown outcome, not as a failure. Marking the payment failed after a timeout can leave a customer charged for an order you cancelled.
Classify failures first
Retry decisions depend on the kind of error.
| Error | Example | Safe to retry? |
|---|---|---|
| Timeout or connection reset | No response in 5 s | Yes, with the same idempotency key |
| 5xx or "try later" | PSP returns 503 | Yes, with backoff |
| Rate limit | HTTP 429 | Yes, after the wait the server asks for |
| Business decline | Card declined, insufficient funds | No. The result is final |
| Validation error | Bad currency code | No. Fix the request |
Retry with the same key and backoff
Retries are safe only when the receiver deduplicates. Reuse one idempotency key for every attempt of the same operation. Add exponential backoff (the wait doubles each attempt) and jitter (a random part of the wait) so many clients do not retry at the same instant and overload a recovering PSP.
import random
import time
def call_with_retries(send, idempotency_key, max_attempts=4, base_delay=0.2):
"""send(key) raises TimeoutError on a network timeout."""
for attempt in range(max_attempts):
try:
return send(idempotency_key)
except TimeoutError:
if attempt == max_attempts - 1:
raise
delay = base_delay * (2 ** attempt)
time.sleep(random.uniform(0, delay))Generate the key once, before the loop, and store it with the payment. If you create a new key inside the loop, each retry looks like a new charge and you lose all protection.
Resolve unknown outcomes
When retries run out, the payment stays in an in-flight state. Do not guess. Resolve it in one of these ways:
- Query the PSP by your idempotency key or reference and read the real status.
- Wait for the PSP's webhook, which reports the final result asynchronously.
- Let a background job re-check stale payments and move them through the allowed state transitions.
- If the PSP has no record, void or cancel the attempt so a late success cannot appear afterward.
Reconciliation, covered later, is the final safety net for anything these steps miss.
Common mistakes
- Retrying inside every layer. If the client, the gateway, and the service each retry 3 times, one failure becomes 27 calls. Pick one layer to own retries.
- Retrying without a deadline. Set a total time budget, so the caller is not left waiting.
- Retrying declines. A declined card will not succeed on the tenth attempt, and repeated tries can trigger fraud flags.
Exercise
A charge request to the PSP times out. Your code generates a fresh UUID as the idempotency key for each retry. What can go wrong, and how do you fix it?
Show answer
If the first request actually succeeded, the retry carries a different key, so the PSP treats it as a new charge and the customer is charged twice. Generate the key once, store it with the payment, and reuse it on every attempt.
Exercise
Your retries are exhausted after repeated timeouts. What should the payment's status be, and what are two ways to learn the real outcome?
Show answer
Leave it in an in-flight (unknown) state, not failed. Query the PSP using the idempotency key or reference, or wait for the PSP's webhook. A background job can also re-check stale payments.