← Back to SQL, page 22

sql-0432 · Easy fresher

Users who double-click 'Place order' sometimes create two identical orders. How do you prevent it at the database level?

Give each checkout attempt a unique token generated when the page loads, store it on the order with a UNIQUE constraint, and insert with ON CONFLICT DO NOTHING (or catch the violation) so the second click returns the first order. Disabling the button helps the user but cannot be trusted alone.

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