How would you design an idempotent payments API that clients can safely retry?

Short answer

Require an Idempotency-Key header on mutating requests, store the key with a request fingerprint and the resulting response in the same transaction as the business effect, return the stored response for repeated keys, reject reuse with different payloads, and handle in-flight duplicates with a lock or unique constraint.

Detailed answer

  1. Client generates a unique key (UUID) per logical operation and sends it on every retry.
  2. Server: INSERT INTO idempotency_keys (key, request_hash, status) VALUES (...) with a unique constraint.
    • If insert succeeds: process the payment, store the response, mark complete (same transaction where possible).
    • If the key exists and is complete: return the stored response.
    • If it exists with a different request hash: return 422 (key reuse).
    • If it exists and is in progress: return 409 or wait.
  3. Keys expire after a retention window (e.g. 24 hours to days).
  4. Downstream calls to payment providers also use idempotency keys.
CREATE TABLE idempotency_keys (
  key text PRIMARY KEY, request_hash text NOT NULL, status text NOT NULL,
  response jsonb, created_at timestamptz DEFAULT now()
);

Real-world example

Stripe's API documents this exact pattern with the Idempotency-Key header.

Follow-up questions

  • What if the server crashes after charging but before storing the response? (Store intent first; reconcile with provider status; outbox.)

What the interviewer expects

Concrete storage and concurrency handling, not just "use idempotency keys".

Common mistakes to avoid

Generating the key on the server, not scoping keys per client/merchant, ignoring concurrent duplicate requests.