Video in progress
In a payment API, a client times out and resends the request. How do you design idempotency so the money isn't charged twice?
The client gives each operation a unique Idempotency-Key. The server stores the key together with a hash of the request and the result: the first request is executed, repeats get the stored response, and a concurrent repeat waits or gets a 409. The key and the business record are saved in one transaction.
📖 Answer
This is the distributed form of the command pattern: the request is an object, the key is its identifier, and the result is the stored response.
The table:
create table idempotency_key (
key varchar(64) primary key,
client_id bigint not null,
request_hash char(64) not null,
status varchar(16) not null, -- IN_PROGRESS, DONE
response_code int,
response_body jsonb,
created_at timestamptz not null default now()
);
The flow:
insert ... on conflict do nothing. If the insert succeeds, we are the first one, and the status isIN_PROGRESS.- If it doesn't insert, we read the existing row. If it is
DONEand therequest_hashmatches, we return the stored response. If the hash doesn't match, this is a different request with an old key: 422. If it isIN_PROGRESS, return 409 or wait briefly. - The business operation and moving the key to
DONEhappen in one local transaction.
The subtlest part is the external call. The money is charged at the provider, not in our database. If the request went to the provider but no response came back, the state is unknown. So:
- we pass the key to the provider as well (most payment providers accept an idempotency key);
- there is an
UNKNOWNstate, and a reconciliation job asks the provider to settle it; - keys stuck in
IN_PROGRESSfor a long time are checked separately, not blindly re-executed.
Design decisions to agree on with the teams:
- key scope:
client_id+ key, otherwise two clients' keys collide; - retention: 24 hours or 7 days. It should be longer than the client's retry policy;
- are error responses stored too? 4xx, yes (a repeat should get the same response); 5xx, usually no, so retrying is allowed.
You can do it in Redis too, but then the key and the business record aren't in one transaction, and a "key written, payment not written" state appears. Where money is involved, I choose the database.
Sign up to mark studied questions and save your progress.