Sub topic 9
Handling timeouts, failures, and retries
This chapter assumes you know HTTP timeouts, the idempotency key pattern from the previous chapters, and the payment state machine (created, authorized, captured, and so on). It covers what to do when a call to a PSP (payment service provider) or to your own service does not return a clear answer.
A timeout is not a failure
A client that times out knows only that it received no response. The request may have never arrived, may have been processed with the response lost, or may still be running. For a payment, these cases differ: in the first the customer was not charged, and in the second they were.
The rule that follows is that a timeout means the outcome is unknown. Do not mark the payment failed because a call timed out. Marking it failed and then retrying with a new key is how double charges happen.
Classifying failures
Each failure type needs a different response. Sort them before writing any retry logic.
| Failure | Example | Outcome known? | Response |
|---|---|---|---|
| Definitive decline | Issuer returns "insufficient funds" | Yes | Do not retry. Move to `failed`. |
| Validation error | Malformed card token, HTTP 400 | Yes | Do not retry. Fix the request. |
| Transient error | HTTP 503, connection refused before sending | Usually yes, nothing happened | Retry with backoff. |
| Timeout | No response within the deadline | No | Retry with the same key, or query status. |
| Rate limit | HTTP 429 | Yes, rejected | Retry after the delay the server asks for. |
Only the timeout row is truly ambiguous. A connection refused before any bytes are sent is safe to retry. A reset after the request body was sent is as ambiguous as a timeout.
Retrying safely
Retries are safe only if the operation is idempotent. Every attempt must carry the same idempotency key, generated once per logical payment and not once per attempt. The server then returns the original result or finishes the original work, and never starts a second charge.
Add exponential backoff, which doubles the wait after each failure, and jitter, which randomizes the wait. Without jitter, thousands of clients that failed together retry together and overload a dependency that is trying to recover.
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))
# Demo: the first two attempts time out, the third succeeds.
calls = []
def flaky_send(key):
calls.append(key)
if len(calls) < 3:
raise TimeoutError("no response")
return {"status": "authorized", "key": key}
print(call_with_retries(flaky_send, "order-1042-attempt-key", base_delay=0.01))
print("keys used:", set(calls))The demo prints one distinct key across all three calls. That is the property that protects the customer.
Limits on retrying
- Cap attempts and total time. Retries must fit inside the caller's own deadline. If the customer's browser gives up after 30 seconds, a 60-second retry loop only produces work nobody waits for.
- Retry at one layer. If the browser, your API gateway, your service, and your PSP client each retry three times, one failure becomes up to 81 calls. Pick one layer to own retries, usually the one closest to the unreliable dependency, and have the others fail fast.
- Use a retry budget. Allow retries to add at most a fixed share of traffic, such as 10 percent. When a dependency is down, a budget stops retries from turning an outage into a bigger one.
- Add a circuit breaker. After many consecutive failures, stop calling the dependency for a short period and fail immediately. This protects the dependency and frees your threads.
Resolving unknown outcomes
Retrying with the same key works when the PSP honors idempotency keys. Not all do, and some keys expire. When you cannot rely on this, resolve the unknown outcome by asking instead of repeating the action.
- Before calling the PSP, record the attempt in your database with your own reference and the key you will send.
- Call the PSP. If you receive a definitive answer, record it and apply the state transition.
- On timeout, leave the attempt unresolved. Do not move the payment to
failed. - A background job queries the PSP for that reference, using a status endpoint or the PSP's lookup by merchant reference. It then records what actually happened.
- If the PSP has no record after its documented processing window, the charge did not happen. Only then mark the attempt failed.
Writing the attempt first matters. If your service crashes between the PSP call and the database write, the record of the intent is what lets the background job find and resolve the payment later.
Failures inside your own system
A payment touches your database, the PSP, your ledger, and a message queue. Any step can fail after an earlier one succeeded. Two habits help:
- Make each step safe to repeat. The state machine enforces this: applying
authorizedto a payment alreadyauthorizedshould return the existing result, not raise or duplicate ledger entries. Ledger writes should carry a unique reference, such as the payment ID plus event type, so a replayed write is rejected by a unique constraint. - Separate the decision from the side effects. Commit the state change first, then send events and notifications from that committed record. The next chapter covers the outbox pattern, which does this reliably.
Edge cases
- Idempotency key reused with a different body. Compare the stored
request_hash. If it differs, return an error such as HTTP 422 instead of replaying the old result. - Concurrent retries. A client may retry while the first request is still running. The unique constraint on
(merchant_id, idempotency_key)lets one request proceed. The other should receive a "request in progress" response (HTTP 409) and retry later, not run in parallel. - Late success. A PSP call that timed out may succeed a minute later. Your status check and later reconciliation must handle an
authorizedresult arriving for an attempt you thought was dead. Void it if the customer has already been told the payment failed. - Clock and deadline mismatch. If your timeout to the PSP is longer than your caller's timeout to you, the caller retries while your first request is still running. Keep each inner timeout shorter than the outer one.
Exercise
A client sends a capture request and gets a timeout. Its retry code generates a fresh idempotency key for each attempt, and the second attempt succeeds. The first request had in fact succeeded. What happens, and how do you fix it?
Show answer
The payment is captured twice, because the service sees two different keys and treats them as two separate requests. The fix is to generate the key once per logical operation and send the same key on every attempt, so the service returns the first result. As a second safeguard, the state machine rejects a second captured transition for the same payment.
Exercise
Your PSP call times out. Why should the payment not be moved to failed, and what should happen instead?
Show answer
The timeout only means no response arrived, and the PSP may have authorized the payment. Marking it failed could leave an authorization the customer never sees, or lead to a duplicate charge on a new attempt. Keep the attempt unresolved, then retry with the same key or query the PSP by your reference until you get a definitive answer.