Video in progress
How do you make an endpoint like "create a payment" idempotent?
The client sends a unique Idempotency-Key with each operation. The server runs the first request and stores the result under that key; if the same key comes again, it returns the stored response without redoing anything. Writing the key and doing the operation happen in one transaction, with a unique constraint.
📖 Answer
Why you need it: a mobile app sent a request, the network dropped, and no response came back. The app retries, and the server must not create a second payment.
The table:
create table idempotency_keys (
key varchar(100) primary key,
user_id bigint not null,
request_hash varchar(64) not null,
status varchar(20) not null, -- IN_PROGRESS / DONE
response jsonb,
created_at timestamptz not null default now()
);
The flow:
- Claim the key with
INSERT ... ON CONFLICT DO NOTHING, in theIN_PROGRESSstate. - If the insert succeeded, run the operation and store the response with
DONE. - If the key already existed:
DONE: the stored response is returned;IN_PROGRESS: 409 or "try again later";- a different
request_hash: 422, meaning a different request came with the same key.
There are subtle points too. Bind the key to the user, otherwise someone can get another user's response with that user's key. If you call an external provider, pass it your own idempotency key as well. Clean up keys after 24-72 hours. To avoid repeating this in every controller, you can pull it out into one place as an interceptor or an aspect.
Sign up to mark studied questions and save your progress.