Idempotency keys for payment APIs

A retried request must not charge twice. A unique key and one transaction are enough to guarantee it.

Networks fail after the server has done the work but before the client sees the response. The client retries, and without protection the customer pays twice.

The contract

The client sends an Idempotency-Key header, a random UUID per logical operation. The server stores the key with the response it produced. A repeated key returns the stored response instead of running the operation again.

create table idempotency_keys (
  key        uuid primary key,
  request    jsonb not null,
  response   jsonb,
  created_at timestamptz not null default now()
);

Doing it in one transaction

Insert the key first with on conflict do nothing. If the insert affected no rows, someone already owns that key: return its stored response, or 409 if it is still running. Otherwise run the charge and save the response in the same transaction.

Two details matter in practice: compare the stored request with the new one and reject a reused key with a different body, and expire old keys so the table does not grow forever.