A customer taps "Pay" once. The spinner keeps spinning, nothing seems to happen, so after a few seconds they tap again. Behind the screen, the payment service gets two requests, the order service retries after its own timeout, and the next morning someone in support is explaining why one purchase shows up as two pending charges.
Nobody did anything wrong there. The customer, the browser and the order service all behaved reasonably. The API didn't have an answer for "what if the same request arrives twice?" This post is about giving it one: what idempotency means in HTTP, how idempotency keys work, why the request body matters as much as the key, and what it costs to run.
What "idempotent" actually promises
HTTP has a precise definition. RFC 9110 calls a method idempotent when "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request." By that definition GET, HEAD, PUT and DELETE are idempotent, and POST isn't (RFC 9110, section 9.2.2).
Two details in that section are easy to miss. First, the promise is about the intended effect. The server can still log every call. Second, the response is allowed to differ: the first DELETE /carts/42 might return 204 and the second 404, and the cart is gone either way.
The trouble is that the operations that matter most are usually POSTs: create an order, start a refund, send a transfer. And duplicates are routine:
- Users double-tap when a screen feels stuck.
- Mobile connections drop after the request went out but before the response came back.
- Client libraries and load balancers retry on timeouts.
- Queues redeliver a message when a worker crashes after doing the work but before acknowledging it.
An API that assumes every request is unique is betting against all of those at once.
Idempotency keys: name the attempt, not the packet
The common fix is an idempotency key. The client generates a unique value when the user starts the action (Stripe suggests a V4 UUID), sends it in a header, and reuses it for every retry of that same action. The server remembers what it did for that key.
POST /v1/payments
Idempotency-Key: 9b2f6c1e-3d4a-4f7b-8c2e-5a1d0e9f7b63
Content-Type: application/json
{"order_id": "ord_123", "amount": 4900, "currency": "USD"}
Stripe's version is the one many teams copy. Per their docs, for API v1 they save the status code and body of the first request once the endpoint starts running, and retries with the same key get that saved response back, 500 errors included. Keys can be up to 255 characters and can be pruned once they're at least 24 hours old. And if the parameters on a retry don't match the original, they return an error.
The IETF is standardizing the header itself. The current Idempotency-Key draft (still an Internet-Draft, not an RFC) suggests three status codes worth adopting even today:
| Situation | Suggested response |
|---|---|
| The endpoint requires a key and the request has none | 400 Bad Request |
| A request with this key is still being processed | 409 Conflict |
| The key was already used with a different request body | 422 Unprocessable Content |
Here's a minimal sketch in TypeScript with Postgres. It assumes a db client, two small helpers (sha256 and canonicalJson) and a chargeCard call to your payment provider:
// idempotency_keys: PRIMARY KEY (user_id, key), plus request_hash,
// status, response_code, response_body, created_at
async function createPayment(userId: string, key: string, body: PaymentRequest) {
const hash = sha256(canonicalJson(body));
const claimed = await db.query(
'INSERT INTO idempotency_keys (user_id, key, request_hash, status) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING',
[userId, key, hash, 'in_progress'],
);
if (claimed.rowCount === 0) {
const { rows: [saved] } = await db.query(
'SELECT request_hash, status, response_code, response_body FROM idempotency_keys WHERE user_id = $1 AND key = $2',
[userId, key],
);
if (saved.request_hash !== hash) return { code: 422, body: { error: 'Key reused with a different request' } };
if (saved.status === 'in_progress') return { code: 409, body: { error: 'Still processing, retry shortly' } };
return { code: saved.response_code, body: saved.response_body };
}
// The client key is only unique per user, so scope it before sending it downstream
const payment = await chargeCard(body, { idempotencyKey: `payments-${userId}-${key}` });
await db.query(
'UPDATE idempotency_keys SET status = $3, response_code = $4, response_body = $5 WHERE user_id = $1 AND key = $2',
[userId, key, 'done', 201, payment],
);
return { code: 201, body: payment };
}
The INSERT ... ON CONFLICT DO NOTHING is what makes it safe under concurrency: two identical requests racing each other can't both claim the key, because the primary key lets only one insert win. Note the gap, too. If chargeCard throws, this sketch leaves the row stuck in in_progress. Real code needs a lock timeout or a way to resume. Brandur Leach's Implementing Stripe-like Idempotency Keys in Postgres walks through a full version with a locked_at column and recovery points, and it's worth reading end to end.
Same key, different request: refuse it
A key on its own is only a label. The server also has to decide what "the same request" means, which is why the sketch above stores a hash of the body. Say a buggy client reuses one key for a $49 payment and then a $490 one. If the server only checks the key, the second payment silently returns the first one's result, and nobody finds out until reconciliation.
AWS describes the same rule in the Builders' Library: the service stores the original request's parameters next to the client token, and a retry with different parameters gets "a validation error indicating a parameter mismatch between idempotent requests" (Making retries safe with idempotent APIs). A good key protects you twice: against doing the work twice, and against one key standing in for two different intentions.
Two practical notes on the fingerprint. Hash a canonical form of the body (sorted keys, normalized numbers) so that harmless formatting differences don't trigger false conflicts. And scope keys to the caller, as Brandur's unique index on (user_id, idempotency_key) does, so one customer's key can never collide with or reveal another's.
Let the data model help
Some operations get much easier when you model them as state changes instead of "do the thing" commands. Take a payment provider's webhook, which may arrive more than once. Inserting a new payment row each time creates duplicates. A conditional update can't:
UPDATE invoices
SET status = 'paid', paid_at = now()
WHERE id = $1 AND status = 'open';
The first delivery flips the invoice to paid. Every later delivery matches zero rows and changes nothing, and your handler can treat "zero rows updated" as "already done" and return success. A small state machine with clear final states (open, paid, refunded) makes duplicates visible in one place instead of hiding them in scattered if checks.
Unique constraints help in the same way. A unique index on processed_webhooks(provider_event_id) turns "did we already process this event?" into something the database answers for you, under concurrency, without a lock in application code.
Side effects outside your database
The hard cases sit at the edges. If the database commit succeeds and the email fails, should the retry create another row or only resend the email? If the payment provider charges the card and your service times out before saving the result, how do you find out what happened?
A few patterns cover most of it:
- Pass your key downstream. If the provider supports idempotency keys, send one derived from yours. Brandur's design does this for the Stripe charge, so a retry after a crash can't double-charge.
- Stage messages in the same transaction. Write the "send receipt" job to a table inside the same commit as the order, and publish it after the commit. That's the outbox pattern, and it keeps "saved but never sent" and "sent but never saved" from happening.
- Reconcile on a schedule. A job that compares your records with the provider's catches whatever slipped through the first two.
On the Napas and Gtel integrations I worked on, idempotent contracts, a retry queue and ACK monitoring were part of the design. None of that is exotic. When the other side of the call is a payment network or a telco, it's the cost of entry.
Keep the responses boring
A retried request shouldn't surprise the caller. AWS's stated preference is to return "a semantically equivalent response" for the same token for some interval, and they explain why: an error like ResourceAlreadyExists forces the caller down a different code path even though nothing went wrong. Return the original success, or the current state of the resource, in the same shape. Then client retry logic stays a three-line loop instead of a decision tree.
What it costs, and when to skip it
Idempotency isn't free:
- Storage and retention. Stripe can prune keys after 24 hours, and Brandur suggests about 72 hours in his design. Longer protects against slow retries. Shorter is cheaper but lets a very late duplicate through as a new request.
- Contention. Every request to a protected endpoint now writes a key row first. On very hot endpoints, measure that.
- Failure handling. Stuck
in_progressrows need a timeout, a resume path or a cleanup job.
So spend it where a duplicate hurts: payments, refunds, transfers, order creation, anything that sends a message a human will read. GETs don't need it. A PUT that replaces a whole resource is already idempotent by definition. Updates like "set the display name" can usually be designed as replacements and skip the key machinery entirely.
Try this week
- List your POST endpoints and mark the ones where running twice would cost money, send a duplicate message or be hard to explain.
- For the top one, have the client generate the key when the user starts the action and reuse it on every retry.
- Store a hash of the request with the key and return
422when the body doesn't match. - Find one webhook handler that inserts rows and turn it into a conditional update or a unique constraint.
Idempotency makes one call safe to repeat. When a business action spans several services, the next pieces are the outbox pattern and sagas.