Architecture
Idempotency Keys: Making Retries Safe in APIs and Payments
By NileVPS Team · Published · 5 min read
اقرأ المقال بالعربيA customer taps "Pay", the mobile network stalls, the app shows a spinner for ten seconds, and the customer taps again. Did they just pay twice? The first request may have succeeded while its response was lost, and the client's only sensible move is to retry. Idempotency is the property that makes that retry harmless: performing the same operation once or many times leaves the system in the same state. This article explains the concept, where it matters, and how to implement idempotency keys on a normal VPS stack.
What idempotent means in practice
An operation is idempotent when repeating it has no additional effect after the first time. Setting a value is idempotent; adding to a value is not.
UPDATE users SET email = '[email protected]' WHERE id = 7is idempotent. Run it five times and the row ends up the same.UPDATE wallets SET balance = balance - 100 WHERE id = 7is not. Run it five times and the customer loses 500.
By HTTP specification, GET, HEAD, PUT and DELETE are meant to be idempotent, while POST and PATCH generally are not, but your code has to keep that promise.
Why retries are unavoidable
Duplicate requests come from more places than impatient users:
- Mobile and browser clients retrying after a timeout.
- HTTP client libraries with automatic retry policies.
- Load balancers or reverse proxies retrying an upstream that did not answer in time.
- Message queues with at-least-once delivery, which can redeliver a message after a worker crash.
- Webhooks from payment gateways, which are commonly resent until they receive a success response.
You cannot get exactly-once delivery across a network. What you can get is at-least-once delivery combined with idempotent processing, which looks like exactly-once from the outside.
The idempotency key pattern
The client generates a unique key, usually a UUID, for each logical operation and sends it with the request, typically in a header such as Idempotency-Key. Retries of the same operation reuse the same key. The server remembers which keys it has processed and what it answered.
The flow on the server:
- Read the key. If it is missing on an endpoint that requires one, reject with
400. - Try to insert the key into a store with status
processing. If the insert fails because the key already exists, look at the stored record. - If the stored record is finished, return the saved response without running the operation again.
- If it is still
processing, return409 Conflict(or ask the client to retry later) so two parallel copies never run at the same time. - Otherwise run the operation, save the status code and response body against the key, and return it.
Also store a fingerprint of the request body. If a client reuses a key with a different payload, that is a bug, and the server should reject it with 422 instead of returning a response that belongs to another request.
A PostgreSQL implementation
A unique constraint does the hard part for you, because the database refuses a second insert atomically:
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
request_hash text NOT NULL,
status text NOT NULL DEFAULT 'processing',
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO idempotency_keys (key, request_hash)
VALUES ($1, $2)
ON CONFLICT (key) DO NOTHING
RETURNING key;If RETURNING gives you a row, you own the key and may proceed. If it returns nothing, someone has already used it. The strongest version performs the business change (creating the order, debiting the wallet) and the update of the key record in the same transaction, so you can never end up with money moved but no record of it.
Delete old keys with a daily cron job, using a window longer than any client's retry period.
A Redis implementation
Redis is a good fit when you want fast lookups with automatic expiry:
SET idem:3f2a9c1e-... processing NX EX 86400NX only sets the key if it does not exist, and EX expires it after a day. Because Redis is not inside your database transaction, use it as a fast guard rather than the only record for money-related operations, or accept that a crash between the two systems needs reconciliation.
Natural idempotency without keys
Sometimes you can design the operation so it is idempotent by nature:
- Use a client-supplied ID as the primary key:
INSERT ... ON CONFLICT (order_id) DO NOTHING. - Prefer absolute state over increments: "set status to shipped" instead of "advance to next status".
- Use conditional updates:
UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending'. A second run matches zero rows. - For webhooks, store the provider's event ID with a unique index and skip events you have seen.
Checklist
| Item | Why it matters |
|---|---|
| Key required on every write endpoint that moves money or creates records | Prevents duplicate orders and charges |
| Unique constraint, not "check then insert" | Avoids race conditions between parallel retries |
| Request fingerprint stored with the key | Detects key reuse with a different payload |
| Saved response replayed on retry | Client gets a consistent answer |
| Expiry window longer than client retry policy | Old keys do not grow forever |
| Clients reuse the same key on retry | A new key per attempt defeats the whole pattern |
Idempotency pairs naturally with other resilience patterns. If you are adding retries, read our guide to the circuit breaker pattern so retries do not hammer a failing service. When you want a server to try this on, a small instance from our pricing page is plenty for PostgreSQL and Redis together.
FAQ
Is POST ever idempotent?
Not by default, but you can make a POST endpoint idempotent by requiring an idempotency key or a client-generated resource ID. The HTTP method describes the default expectation, while your implementation decides the actual behaviour.
How long should I keep idempotency keys?
Keep them at least as long as any client, queue or webhook sender might retry. For most APIs 24 to 72 hours is reasonable. Payment providers may resend webhooks over several days, so event IDs from them are often kept longer.
Do idempotency keys replace database transactions?
No. They solve a different problem. Transactions keep one request consistent, while idempotency keys stop repeated requests from applying the same change twice. The safest design uses both, with the key record updated inside the same transaction as the business change.