Idempotency: Sending the Same Request Twice Must Not Do It Twice
You send a request to create a payment. Nothing comes back, and your code times out. Maybe the payment never happened. Maybe it did, and only the reply got lost. From your side, both look the same.
What the word means
Idempotent means doing it again gives the same result as doing it once. Pressing a lift button five times still calls one lift. Adding an item to a cart five times gives five items. Retries are only safe for idempotent actions.
- GET, PUT and DELETE are idempotent. Sending them twice has the same effect as once.
- POST usually creates a new thing each time. Not idempotent.
Making POST safe
Many payment APIs, like Stripe, accept an Idempotency-Key header. You make up a unique value once per action. Send the same key on a retry, and the API returns the first result instead of creating it again.
POST /v1/payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: 3f9c1a52-8d4e-4b7a-9f21-6c0e5d8b2a17
{ "amount": 5000, "currency": "pkr", "order_id": "ORD-1042" }Do not make a new key inside the retry loop, or every retry looks new. No key support? Look it up first and create only if it is missing. If you truly cannot know, do not retry. Alert a human.