Software engineering: make the second request safe

Lesson 3 of 3

The practical: idempotency plus a unique constraint

7 min

A retried payment should be the same payment. The client sends an idempotency key (a random token for that checkout attempt). The server stores the key with the charge. A second request with the same key returns the first result and does not charge again.

Clients forget, or a bug sends two requests before the first key is saved. A unique constraint on the key, or on the payment id, makes the database reject the duplicate insert. The application then treats that conflict as “we already have this payment,” not as a new sale.

Sleeping for three seconds, emailing a receipt, or logging both charges leaves the double charge in place.

Example

Pay is clicked twice. Both requests carry `Idempotency-Key: 8f3…`. The first insert succeeds and charges the card. The second hits the unique index on the key and returns the original order id. One charge.

Practice

Name the token and the database backstop.