Two requests with the same idempotency key arrive at the same time. How do you make sure only one runs?
Sketch your own answer first, then compare it with the one below.
A strong answer
A check and then an insert is a race. Both can see no key and both proceed. Make the database enforce it. Insert the key with a unique constraint as the first step of the transaction. The loser gets a conflict.
Then decide what the loser does. It can wait and return the winner's stored result, or return a conflict status that tells the client to retry later. Store a state with the key: in progress or done, along with the result. A crashed winner leaves a key stuck in progress, so give it a lease or a timeout after which another request may take over.
Also store a hash of the request. The same key with a different body is a client bug, and should be rejected rather than answered with the old result.
Sources
- Jayadeba Jena, Sanjay Dalal (2024). The Idempotency-Key HTTP Header Field.
- Martin Kleppmann (2017). Designing Data-Intensive Applications.