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 SQL and Python snippets.
Why payments need idempotency
An operation is idempotent if doing it several times has the same effect as doing it once. Networks make this a requirement for payments. A client sends "charge $19.99", the server charges the card, and the response is lost. The client cannot tell whether the charge happened. If it retries without protection, the customer is charged twice.
The fix is an idempotency key. The client generates a unique value for each logical payment attempt and sends it with the request, usually in an Idempotency-Key header. The server uses that key to recognize a retry and return the original result instead of repeating the work.
Let the database decide
Checking "have I seen this key?" and then inserting is a race. Two concurrent retries can both pass the check. Instead, use a unique constraint and let the database settle it 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;The key is scoped to the merchant, so two merchants can use the same key string without colliding. If RETURNING gives a row, this request is new and the service proceeds. If it returns nothing, the key was used before.
Handling a repeated key
When no row comes back, the service loads the existing payment and compares request_hash with the hash of the incoming request. The hash is computed over the fields that define the request, such as amount, currency, and payment method.
The two outcomes differ:
| Situation | Hashes match? | Response |
|---|---|---|
| Genuine retry of a finished request | Yes | Return the stored result, with the same status code and body as the first time |
| Genuine retry while the first is still running | Yes | Return a conflict or "in progress" response so the client retries later |
| Key reused for a different request | No | Reject with a client error such as 422 |
Rejecting a mismatch matters. Without it, a client bug that reuses a key for a new amount would silently return the old payment, and the customer would never be charged the new amount.
Common errors
- Check-then-insert. Reading first and inserting later leaves a race window. Rely on the constraint.
- Global keys. A key unique across all merchants lets one merchant's key block another's. Scope by merchant.
- Skipping the hash. Without
request_hash, you cannot detect key reuse. - Not storing the response. If the first attempt finished, a retry should receive the same outcome, not a new computation.
- Keys that never expire. Keep them long enough to cover realistic retry windows, often 24 hours or more, then clean them up by policy.
Exercise
Two identical requests with the same idempotency key arrive at the same moment. How does the design above ensure only one payment is created?
Show answer
Both run the INSERT ... ON CONFLICT DO NOTHING. The unique constraint on (merchantid, idempotencykey) lets the database accept only one of them atomically. The first gets a row back and processes the payment. The second gets no row, loads the existing payment, finds the hashes match, and returns the stored result or an "in progress" response.
Exercise
A client reuses a key but changes the amount from 1999 to 2999. What should the service do, and why?
Show answer
It should reject the request with a client error. The request_hash differs from the stored one, so returning the old payment would hide the fact that the new amount was never charged.