Sub topic 6
Making payments idempotent
This chapter assumes you know basic HTTP and REST, relational transactions and unique constraints, and how timeouts and retries behave in distributed systems. You should also be able to read short Python and SQL snippets.
Why payments need idempotency
An operation is idempotent if running it several times has the same effect as running it once. Payment clients retry constantly. A mobile app loses signal, a load balancer drops a connection, or a user double-clicks "Pay". In each case the client does not know whether the first request reached the server and succeeded.
Without protection, a retry after a timeout can charge the customer twice. With an idempotency key, the retry is recognized as a repeat and returns the original outcome instead of creating a second payment.
The idempotency key contract
The client generates a unique key per logical operation, usually a random UUID, and sends it in a header such as Idempotency-Key. The server treats (merchant_id, idempotency_key) as the identity of that operation.
The rules the server enforces:
- First use of a key: process the request and store the result.
- Repeat use with the same request: return the stored result. Do not run the operation again.
- Repeat use with a different request: reject it with an error, such as HTTP 422 or 409. This is a client bug, and silently returning the old result would hide it.
- Repeat use while the first request is still running: return 409 (conflict, retry later), or wait for it to finish.
Scoping the key to the merchant matters. Two merchants can pick the same key by accident, and one must never see the other's payment.
Letting the database decide
Do not implement "check whether the key exists, then insert" in application code. Two concurrent requests can both see no row and both insert. Use a unique constraint and let the database settle the race atomically.
CREATE TABLE payments (
id UUID PRIMARY KEY,
merchant_id UUID NOT NULL,
idempotency_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (merchant_id, idempotency_key)
);
-- Try to create the payment. If the key was already used, no row is returned.
INSERT INTO payments (id, merchant_id, idempotency_key, request_hash, amount_minor, currency, status)
VALUES (gen_random_uuid(), :merchant_id, :key, :request_hash, :amount_minor, :currency, 'created')
ON CONFLICT (merchant_id, idempotency_key) DO NOTHING
RETURNING id;If the statement returns a row, this request won the race and owns the operation. If it returns no row, the key was already used. Load the existing payment and compare its request_hash with the hash of the current request.
- Hashes match: this is a genuine retry. Return the stored payment.
- Hashes differ: the client reused a key for a different request. Return an error.
What goes into the request hash
The request hash is a fingerprint of the parts of the request that define its meaning. A typical choice is a SHA-256 over a canonical form of the amount, currency, payment method token, and target resource.
Some edge cases:
- Canonicalize before hashing. Field order in JSON, whitespace, and number formatting should not change the hash.
- Exclude fields that legitimately vary between retries, such as a request timestamp or trace ID.
- Hash the parsed values, not the raw body, so that
19.99and19.990do not look different.
Request flow
The diagram shows the decision path for each incoming request.
Storing the result and the in-progress problem
The payments row records the outcome through its status. For simple creation calls, a retry can read the payment and return its current state. Some APIs also store the full response body, status code, and headers so the replay is byte-for-byte identical. That is more work but gives clients a predictable contract.
The tricky case is a request that has inserted its row but not yet finished. A retry arriving at that moment sees status = 'created'. The server must not start a second call to the PSP (the payment service provider). Options:
- Return 409 with a
Retry-Afterheader and let the client poll. - Block briefly on the row, for example with
SELECT ... FOR UPDATE, until the first request commits.
The second harder case is a crash after the insert but before the PSP call, which leaves a row stuck in created. A recovery job should find old rows in non-terminal states and either resume them or move them to failed. This ties into the state machine chapter, since only legal transitions should move the row forward.
Idempotency toward the PSP
Your own API is only half of the problem. Your service also calls a PSP, and that call can time out too. If you retry it with no protection, you may create two charges at the PSP even though your database holds one payment.
Pass an idempotency key to the PSP on every call, and derive it from your own stable identifiers, for example the payment id plus the operation name (authorize). Never generate a fresh random key per attempt. A fresh key per attempt defeats the purpose.
The retry helper from the failures chapter shows the pattern: the same key is sent on every attempt.
import random
import time
def call_with_retries(send, idempotency_key, max_attempts=4, base_delay=0.2):
"""send(key) raises TimeoutError on a network timeout."""
for attempt in range(max_attempts):
try:
return send(idempotency_key)
except TimeoutError:
if attempt == max_attempts - 1:
raise
delay = base_delay * (2 ** attempt)
time.sleep(random.uniform(0, delay))Common errors
| Mistake | Consequence | Fix |
|---|---|---|
| Check-then-insert in application code | Concurrent requests both create payments | Unique constraint plus `ON CONFLICT` |
| Key not scoped to the merchant | One merchant can read or collide with another's payments | Unique on `(merchant_id, key)` |
| No request hash comparison | A reused key silently returns the wrong payment | Store and compare `request_hash` |
| New PSP key on each retry | Duplicate charges at the PSP | Derive the key from the payment ID and operation |
| Keys kept forever | Table growth, and old keys block legitimate reuse | Define a retention window, such as 24 hours to 30 days |
| Treating a 5xx or timeout as "not processed" | Client retries a request that did succeed | Always retry with the same key |
Key lifetime
Many providers expire idempotency keys after a window, for example 24 hours. Expiry bounds storage, but it creates a rule you must document: a retry after expiry is treated as new. In the schema above the key lives on the payment row, so the payment record would have to outlive the key, or you would move keys to a separate table you can purge. Whichever you choose, state the window in your API documentation so clients do not retry with an old key days later.
Summary of the design
- The client supplies a unique key per logical operation.
- The database enforces uniqueness on
(merchant_id, idempotency_key). - A request hash detects reuse of a key for a different request.
- In-progress and crashed requests are handled explicitly.
- Every downstream call, especially to the PSP, carries its own stable key.
Exercise
A client sends POST /payments with key K and an amount of 1000. The request times out. The client then sends the same key K with an amount of 2000. What should the server do, and why? Name the mechanism that detects this.
Show answer
The server should reject the second request with an error such as 422 or 409. The insert returns no row because (merchantid, K) already exists. The server loads the existing payment and finds that its stored requesthash differs from the hash of the new request. A reused key with different content is a client bug, so returning the original payment would hide it.
Exercise
Your service calls the PSP with a randomly generated idempotency key on each attempt, and retries up to four times on timeout. What can go wrong, and how do you fix it?
Show answer
If the first attempt reached the PSP and succeeded but the response was lost, each retry has a new key, so the PSP treats it as a new charge. The customer can be charged up to four times. Fix it by deriving one stable key from the payment ID and operation (for example "<payment_id>:authorize") and sending that same key on every attempt.