Databases · Senior · Question 14 of 75
Why should the uniqueness of an idempotency key be enforced with a unique constraint rather than a 'check, then insert'?
- ✓Correct answer: Concurrent duplicates can both pass the check; the constraint makes exactly one insert succeed
- 2Checks don't work inside transactions
- 3Constraints are faster to write in code
Explanation
Insert the key first (ON CONFLICT DO NOTHING), and only the request that inserted it does the work. Others return the stored result.