What Is Idempotency? How APIs Stop Double Charges | Learn in 30 Seconds
Your checkout freezes. The customer taps Pay again. Did they just pay twice?
Here's the uncomfortable part: it usually isn't the customer's second tap that causes the duplicate. It's your HTTP client retrying a request that timed out. The payment went through — only the response got lost. The retry is behaving correctly. The API isn't.
Idempotency is the property that performing the same logical operation more than once produces the same intended effect as doing it once.
HOW IT WORKS
The client attaches a unique key to the operation:
Idempotency-Key: pay-abc123
First request: the server processes the payment, then stores the key alongside the result.
Retry with the same key: the server recognises it, and returns the stored result instead of charging again.
One payment. One record. One consistent response — no matter how many times the request arrives.
THE RULE PEOPLE GET BACKWARDS
Reuse the same key for every retry of the same operation. Generating a fresh key per attempt defeats the entire mechanism — each retry then looks like a brand-new payment, which is exactly the behaviour you were trying to prevent. The key identifies the *operation*, not the attempt.
WHAT IDEMPOTENCY DOESN'T SOLVE BY ITSELF
→ Concurrent requests with the same key arriving simultaneously — you need locking or a unique constraint, or two threads both see "no record yet"
→ Key expiry — how long do you honour a key? Too short and late retries double-charge; too long and you're storing keys forever
→ Partial failure — what if the payment succeeded but writing the result to your store didn't?
And no API is idempotent unless someone deliberately built it that way. `GET` and `PUT` are idempotent by specification; `POST` is not, which is precisely why payment APIs add a key header.
—
#Astmation — #software #systems, #automation, and #AI-powered #applications.
Build. Automate. Evolve.
https://astmation.com/
Watch on YouTube