Full answer
text
payment_requests(idempotency_key TEXT PRIMARY KEY, customer_id, amount_cents,
status, provider_ref, response jsonb, created_at)Flow:
- Client sends the key (a UUID it generated) with the request.
- Server does
INSERT ... ON CONFLICT (idempotency_key) DO NOTHING. If a row already existed, return its stored status and response; if it is still pending, tell the client to retry later. - For a new row, call the provider, passing the same key if the provider supports it, and update the row with the outcome.
The unique constraint closes the race where two identical retries arrive at the same moment: only one insert succeeds. Also check that a reused key comes with the same amount and customer, rejecting mismatches. Keys can expire after a retention period such as 24 hours.
Key points
- Client-generated idempotency keys
- Unique constraint on the key
- Return the stored result on retries
- Reject a reused key with different parameters
Common mistakes
- Deduplicating by amount and time window
- Calling the provider before recording the key
Follow-ups
- What if the server crashes after charging but before saving the result?
- How long should keys be kept?
Tips
- Say what the unique constraint prevents