Video in progress

Strong Middle 🏗️ System design

In a payment service, a client got a timeout and resent the request. How do you guarantee the money isn't charged twice?

For each payment attempt the client sends an idempotency key, and the server stores it with a unique constraint and records the result. A repeated request doesn't open a new payment — it returns the stored result, or 409 if the first one hasn't finished yet.

📖 Answer

The table for storing keys:

CREATE TABLE payment_requests (
    idempotency_key text PRIMARY KEY,
    request_hash    text   NOT NULL,
    status          text   NOT NULL,   -- IN_PROGRESS, SUCCEEDED, FAILED
    payment_id      bigint,
    response        jsonb,
    created_at      timestamptz NOT NULL DEFAULT now()
);

The flow:

  1. Insert an IN_PROGRESS record with INSERT ... ON CONFLICT DO NOTHING. It was inserted — we continue.
  2. It wasn't inserted — the record exists. If it's SUCCEEDED or FAILED, the stored response is returned. If it's IN_PROGRESS — 409, and the client asks again later.
  3. If the request_hash differs (same key, different amount) — 422, that's a client error.
  4. The call to the bank or processor. Give them your own idempotency key too, so your retry doesn't create a duplicate on their side.
  5. The result is recorded.

The hardest spot is a timeout at step 4. You don't know whether the money was charged or not. Recording FAILED in this case is a mistake. The record stays in an UNKNOWN state, and a reconciliation job asks the provider for the payment status and then sets the final state.

Also:

  • keys are kept for a set period (for example, 24 hours);
  • the balance change is recorded in a ledger with a unique payment_id — a second layer of protection;
  • on the UI side, disabling the "Pay" button after the click is good, but it isn't protection, only convenience.