← Back to SQL, page 18

sql-0351 · Medium mid

A payment request may be retried by the client after a timeout. How do you make sure the customer is charged only once?

Require an idempotency key on each payment request and store it with a unique constraint alongside the result. A retry with the same key finds the existing row and returns the stored result instead of charging again. Insert the key before calling the payment provider, inside a transaction or with a pending status.

Full answer
text
payment_requests(idempotency_key TEXT PRIMARY KEY, customer_id, amount_cents,
                 status, provider_ref, response jsonb, created_at)

Flow:

  1. Client sends the key (a UUID it generated) with the request.
  2. 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.
  3. 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