A payment endpoint dedups retries like this:
SELECT 1 FROM payments WHERE idem_key = $1;
-- if no row: charge card, then
INSERT INTO payments (idem_key, ...) ...;A client times out and retries, so two requests with the same key arrive together. What prevents a double charge?
Show answer
Answer
Inserting the key first makes the database pick one winner: the second insert hits the unique violation and does not charge. The row then records the in-flight state and later the stored response.
A transaction does not stop both SELECTs from seeing no row. In-memory sets miss retries routed to another server or after a restart. A plain index makes the race faster, not impossible.
Source: Designing robust and predictable APIs with idempotency, Brandur Leach, PostgreSQL Documentation: INSERT (ON CONFLICT)