Video in progress
In a payment service, a client got a timeout and resent the request. How do you guarantee the money isn't charged twice?
For each payment attempt the client sends an idempotency key, and the server stores it with a unique constraint and records the result. A repeated request doesn't open a new payment — it returns the stored result, or 409 if the first one hasn't finished yet.
📖 Answer
The table for storing keys:
CREATE TABLE payment_requests (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
status text NOT NULL, -- IN_PROGRESS, SUCCEEDED, FAILED
payment_id bigint,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
The flow:
- Insert an
IN_PROGRESSrecord withINSERT ... ON CONFLICT DO NOTHING. It was inserted — we continue. - It wasn't inserted — the record exists. If it's
SUCCEEDEDorFAILED, the stored response is returned. If it'sIN_PROGRESS—409, and the client asks again later. - If the
request_hashdiffers (same key, different amount) —422, that's a client error. - The call to the bank or processor. Give them your own idempotency key too, so your retry doesn't create a duplicate on their side.
- The result is recorded.
The hardest spot is a timeout at step 4. You don't know whether the money was charged or not. Recording FAILED in this case is a mistake. The record stays in an UNKNOWN state, and a reconciliation job asks the provider for the payment status and then sets the final state.
Also:
- keys are kept for a set period (for example, 24 hours);
- the balance change is recorded in a ledger with a unique
payment_id— a second layer of protection; - on the UI side, disabling the "Pay" button after the click is good, but it isn't protection, only convenience.
Sign up to mark studied questions and save your progress.