Part 2 of 3: Reliable backends with just your database Next: The Transactional Outbox Pattern, Explained Simply
A customer taps “Pay”. Your app sends the payment request. The phone loses signal for a moment and the request times out. The app does the sensible thing and tries again. The customer gets charged twice.
Nothing here was a bug in the usual sense. The network did what networks do, and the client did what clients should do. The missing piece was a way for the server to recognise “this is the same request I already handled”.
That piece is called an idempotency key. Stripe, Shopify, Adyen, PayPal and most banking APIs use one. This post explains the idea, then builds the server side step by step.
Short version:
- The client makes up a unique key for each action, like “pay order 881”, and sends it with every retry of that action.
- The server saves the key with the result. If the same key comes again, it returns the saved result instead of doing the work again.
- Save the key before doing the work, in the same transaction when you can. That is what makes the whole thing safe.
The problem: a timeout tells you nothing
When a request times out, the client cannot tell which of these happened:
From the client’s side, A and B look the same. If it never retries, case A leaves a customer who wanted to pay with no order. If it always retries, case B charges them twice. You need the server to make retries safe.
What “idempotent” means
An action is idempotent when doing it twice has the same effect as doing it once. Pressing a lift button is idempotent. Pressing it five more times does not call five lifts.
HTTP already defines some methods this way (RFC 9110):
| Method | Idempotent? | Why |
|---|---|---|
GET |
Yes | Reading twice changes nothing |
PUT |
Yes | “Set the name to Sam” twice leaves the name as Sam |
DELETE |
Yes | Deleting a deleted thing leaves it deleted |
POST |
No | “Create a payment” twice creates two payments |
PATCH |
Not always | “Add 10 to the balance” twice adds 20 |
Idempotency keys exist to make POST (and risky PATCH) calls behave like
the safe ones.
How an idempotency key works
The client sends a header with a value it generated, usually a random UUID:
POST /payments
Idempotency-Key: 6f1c2a9e-4b7d-4d3e-9a51-0c8e2f3b7d10
Content-Type: application/json
{"order_id": 881, "amount": "25.00", "currency": "EUR"}
The server keeps a small table of keys it has seen:
There is an IETF draft for the Idempotency-Key
header
that writes down the common behaviour, so you don’t have to invent your own
rules.
The four cases your server must handle
This table is the whole design. Print it out.
The last row catches a real bug: a client that reuses one key for two different actions. Without the check, the second payment would silently return the first payment’s result, and nobody would notice until the accounts don’t add up. To check it, store a hash of the request body with the key.
Building it in Postgres
The table
CREATE TABLE idempotency_keys (
account_id bigint NOT NULL,
key text NOT NULL,
request_hash text NOT NULL, -- sha256 of method + path + body
status text NOT NULL, -- 'started' | 'finished'
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, key)
);
The key is scoped to the account. Two customers who happen to send the same UUID don’t clash, and one customer cannot replay another customer’s response by guessing their key.
Case 1: all the work happens in your database
If “do the request” only means writing rows to the same database, this is easy. Put everything in one transaction:
BEGIN;
INSERT INTO idempotency_keys (account_id, key, request_hash, status)
VALUES ($account, $key, $hash, 'started')
ON CONFLICT (account_id, key) DO NOTHING
RETURNING key;
-- No row returned? The key exists. ROLLBACK, then read the saved row
-- and follow the four-case table.
INSERT INTO orders (account_id, order_id, amount) VALUES (...);
UPDATE idempotency_keys
SET status = 'finished', response_code = 201, response_body = $response
WHERE account_id = $account AND key = $key;
COMMIT;
Postgres quietly handles the hard race for you here. If two copies of the
same request arrive at the same moment, the second INSERT ... ON CONFLICT
waits until the first transaction ends. If the first one commits, the second
sees the key and returns the saved response. If the first one rolls back,
the second goes ahead as if it came first. No double order either way.
Case 2: the work calls someone else
Now the hard one. Your endpoint charges a card through a payment provider. That call is outside your database, so you cannot roll it back.
You can’t hold a transaction open across a slow network call (it ties up a connection and can block database cleanup). So you split the work into steps and save progress between them:
The important trick is in step 2: pass the idempotency key on to the provider. Most payment providers accept one. Now think about a crash:
| Crash happens | What the retry sees | What it does |
|---|---|---|
| Before step 1 commits | No key | Starts fresh. Nothing was charged |
| Between step 1 and 2 | Key started, old |
Calls the provider. Not charged yet, so this charges once |
| Between step 2 and 3 | Key started, old |
Calls the provider again with the same key. The provider returns the first charge instead of making a new one |
| After step 3 | Key finished |
Returns the saved response |
Every row ends with exactly one charge. That works only because the key travels through every system that has a side effect.
How does a retry know a started key is “old” and not still running? Use
created_at. If it is older than your request timeout (say 60 seconds), the
first attempt is dead and the retry can take over. If it is newer, answer
409 and let the client try again in a moment.
Brandur Leach wrote a longer version of this with more steps, called recovery points. It is worth reading if your endpoint calls more than one outside system.
The client side
The server can only help if the client sends the key correctly. The most common mistake:
Generate the key when the user decides to act (taps “Pay”), store it with the pending action, and reuse it for every retry. If the app restarts mid-retry, it should pick up the same key from storage.
Also:
- Retry with growing waits plus a bit of randomness (for example 1s, 2s, 4s, each plus up to 1s random). Without the randomness, thousands of clients that failed together all retry at the same instant.
- Only retry on timeouts, connection errors, 409 and 5xx. A 400 or 422 will fail the same way every time.
How long to keep keys
Keys don’t need to live forever. They only need to outlive any realistic retry. Stripe keeps them for at least 24 hours. Pick a window, document it, and delete older rows with a daily job:
DELETE FROM idempotency_keys
WHERE created_at < now() - interval '24 hours';
Mistakes I see often
- Saving the key after the work. If you crash in between, the retry finds no key and does the work again. Save the decision first.
- Keeping keys in a cache that can lose them. If the key lives in Redis and Redis restarts, your protection is gone. Keep the key in the same database as the data it protects.
- Not saving errors. If the first attempt failed validation, a retry with the same key should get the same error, not a fresh run. Some APIs choose not to save 5xx errors so a retry can succeed. Either is fine if you document it.
- No body hash. Reusing a key for a different request should fail loudly, not return the wrong result.
- Global keys. Scope keys to the caller, or one client can read another client’s responses.
You don’t always need a key
Sometimes the request already carries something unique. Then a UNIQUE
constraint does the job:
- A message consumer can store each message id in a
processed_messagestable with a unique index, and skip ids it has seen. This is the usual partner for the transactional outbox pattern, which delivers messages at least once. - A background job can use the job id the same way. Jobs in a Postgres job queue can run twice after a crash, so they need this.
- “Create the invoice for order 881” can use
UNIQUE (order_id)on the invoices table.
An idempotency key is what you use when the request has no natural unique value, which is the usual case for “create a new thing” endpoints.
Questions people ask
Who creates the key, client or server? The client. Only the client knows that attempt 2 is a retry of attempt 1.
Should the key be a UUID? Any random string with enough length works. UUID v4 is the easy choice. Don’t build keys from timestamps or counters, because two devices can produce the same one.
Is PUT enough instead of POST with a key?
Sometimes. If the client can choose the new resource’s id (PUT /payments/6f1c...), the id itself acts as the key. Many APIs prefer POST
plus a key so the server keeps control of ids.
Does this give “exactly once”? It gives “the effect happens once”, which is what users care about. Under the hood, requests still arrive more than once. The key makes the extra copies harmless.
Cheat sheet
Further reading
- IETF draft: The Idempotency-Key HTTP Header Field
- Stripe API docs: idempotent requests
- Brandur Leach: Implementing Stripe-like idempotency keys in Postgres