Full answer
text
orders(id, customer_id, checkout_token TEXT UNIQUE, ...)
INSERT INTO orders (customer_id, checkout_token, ...) VALUES (:c, :token, ...)
ON CONFLICT (checkout_token) DO NOTHING
RETURNING id;If RETURNING yields no row, look up the existing order by token and return it, so both requests show the same confirmation page.
Why the database: two requests can arrive at different servers within milliseconds. Application checks ('does an order with this cart exist?') race, but a unique constraint is checked atomically. The same idea protects payments, sign-ups and any form that creates records.
Front-end measures (disabling the button, showing a spinner) reduce the frequency but do not cover retries from flaky networks or browser resubmits.
Key points
- A unique token per attempt
- UNIQUE constraint catches the second insert
- Return the existing order on conflict
- UI measures are not enough
Common mistakes
- Deduplicating by comparing order contents and times
- Relying only on disabling the button
Follow-ups
- How long should tokens remain valid?
- How does this relate to idempotency keys in APIs?
Tips
- Explain why application checks race