Retries, Backoff and Idempotency
Learn which failed requests are safe to repeat, how to space retries, and how idempotency keys prevent duplicate actions.
Key takeaways
- A timeout doesn't tell you whether the server did the work, only that you didn't hear back.
- Retry timeouts, connection failures and some
5xxand429responses; don't retry requests that are simply wrong. - Exponential backoff with random jitter keeps many clients from returning in waves.
- An operation is idempotent when doing it several times leaves the same result as doing it once.
- Limit total attempts and total time, and avoid retrying at every layer of a system at once.
Retry a failed request only when the failure is likely to be temporary and repeating the action can't cause harm. Wait a little longer after each attempt, add some randomness to the wait, and stop after a limit. For actions that must not happen twice, such as charging a card, attach a unique idempotency key so the server can recognize a repeat.
Those three ideas belong together. Retries recover from brief faults, backoff stops the retries from making an outage worse, and idempotency makes them safe.
Why a timeout is ambiguous
Your program sends "create this order" and nothing comes back. There are three very different possibilities: the request never arrived, the server received it and failed partway, or the server finished and the reply was lost.
From the client's side these look identical. Resend a plain create request and you may produce a second order. Give up and you may lose the first. Networks can't remove this uncertainty, so the application has to be designed for it.
The payment happens once even though the request was sent twice.
What idempotent means
An operation is idempotent if applying it repeatedly has the same effect as applying it once. "Set the light to on" is idempotent. "Toggle the light" isn't.
In HTTP, RFC 9110 defines GET, HEAD, OPTIONS, TRACE, PUT and DELETE as idempotent. POST isn't, and PATCH isn't guaranteed to be. This describes the intended effect on the server, not an identical response: a second DELETE may report that the item is already gone, and the state is still the same. HTTP methods has the full picture.
The definition is a promise the application must keep. If a GET handler sends an email, retrying it sends two, whatever the standard says.
Which failures deserve a retry
| What happened | Retry? | Notes |
|---|---|---|
| Connection refused or reset | Often | Brief restarts cause these |
| Timeout | If the action is safe to repeat | Outcome is unknown |
408 Request Timeout | Usually | The server gave up waiting |
429 Too Many Requests | Yes, after waiting | Honor Retry-After |
500 Internal Server Error | With caution | May be a repeatable bug |
502, 503, 504 | Often | Gateway or overload problems |
400, 404, 422 | No | The same request will fail again |
401, 403 | No | Fix or refresh credentials first |
The gateway codes are explained in 502 and 504 errors. Note that a 504 means an intermediary didn't get an answer in time, so the back end may still complete the work.
Backoff: wait longer each time
Retrying immediately is the worst choice for an overloaded server. Exponential backoff doubles the delay after each failure. With a base of one second and a cap of 30, the maximum waits are 1, 2, 4, 8, 16 and then 30 seconds.
With jitter, each client picks a random wait up to the ceiling. Hypothetical example: the numbers are made up to show the method, not a quote or an average.
Jitter: don't retry in step
Imagine a service blinks and a thousand clients fail at the same moment. If they all use identical delays, they all return together one second later, then two seconds after that. The synchronized waves can knock the service over again, a pattern often called a thundering herd.
Jitter spreads them out. A simple and effective version, known as full jitter, picks a random delay between zero and the current ceiling:
ceiling = min(cap, base * 2 ^ attempt)
delay = random number between 0 and ceiling If the server supplies Retry-After, treat it as the minimum and add a small random amount on top. You can compare schedules in the retry and backoff simulator.
Know when to stop
Retries need two limits: a maximum number of attempts and a deadline for the whole operation. A person waiting at a checkout can't sit through minutes of silent retrying, while a background sync can reasonably try for hours.
Beware of multiplication. If a browser retries three times, your server retries three times and your database library retries three times, one click can become 27 database attempts during the very moment the database is struggling. Pick one layer to own retries, usually the one closest to the failing call that understands whether repeating is safe.
Two more tools help. A retry budget allows retries only as a small fraction of normal traffic. A circuit breaker stops calls to a failing dependency for a while, then lets a few test requests through to see whether it has recovered. Both stop one broken service from tying up every thread in the services that call it.
Idempotency keys
To make a POST safe, the client generates a unique value for each intended action and sends it with the request, often in a header named Idempotency-Key. Many payment APIs work this way, though header names and rules differ.
curl https://api.example.com/v1/payments \
-H "Idempotency-Key: 0f8c2b1e-6d4a-4c9b-9a51-7e3d2b8c1a44" \
-H "Content-Type: application/json" \
-d '{"amount": 4200, "currency": "usd"}' The key must stay the same across retries of one action and differ between actions. A random UUID works well. Generate it when the user decides to act and store it with the pending job, so a restart doesn't create a new one.
On the server:
- Save the key with a unique database constraint before or in the same transaction as the work.
- If the key is new, do the work and store the response.
- If it exists and finished, return the stored response.
- If it exists and is still running, ask the client to wait.
- If the same key arrives with a different body, reject it.
- Expire old keys after a documented period.
The unique constraint matters. Checking for the key and then inserting it as two separate steps leaves a gap where two simultaneous requests both pass.
Other ways to make repeats harmless
You don't always need a key. Let the client choose the identifier and use PUT /orders/{id}, so repeating it writes the same record. Record which message IDs a queue consumer has handled. Use conditional updates that apply only if the record is still in the expected state. When changing quantities, send the target value instead of an increment.
The same thinking applies to webhook receivers and scheduled jobs: assume any step may run twice, and make the second run do nothing new.
When you can't tell what happened
Sometimes retries run out and the outcome is still unknown. Don't guess. Mark the record as pending instead of succeeded or failed, and find out the truth separately.
If the other service lets you look an item up by your own reference, ask it whether the payment or order exists. If it only offers lists, compare recent entries against your pending records on a schedule. Where neither is possible, route the case to a person with enough detail to check it by hand.
Tell users the truth as well. "We're confirming your payment; please don't pay again" is far better than a generic error that invites a second click. Disabling the button after the first press helps, but it isn't a substitute for server-side protection, since reloads, back buttons and flaky mobile connections all find ways around it.
Settings in the tools you already use
Many HTTP libraries, command line tools and cloud software kits retry on their own. Before adding your own loop, find out what happens by default: which errors they retry, how many times, with what delays, and whether they include POST. Curl, for instance, retries only when you ask it to with the --retry option, while some kits retry several times unless told otherwise. Message queues often redeliver unacknowledged messages, which is a retry too, and it counts toward the same multiplication described above.
A small retry policy you can write down
Put the rules where your team can read them. A sensible starting policy for calls to an outside API might read: retry connection errors, timeouts, 429, 502, 503 and 504; allow up to four attempts; start at half a second, double each time and cap at ten seconds with full jitter; give up after thirty seconds in total; and retry a POST only when it carries an idempotency key.
Treat those numbers as placeholders to adjust. A search box wants fewer, faster attempts or none at all, because the user will simply type again. A nightly transfer can wait far longer. The value of writing the policy down is that exceptions become deliberate, and nobody has to rediscover during an outage why one service hammers another.
Testing it
Retry code often goes untested because failures are rare on a developer's machine. Simulate them: return 503 from a test server, add a delay longer than the timeout, and drop the response after saving the record. Confirm that exactly one record exists afterward, that waits grow, that attempts stop at the limit and that the final error reaches a person or a log. Record how often retries happen in production, too. A rising rate is an early warning that something downstream is getting worse.