Skip to content
Commitwise
Menu

A client retries a payment request after a timeout. How do you make sure the customer isn't charged twice?

BackendSenior

In shortMake the operation idempotent: the client sends a unique idempotency key with the request, the server stores the key with the request fingerprint and result in the same transaction as the work, and repeats return the stored result. Downstream calls to the payment provider carry their own idempotency key.

Model answer

A timeout doesn’t tell the client whether the payment happened, so retries are unavoidable. The server must make them safe.

  1. The client generates an idempotency key (a UUID) per logical operation, stores it with the pending action, and sends it on every retry: Idempotency-Key: 6f1a….
  2. The server claims the key atomically: insert (key, user_id, request_hash, status = IN_PROGRESS) with a unique constraint on (user_id, key). If the insert fails, the key exists:
    • completed: return the stored response (same status and body);
    • in progress: return 409 (or wait briefly), so two concurrent duplicates never both execute;
    • different request hash: return 422, the client reused a key for a different payment.
  3. Do the work and store the result in the same transaction as the business change (order marked paid, ledger entry), so a crash can’t leave a charged-but-unrecorded state. External calls happen outside the transaction, so record the state machine (created → provider called → succeeded) and resume it.
  4. Call the provider idempotently: payment providers accept their own idempotency key; derive it from yours, so retrying the provider call can’t double charge either.
  5. Expire keys after a window (24 hours to a few days), documented for clients.

Webhooks from the provider need the same treatment: dedupe by event id.

What they're looking for

Idempotency keys end to end, atomic storage of key and result, handling concurrent duplicates (in-progress state, unique constraint), fingerprint mismatch, key expiry, and idempotent calls to the provider.

Common mistakes

  • Checking for the key and doing the work in separate, non-atomic steps.
  • Generating the key on the server for each request.
  • Forgetting the call to the payment provider can also be retried.

More backend questions

Esc

Type to search the whole site.