Deep Dive
high level designdistributed systemsreliability

Idempotency: How to Retry a Payment Without Charging Twice

The network fails after your server does the work but before the answer gets home, so the client retries — and a naive charge endpoint bills the card twice. Idempotency is the discipline that makes every retry safe.

·15 min read
Medium

A user taps Pay $500. Your server receives the request, calls the payment processor, the card is charged, the row is written — and then, on the way back, the response dies. A dropped connection, a load balancer that reaped an idle socket, a phone that slipped onto 3G in an elevator. The user’s screen spins, then times out.

They don’t know the money already left. They see a failure, so they do the only sane thing: they tap Pay $500 again. Now there are two charges for one order, an angry customer, and a chargeback with your name on it. Nobody wrote a bug. The code worked perfectly — twice.

Why retries are not optional

The instinct is to make the client “just not retry.” That instinct is wrong, and understanding why is the whole lesson.

When a request times out, the client learns exactly one thing: it didn’t get a response. It cannot tell why. The request may have been lost on the way out (never processed — safe to retry) or the response may have been lost on the way back (already processed — dangerous to retry). Both look identical from the outside: silence.

From here the members-only continuation builds the real mechanism: why HTTP’s method semantics promise idempotency but don’t enforce it, the production idempotency-key pattern with the naive-vs-fixed charge code and the atomic UNIQUE-claim trick, the messaging sibling (at-least-once delivery plus a consumer dedup table), how Stripe, AWS, PayPal, and Kafka do it in the wild, key retention and TTLs, plus an interview-corner challenge and a quiz to test yourself.

Members only

Keep reading with Premium

You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.