hebel. today · 18 November 202671 / 80
Technology · Software Architecture Patterns
Payment endpoints enforce idempotency through order-bound keys
Stripe, Adyen, and Square recommend random idempotency keys per request to protect against network retries, but this method fails when a user reloads a page or opens a second tab. Payment teams now link…
From 2 newsletters · 1 min read · one thing to try
Stripe, Adyen, and Square recommend random idempotency keys per request to protect against network retries, but this method fails when a user reloads a page or opens a second tab (The T-Shaped Dev). Payment teams now link the idempotency key to a server-created order ID instead of the individual click, ensuring that every retry for a single purchase uses the same key. This approach forces the payment provider to recognize subsequent attempts as replays of the original transaction, preventing duplicate charges (The T-Shaped Dev).
Engineers implement a partial unique index on the payments table using the SQL command CREATE UNIQUE INDEX one_live_payment_per_order ON payments (order_id) WHERE status <> 'declined'. This database constraint allows only one successful payment attempt per order, effectively acting as the final arbiter of state. When a server crash occurs before saving a result, a 30-second lease on the payment row allows a subsequent request to take over the attempt and re-send the original card details to the provider.
This design creates a reliable seam between internal state and external payment providers, mirroring how Netflix and Uber use API gateways to isolate internal services from unstable external traffic (Hands On System Design, Hands On System Design). By queuing receipts and events in the same database statement that marks a payment as successful, systems guarantee that customers receive exactly one confirmation for their purchase.
Try today · 15 min
Implement a partial unique index on your payments table to prevent duplicate charges per order.
Run the SQL command provided in the source to lock status-based payment attempts.
You need
- Access to your database schema
- The order_id column in your payments table
Steps
- Identify the payments table in your database schema.
- Verify that your payments table includes an order_id column.
- Execute the SQL command: CREATE UNIQUE INDEX one_live_payment_per_order ON payments (order_id) WHERE status <> 'declined';
- Test the constraint by attempting to insert two payments with the same order_id.