How to Design Idempotent APIs That Survive Retries

Your payment endpoint worked fine in testing, until a customer on a slow connection clicked “Pay” twice, the client retried a timed-out request, and the same order was charged twice. Nobody shipped a bug that day. The API simply had no answer for “did this request already happen?” That is the problem idempotency solves, and learning how to design idempotent APIs that survive retries is one of the highest-value skills in backend work.

Networks fail in ambiguous ways. A request can reach the server, run to completion, and still never deliver its response, so a timeout and a total failure look identical from the client’s side. The only safe move is to retry, and the only safe retry is one the server can recognize as a repeat.

Why Retries Break APIs That Were Never Designed for Them

Most APIs treat every incoming request as new work: a POST to create an order runs the same code whether it is the first attempt or the third. When a client retries after a timeout, the server creates a second order, sends a second confirmation email, and charges the card a second time. The design was the failure.

This is not an edge case: mobile networks drop packets, load balancers restart, and a deploy can cut a connection mid-response. Any API serving real users will see retried requests, so the question is whether yours can tell a retry from a fresh request. POST, PATCH, and any operation with a side effect (charging, sending, creating, decrementing) need explicit idempotency design, and they are the ones where a duplicate costs real money.

What Idempotency Actually Guarantees (and What It Does Not)

An idempotent operation is one you can run many times with the same effect as running it once: the second call does not repeat the side effect, it returns the original result instead. That promise is narrower than people assume.

Idempotency does not mean the response is identical forever: an order created on Monday may show a different status on Friday. What stays fixed is the creation itself, one order, one charge, one shipment, no matter how many times the request arrived.

It also does not mean every identical payload is the same request: two customers can legitimately submit identical orders. The system must distinguish “the same request sent twice” from “two requests that happen to look alike”, and that needs an explicit identifier from the client.

Design Idempotent APIs Around a Key, Not a Hope

Idempotency keys are the standard mechanism: a unique value, usually a UUID, generated per logical operation and sent in a header such as Idempotency-Key. The server stores the key with the result of the first execution, and on a repeat it returns the stored result without running the operation again.

First, the key belongs to one logical operation, not to one HTTP attempt. A client retrying a payment must send the same key it used the first time, and a new payment gets a new key. A fresh key per attempt leaves the server no way to recognize the repeat.

Second, scope the key to the operation and the caller, by account and endpoint, so one tenant’s retry never returns another tenant’s result.

Third, give keys a lifetime. Keep them long enough to cover realistic retry windows, 24 hours is a common choice for payment-style APIs, and expire them eventually or storage grows without bound. Tell clients the retention period, because a silently expired key turns a safe retry into a duplicate.

When you design a public API for clients on unreliable networks, put the idempotency key in the contract from day one. Bolting it on later means existing clients do not send it, and the endpoints that need it most stay unprotected.

Store the Result, Not Just the Key

A common first attempt stores the key alone and skips the operation on a repeat. That stops the duplicate charge, but the client still needs the original response, order ID and receipt included. A bare “already processed” status forces the client to guess what happened, so store the full response with the key and replay it verbatim on a repeat.

The storage step must be atomic with the operation itself. If the server records the key but crashes before committing the order, the retry finds a key with no result and no order. If it creates the order but crashes before storing the key, the retry creates a second order. Write the key and the result in the same transaction as the business operation, or put a unique constraint on the key column.

Store the key in a table with the request fingerprint, the response status and body, and a timestamp. Look it up before each request: if it exists and the fingerprint matches, return the stored response. If the fingerprint differs, the client reused a key for a different operation, so answer with a 422 or 409 error instead of replaying the wrong result.

Method Idempotent by default? What to do
GET Yes Safe to retry freely
PUT Yes Full replacement repeats safely
DELETE Yes Deleting a missing resource returns the same outcome
POST No Require an idempotency key
PATCH Depends Repeatable only for absolute values, not increments

Retry Rules Clients Should Follow

Idempotency is a contract with two sides, and the client holds up its end with disciplined retries. First, retry only requests that can fail safely: network errors, timeouts, and 5xx responses. A 4xx means the server understood and rejected the request, so retrying the same payload fails the same way.

Second, wait before retrying, and wait longer each time. Immediate retries pile onto a struggling server, and a retry storm can turn a brief outage into a long one. Exponential backoff with jitter, a small random delay added to each wait, spreads the load and gives the server room to recover. Three attempts with waits around one, two, and four seconds is a solid starting point. For a deeper treatment, this guide on how to design retries that do not make things worse walks through backoff, jitter, and circuit breakers in detail.

Third, keep the idempotency key stable across the whole retry chain. Generate it once when the user initiates the action, store it with the pending operation, and reuse it for every attempt until the operation succeeds or the user cancels.

Good API retry safety also means knowing when to stop: after the final attempt fails, surface the failure instead of retrying forever in the background. A payment stuck in limbo is worse than one that clearly failed, because the user cannot tell whether to try again or wait.

Where Idempotency Gets Hard: Side Effects and Timeouts

The easy cases are single writes to your own database. The hard cases are everything else: sending an email, calling a payment gateway, or publishing a message to a queue cannot be undone by a transaction, and each step can fail on its own.

The usual answer is to make the external call idempotent too. Most payment gateways accept their own idempotency key, so pass yours through instead of generating a new one. For emails, record the intent to send before sending, then check that record before each attempt, and skip any message already sent.

Timeouts deserve their own attention. When your server calls a slow downstream service, a short timeout can kill the request while the downstream work still completes, and the next retry collides with the first attempt’s side effect. Set timeouts to match the service’s real latency, and when you handle API errors from those calls, distinguish “the call failed” from “we do not know what happened.” Only the unknown case needs a cautious retry.

Finally, watch rate limiting. A retried request counts against the client’s quota each time it arrives, and a client stuck in a retry loop can burn through its allowance. Consider exempting replayed idempotent requests from rate limits, or counting a replay as a cache hit rather than fresh work.

A Practical Checklist Before You Ship

Before your next side-effect endpoint goes live, run through this list. Require an idempotency key header on every mutating POST, and reject requests that omit it with a clear 400 error. Store the key, the request fingerprint, and the full response in the same transaction as the operation. Replay the stored response on repeats, and return a 409 when a key is reused with a different payload. Document the key format, retention period, and retry behavior clients should use. Then test it the way production will: send the same request twice, kill the connection mid-response, and confirm one order, one charge, and one email result.

Idempotent API design is not a feature you add when duplicates start hurting. It is the baseline that makes retries safe, and retries are the baseline that makes distributed systems work at all. Build it in early, and the day the network drops a response becomes a boring log line instead of a refund ticket.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.