The goal is idempotency: if the same payment request arrives twice (double click, retry after timeout, network glitch), the customer is charged only once. Frontend (React) - Disable the Pay button after the first click and show progress. - Generate an idempotency key (crypto.randomUUID()) when the checkout attempt starts and send it with every retry of that attempt in an Idempotency-Key header. - On timeout, poll the order or payment status (or retry with the same key) rather than starting a new payment. Backend (Spring Boot) 1. Create the order in state PENDING_PAYMENT with server-calculated totals; never trust prices sent by the client. 2. Store the idempotency key in a table with a unique constraint on (customerId, key) together with a hash of the request and the stored response. - If the key already exists with the same request: return the stored response. - If it exists but is still processing: return 409 or 202 with the current status. - If it exists with a different request body: reject with 422. 3. Call the payment gateway passing the same idempotency key — Stripe, Razorpay and others support this, so gateway-level duplicates are prevented too. 4. Update the order to PAID or FAILED in a transaction. Concurrency - Use optimistic locking (@Version on the Order entity) or a conditional update (UPDATE orders SET status = 'PAID' WHERE id = ? AND status = 'PENDING_PAYMENT') so only one transition succeeds. - The unique constraint on the idempotency key handles two simultaneous requests: one insert succeeds, the other gets a constraint violation and is treated as a duplicate. Webhooks - Payment providers confirm asynchronously. Verify the webhook signature, de-duplicate by the provider's event ID, and apply idempotent status updates. Treat the webhook as the authoritative confirmation, since the browser redirect may never arrive. Reliability - Publish "OrderPaid" events through the transactional outbox for fulfilment and emails. - A reconciliation job compares pending orders with the gateway's records and resolves stuck payments (capture, cancel or refund). Security and compliance: HTTPS, card data handled by the provider's hosted fields or SDK (reducing PCI DSS scope), and authorization checks so users can pay only for their own orders.
Ravindra Wadile · · 0 likes