System Design

C19

Payments

Design a payment system: take a card, charge exactly once, and keep a ledger that always balances.

Not startedSaved in this browser only.
  1. 1A timeout is an unknown outcome. Look the key up at the provider before any retry, and send again only with the same key.
  2. 2The key travels end to end: client to service, service to provider, service to ledger. Each hop has its own unique key.
  3. 3Replies, webhooks and lookups pass one gate that only moves a payment forward. Order and copies stop mattering.
  4. 4The ledger hears about money through an outbox, and a nightly match with the settlement file proves it.
C19
    A

    The prompt and requirements

    questions first, then numbers
    "Design a payment system: take a card, charge exactly once, and keep a ledger that always balances."
    questionanswer assumed
    Do we talk to banks?No. One provider runs the card network. Others can join behind the same interface.
    How many payments?10 million a day, with a sale peak of 10 times the average.
    One step or two?Authorize at checkout, capture when the goods ship.
    Refunds?Full and partial, from us or from the provider's dashboard.
    Do we store cards?No. The provider vaults them. We keep a token and the last 4 digits.
    How does the provider report?A reply, webhooks, a lookup by key, and a nightly settlement file.
    Provider latency?About 2 s per call, assumed. Use the provider's own figures.
    requirementtarget
    Double charges0, under any fault the provider makes
    Ledger balanceEvery entry sums to 0, always
    Peak1,157 payments a second
    Unknown outcomesResolved without a person
    SettlementEvery line matched each night, or a case
    Card data at restNone in our systems
    AuditEvery fact from the provider kept, with its source

    I charge each payment once, whatever the provider does, and a ledger that sums to 0 records every cent.

    B

    Estimates

    arithmetic shown
    average
    10,000,000 ÷ 86,400 s ≈ 116 a second
    peak
    116 × 10 ≈ 1,157 a second
    in flight
    1,157 × 2 calls × 2 s ≈ 4,630 calls open at once
    webhooks in
    1,157 × 2 ≈ 2,315 a second
    ledger writes
    1 entry per capture: 1,157 a second at peak
    storage
    10 million × 2.4 kB = 24 GB a day, 8.8 TB a year

    Bytes per payment were measured in the lab, with indexes, in both databases.

    The peak is about 1,157 payments a second. The hard part is thousands of calls in flight, so I hold no transaction across a call.

    C

    API

    methods, bodies, status codes
    callresult
    POST /paymentsToken, amount. 201, or 200 for the same key. 422 if the key had another body.
    POST /payments/:id/authorize200 authorized or failed. 202 unknown.
    POST /payments/:id/captureAmount. 200, or 202 unknown. 409 wrong state.
    POST /payments/:id/refundsAmount. 200, or 202 unknown. 409 wrong state, 422 over the capture.
    GET /payments/:idState, amounts, refunds.
    POST /webhooks/provider200 after the commit. 401 bad signature.

    The client makes one key per purchase. The header is Idempotency-Key.

    Every POST takes an idempotency key. A timeout at the provider is a 202, not an error: the client polls the state.

    D

    Data model

    entities, then SQL
    paymentsPKidUQclient_keyfrom the clienttokennever a cardstate5 statescapturedcentsrefundedconfirmedrefund_heldaskedCHECK refunds <= capturedprovider_callsPKkeyauth:<id>FKpayment_idopstatuspending, donenext_try_atsweepercommitted before the callprovider_factsPKidevent idFKpayment_idsourcereply, webhook…op, outcomestatusparked, stale…a copy of an id is droppedrefundsPKidUQclient_keyUQcall_keyUQprovider_refone row per refundoutboxUQkeyledger keykindcapture, refundexternal_refpublished_atcommits with the stateledger, 2 tablesUQidempotency_keyUQexternal_refaccount_idamount+ or -each entry sums to 0
    money
    bigint cents. Floats never touch an amount.
    facts
    Kept forever: they are the audit of what the provider said.
    growth
    About 2.4 kB per payment. Partition facts and calls by month.
    facts, outbox, settlementsql
    -- Everything the provider told us, by any path. The primary key drops a copy.
    CREATE TABLE provider_facts (
      id         text   PRIMARY KEY1, -- webhook event id, reply:<key>, lookup:<key>
      seq        bigint GENERATED ALWAYS AS IDENTITY,
      payment_id bigint NOT NULL REFERENCES payments (id),
      source     text   NOT NULL CHECK (source IN ('reply', 'webhook', 'lookup')),
      op         text   NOT NULL,
      outcome    text   NOT NULL,
      call_key   text   NOT NULL,
      ref        text   NOT NULL,
      target     text   NOT NULL,
      amount     bigint NOT NULL,
      status     text   NOT NULL DEFAULT 'new'
        CHECK (status IN ('new', 'parked', 'applied', 'stale'))
    );
    CREATE INDEX provider_facts_open ON provider_facts (payment_id)
      WHERE status IN ('new', 'parked');
    
    -- Commits with the state change. The relay copies it to the ledger.
    CREATE TABLE outbox (
      id           bigint  GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      key          text    NOT NULL UNIQUE2, -- the ledger entry's key
      kind         text    NOT NULL CHECK (kind IN ('capture', 'refund')),
      merchant_id  bigint  NOT NULL,
      amount       bigint  NOT NULL,
      currency     char(3) NOT NULL,
      external_ref text    NOT NULL,        -- matched at reconciliation
      published_at timestamptz
    );
    CREATE INDEX outbox_unsent ON outbox (id) WHERE published_at IS NULL;
    
    CREATE TABLE settlement_lines (
      ref    text   PRIMARY KEY,
      file   text   NOT NULL,
      amount bigint NOT NULL
    );
    
    -- What the nightly match could not explain. A person works these.
    CREATE TABLE recon_cases (
      ref    text PRIMARY KEY,
      result text NOT NULL
    );
    1. 1A second copy of an event hits this key and is dropped.
    2. 2The key the relay gives the ledger. The last hop of exactly-once.
    payments, calls, refundssql
    -- The card number never reaches these tables. The browser sends it to the
    -- provider and gets a token. Amounts are integer minor units (cents).
    CREATE TABLE payments (
      id          bigint  GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      client_key  text    NOT NULL UNIQUE1,  -- the client's Idempotency-Key
      fingerprint text    NOT NULL,         -- the request it was first used for
      merchant_id bigint  NOT NULL,
      token       text    NOT NULL,         -- the provider's token for the card
      card_last4  char(4) NOT NULL,         -- enough for a receipt
      amount      bigint  NOT NULL CHECK (amount > 0),
      currency    char(3) NOT NULL,
      state       text    NOT NULL DEFAULT 'created' CHECK (state IN
        ('created', 'authorized', 'captured', 'refunded', 'failed')),
      auth_ref    text,                     -- the provider's authorization id
      capture_ref text,                     -- the provider's capture id
      captured    bigint  NOT NULL DEFAULT 0,
      refunded    bigint  NOT NULL DEFAULT 0, -- confirmed by the provider
      refund_held bigint  NOT NULL DEFAULT 0, -- asked for, not confirmed yet
      CHECK (captured <= amount),
      CONSTRAINT refund_limit CHECK (refunded + refund_held <= captured)2
    );
    
    -- One row per provider call, committed before the call. The key comes from
    -- our row, so a retry sends the same key and a crash leaves a row to resolve.
    CREATE TABLE provider_calls (
      key         text        PRIMARY KEY,
      payment_id  bigint      NOT NULL REFERENCES payments (id),
      op          text        NOT NULL
        CHECK (op IN ('authorize', 'capture', 'refund')),
      amount      bigint      NOT NULL,
      status      text        NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending', 'done'))3,
      attempts    int         NOT NULL DEFAULT 1,
      next_try_at timestamptz NOT NULL DEFAULT now()
    );
    CREATE INDEX provider_calls_due ON provider_calls (next_try_at)
      WHERE status = 'pending';
    
    CREATE TABLE refunds (
      id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      client_key   text   UNIQUE,  -- NULL when the provider's dashboard started it
      call_key     text   UNIQUE,  -- the provider's idempotency key
      payment_id   bigint NOT NULL REFERENCES payments (id),
      amount       bigint NOT NULL CHECK (amount > 0),
      status       text   NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending', 'succeeded', 'failed')),
      provider_ref text   UNIQUE
    );
    1. 1The first hop of the key: a copy of the request finds this row.
    2. 2Confirmed refunds plus asked refunds never pass the capture, whatever the concurrency.
    3. 3A pending row means a call may have happened. The sweeper reads these.

    A payment has one intent row per provider call and one fact row per report. The outbox commits with the state, and the ledger is a separate database.

    E

    The architecture

    click a step; its path lights up
    Browserhosted fieldPayment serviceN copies, statelessSweeperunknown callsRelayN, SKIP LOCKEDPostgrespayments, facts, outboxLedgerits own databaseProvidercard networkNightly jobsettlement file

    Step 1: Create

    • The browser sends the card to the hosted field and gets a token.
    • POST the token, the amount and an Idempotency-Key. The unique client key makes one row.

    If it fails

    A copy of the request finds the first row and returns it. A card number in the request is refused.

    The service calls the provider with no transaction open. Three kinds of report reach one gate, and a relay feeds the ledger.

    F

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresUnique keys and ON CONFLICT DO NOTHINGOne payment, one intent, one fact, one outbox event per key.Idempotent APIs
    PostgresSELECT FOR UPDATE on the paymentFacts for one payment apply one at a time.Per-entity ordering
    PostgresA transaction across rowsState, fact and outbox event commit together.Every multi-row change
    PostgresCHECK constraintsRefunds stay within the capture; the state is one of 5 values.Balances, stock
    PostgresFOR UPDATE SKIP LOCKEDN relays share the outbox.Job queues
    PostgresPartial indexesPending calls and unsent events stay cheap to find.Queues, outboxes
    PostgresDeferred constraint triggerEvery ledger entry sums to 0 at commit.Rules across rows
    PostgresFULL OUTER JOINMatches the settlement file with the ledger, both ways.Any reconciliation
    ServiceHMAC check in constant timeA forged webhook cannot move a payment.Signed callbacks
    ProviderIdempotency keys, for a windowA copy of a call inside the window applies once.Any external write
    ProviderLookup by keyTurns an unknown outcome into a known one.Any timeout
    ProviderTokens, hosted card fieldCard data stays out of our systems.PCI scope
    ProviderSettlement fileAn independent record of the money.Audit

    Postgres gives me unique keys at every hop, a row lock that orders facts, and an outbox that commits with the state. The provider gives me keys, a lookup and a file.

    G

    The state machine

    authorize, capture, refund
    createdauthorizedcapturedrefunded✕ failedholdcapturerefunds reachthe capturea capture fact that arrives firstdeclinedcapture refusedpartial refund:stays capturedno fact moves a payment back
    factfromtoledger
    authorizedcreatedauthorizednothing
    declinedcreatedfailednothing
    capturedcreated, authorizedcapturedclearing to merchant
    capture refusedauthorizedfailednothing
    refundcapturedcapturedmerchant to clearing
    last refundcapturedrefundedmerchant to clearing
    any fact, any other stateanyno changenothing

    A refund that arrives while the state is created or authorized is parked, not refused.

    Authorize places a hold and moves no money. Capture moves money and writes the ledger. A partial refund leaves the state at captured.

    H

    Deep dive: keys, end to end

    one key per hop, none made per attempt
    hopkeystops
    Client to serviceIdempotency-KeyDouble click, 2 tabs, a retry after a timeout
    Service to providerauth:<id>, capture:<id>, refund:<id>A resend after a timeout, a slow request
    Provider to serviceevent idWebhook copies
    Service to ledgercapture:<id>, refund:<ref>A relay that crashed before its mark
    Provider file to ledgerprovider refA file loaded twice
    design without a ruleholdschargestaken
    Client sends no key: 2 tabs make 2 payments22$200.00
    Service retries a timeout with a new key20$0.00
    Service retries with the same key after the window, no lookup20$0.00

    Recorded controls against the fake provider. A hold on a card lowers the customer's credit until it expires, so 2 holds are a defect even with 0 charges.

    one provider callpseudo code
    perform(call):
      key = derived from our row1           // auth:<payment id>
      COMMIT intent row2, status pending
      IF the row exists: STOP               // a copy of this request3
      outcome = provider(call, key)         // no transaction open4
      IF timeout: answer 202, STOP          // the intent stays pending
      report(reply)                         // through the gate
    1. 1Not a random value per attempt. Every retry, from any process, sends the same key.
    2. 2It commits before the call, so a crash cannot hide a call.
    3. 3A second tab gets no second call. It reads the state.
    4. 4At peak about 4,630 calls are open. A transaction per call would hold a connection and a row lock for seconds.
    Tested source Go: perform · Go: the provider interface · SQL: intent
    Go: performgo
    // perform commits an intent, calls the provider with no transaction open, and passes the reply
    // through the gate. If the intent exists, this request is a copy and sends nothing.
    func (s *Service) perform(ctx context.Context, c Call) (Payment, error) {
      tag, err := s.DB.Exec(ctx, q["intent"], c.Key, c.Payment, c.Op, c.Amount, s.Grace.String())
      if err != nil {
        return Payment{}, fmt.Errorf("write intent %s: %w", c.Key, err)
      }
      if tag.RowsAffected() == 0 {
        return s.Get(ctx, c.Payment)
      }
      if s.CrashAfterIntent {
        s.CrashAfterIntent = false
        return Payment{}, ErrCrashed
      }
      if err := s.send(ctx, c); err != nil {
        return Payment{}, err
      }
      return s.Get(ctx, c.Payment)
    }
    
    func (s *Service) send(ctx context.Context, c Call) error {
      out, err := s.dial(ctx, c)
      if errors.Is(err, ErrTimeout) {
        return fmt.Errorf("%w: %s", ErrUnknown, c.Key) // the intent stays pending
      }
      if err != nil {
        return fmt.Errorf("call %s: %w", c.Key, err)
      }
      if s.CrashAfterCall {
        s.CrashAfterCall = false
        return ErrCrashed
      }
      _, err = s.Report(ctx, Fact{ID: "reply:" + c.Key, Source: "reply", Outcome: out})
      return err
    }
    
    Go: the provider interfacego
    // Provider is what the service needs from a card provider. Each call carries a key the provider
    // keeps for a limited window. A timeout returns ErrTimeout and says nothing about the outcome.
    type Provider interface {
      Authorize(ctx context.Context, c Call) (Outcome, error)
      Capture(ctx context.Context, c Call) (Outcome, error)
      Refund(ctx context.Context, c Call) (Outcome, error)
      // Lookup returns the outcome of the call with this key, or ErrNotFound.
      Lookup(ctx context.Context, key string) (Outcome, error)
    }
    
    SQL: intentsql
    -- Commit this before the call. 0 rows: the call was already made or is in flight.
    INSERT INTO provider_calls (key, payment_id, op, amount, next_try_at)
    VALUES ($1, $2, $3, $4, now() + $5::interval)
    ON CONFLICT (key) DO NOTHING;
    retry methodstatus
    New key per attemptNot approved
    Same key, blind retryInside the window
    Key from our row, lookup firstApproved

    The client key makes one payment. A key derived from our row makes one provider call. The entry key makes one ledger entry.

    I

    Deep dive: the unknown outcome

    a timeout says nothing about the charge
    Request lostserviceproviderlook up: not found → send✕timeoutlook up the keynot foundsend, same keyonceReply lostserviceproviderlook up: found → send nothingonce✕timeoutlook up the keyfound: the resultthe gate applies it; a blindretry past the key windowcharges againRequest slowserviceprovidernot found → send; key stops the copytimeoutlook upnot foundsend, same keyoncefirst copy lands: key seen
    the sweeperpseudo code
    resolve():
      FOR each pending call past its lease1:
        found = provider.lookup(key)
        IF found: report(found)             // send nothing2
        IF not found: send with the same key3
        IF the lookup timed out: try next sweep
    1. 1A lease stops 2 sweepers and a running call from working on the same row.
    2. 2The provider already acted. The gate records the outcome.
    3. 3The first copy may still land. The key makes it a copy, not a second call.
    Tested source Go: resolve · SQL: claim due calls
    Go: resolvego
    // Resolve works every call whose outcome is unknown. It asks the provider first: a key can pass
    // out of the provider's window, and a blind retry after that charges again. Only a call the
    // provider has no record of is sent again, with the same key, in case the first copy is still
    // on its way. It returns how many calls reached a final outcome.
    func (s *Service) Resolve(ctx context.Context) (int, error) {
      rows, err := s.DB.Query(ctx, q["claim_due"], s.Lease.String())
      if err != nil {
        return 0, fmt.Errorf("claim calls: %w", err)
      }
      var due []Call
      var c Call
      var auth, capture *string
      if _, err := pgx.ForEachRow(rows, []any{&c.Key, &c.Op, &c.Payment, &c.Amount, &c.Token, &c.Currency, &auth, &capture}, func() error {
        call := c
        if c.Op == OpCapture && auth != nil {
          call.Target = *auth
        }
        if c.Op == OpRefund && capture != nil {
          call.Target = *capture
        }
        if c.Op != OpAuthorize {
          call.Token = ""
        }
        due = append(due, call)
        return nil
      }); err != nil {
        return 0, fmt.Errorf("claim calls: %w", err)
      }
      resolved := 0
      for _, c := range due {
        out, err := s.Provider.Lookup(ctx, c.Key)
        switch {
        case errors.Is(err, ErrTimeout):
          continue // still unknown: the next sweep tries again
        case errors.Is(err, ErrNotFound):
          if err := s.send(ctx, c); errors.Is(err, ErrUnknown) {
            continue
          } else if err != nil {
            return resolved, err
          }
        case err != nil:
          return resolved, fmt.Errorf("look up %s: %w", c.Key, err)
        default:
          if _, err := s.Report(ctx, Fact{ID: "lookup:" + c.Key, Source: "lookup", Outcome: out}); err != nil {
            return resolved, err
          }
        }
        resolved++
      }
      return resolved, nil
    }
    
    SQL: claim due callssql
    -- A sweeper claims a call for one lease, so 2 sweepers do not work on the same call.
    UPDATE provider_calls c
    SET attempts = attempts + 1, next_try_at = now() + $1::interval
    FROM payments p
    WHERE p.id = c.payment_id AND c.status = 'pending' AND c.next_try_at <= now()
    RETURNING c.key, c.op, c.payment_id, c.amount, p.token, p.currency, p.auth_ref, p.capture_ref;
    on a timeoutstatus
    Mark the payment failedNot approved
    Show the customer an error, ask to pay againNot approved
    Wait for a webhook onlyNot approved
    Answer 202, then look up, then resend with the same keyApproved

    Tested: each of 3 faults on each of 3 calls, and a crash at 2 points around each call. Each case ends with one effect at the provider.

    A timeout does not mean failed. I look the key up first, because the provider may have charged, and I send again only if it has no record.

    J

    Deep dive: webhooks

    late, duplicated, out of order
    Replythe call returnedWebhooklate, copied, reorderedLookupthe sweeper askedThe gate1 lock the payment2 drop a seen id3 apply open facts, parents first4 close the callpayments DBpaymentsprovider_factsprovider_callsoutboxone transactionRelayat least onceledger DBentry key: onceentries sum to 0the T9 ledger
    the gatepseudo code
    report(fact):
      BEGIN
        lock the payment row1
        insert fact; id seen: duplicate2, STOP
        FOR each open fact, parents first3:
          apply: move the state forward, or
            stale4:  the payment moved past it
            parked: its parent has not arrived
          a capture or refund writes the outbox
          close the provider call5
      COMMIT
    1. 1Reports for one payment line up here. Reports for other payments run in parallel.
    2. 2The id is the primary key of the fact table.
    3. 3An authorization, then a capture, then refunds. A parked refund runs in the transaction that brings its capture.
    4. 4The fact is kept for the audit and changes nothing.
    5. 5A webhook closes a pending call, so the sweeper has less work.
    Tested source Go: the gate · Go: webhook · SQL: open facts
    Go: the gatego
    // Report is the gate. Replies, webhooks and lookups all pass through it, one at a time per
    // payment. It stores the fact, then applies every open fact of the payment, parents first.
    func (s *Service) Report(ctx context.Context, f Fact) (verdict string, err error) {
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        var p Payment
        if err := tx.QueryRow(ctx, q["lock_payment"], f.Payment).Scan(p.dest()...); err != nil {
          return fmt.Errorf("lock payment %d: %w", f.Payment, err)
        }
        tag, err := tx.Exec(ctx, q["put_fact"], f.ID, f.Payment, f.Source, f.Op, f.Status, f.Key, f.Ref, f.Target, f.Amount)
        if err != nil {
          return fmt.Errorf("store fact %s: %w", f.ID, err)
        }
        if tag.RowsAffected() == 0 {
          verdict = Duplicate
          return nil
        }
        rows, err := tx.Query(ctx, q["open_facts"], f.Payment)
        if err != nil {
          return fmt.Errorf("read open facts: %w", err)
        }
        open, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Fact, error) {
          var o Fact
          err := r.Scan(&o.ID, &o.Source, &o.Op, &o.Status, &o.Key, &o.Ref, &o.Target, &o.Amount)
          o.Payment = f.Payment
          return o, err
        })
        if err != nil {
          return fmt.Errorf("read open facts: %w", err)
        }
        for _, o := range open {
          v, err := s.apply(ctx, tx, &p, o)
          if err != nil {
            return err
          }
          if _, err := tx.Exec(ctx, q["set_fact"], o.ID, v); err != nil {
            return fmt.Errorf("mark fact %s: %w", o.ID, err)
          }
          if v != Parked {
            if _, err := tx.Exec(ctx, q["call_done"], o.Key); err != nil {
              return fmt.Errorf("close call %s: %w", o.Key, err)
            }
          }
          if o.ID == f.ID {
            verdict = v
          }
        }
        return s.save(ctx, tx, &p)
      })
      return verdict, err
    }
    
    // apply moves the payment forward by one fact, or leaves it alone. No fact moves a payment back.
    func (s *Service) apply(ctx context.Context, tx pgx.Tx, p *Payment, f Fact) (string, error) {
      switch {
      case f.Op == OpAuthorize && f.Status == Succeeded:
        p.AuthRef = f.Ref
        if p.State != Created {
          return Stale, nil
        }
        p.State = Authorized
      case f.Op == OpAuthorize:
        if p.State != Created {
          return Stale, nil
        }
        p.State = Failed
      case f.Op == OpCapture && f.Status == Succeeded:
        if p.State != Created && p.State != Authorized {
          return Stale, nil
        }
        p.State, p.Captured, p.CaptureRef = Captured, f.Amount, f.Ref
        return Applied, s.emit(ctx, tx, "capture:"+strconv.FormatInt(p.ID, 10), "capture", p, f)
      case f.Op == OpCapture:
        if p.State != Authorized {
          return Stale, nil
        }
        p.State = Failed
      case f.Op == OpRefund && (p.State == Created || p.State == Authorized):
        return Parked, nil // the capture has not reached us yet
      case f.Op == OpRefund && p.State == Failed:
        return Stale, nil
      case f.Op == OpRefund:
        return s.applyRefund(ctx, tx, p, f)
      }
      return Applied, nil
    }
    
    Go: webhookgo
    // HandleWebhook checks the signature and passes the event through the gate. The caller answers
    // 200 only after this returns, so the provider sends it again if the commit failed.
    func (s *Service) HandleWebhook(ctx context.Context, body []byte, sig string) (string, error) {
      if !hmac.Equal([]byte(sig), []byte(signature(s.Secret, body))) {
        return "", ErrBadSignature
      }
      var e Event
      if err := json.Unmarshal(body, &e); err != nil {
        return "", fmt.Errorf("decode webhook: %w", err)
      }
      return s.Report(ctx, Fact{ID: e.ID, Source: "webhook", Outcome: e.Outcome})
    }
    
    SQL: open factssql
    -- One fact at a time per payment. Replies, webhooks and lookups all queue on this row.
    SELECT id, merchant_id, token, amount, currency, state, coalesce(auth_ref, ''),
           coalesce(capture_ref, ''), captured, refunded, refund_held
    FROM payments WHERE id = $1 FOR UPDATE;
    
    INSERT INTO provider_facts (id, payment_id, source, op, outcome, call_key, ref, target, amount)
    VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
    ON CONFLICT (id) DO NOTHING;
    
    -- Parents first: an authorization, then a capture, then refunds, in arrival order.
    SELECT id, source, op, outcome, call_key, ref, target, amount
    FROM provider_facts
    WHERE payment_id = $1 AND status IN ('new', 'parked')
    ORDER BY CASE op WHEN 'authorize' THEN 0 WHEN 'capture' THEN 1 ELSE 2 END, seq;
    arrivalverdicteffect
    First report of a factappliedState moves; outbox if money moved
    A copy of an eventduplicateNothing
    Reply after the webhookstaleNothing
    Authorized after capturedstaleStores the auth ref
    Refund before captureparkedApplies when the capture arrives
    Bad signaturerefused401, no row
    order handlingstatus
    Apply in arrival orderNot approved
    Trust a sequence number from the providerIf it has one
    Refuse an early event, so it is sent againRetries are bounded
    Store every fact, apply by a fixed rankApproved

    Tested: all 24 orders of 4 events, then 300 random orders with copies. Each one ended in the same row and the same money.

    A webhook is a report, not a command. It passes the same gate as a reply, so a copy is dropped, a late event is stale and an early refund waits.

    K

    Deep dive: outbox and nightly match

    the ledger hears once, and the file checks it
    outbox to ledgerpseudo code
    relay(batch):
      BEGIN
        events = oldest unsent, SKIP LOCKED1
        post each to the ledger, key = event key2
        mark them published
      COMMIT                                // a crash sends them again3
    1. 1N relays take different events.
    2. 2The ledger returns the first entry for a key it has seen.
    3. 3The post and the mark are in 2 databases, so delivery is at least once. The key gives one effect.
    Tested source Go: relay · SQL: outbox
    Go: relaygo
    // Relay copies up to n outbox events to the ledger and returns how many it posted. Delivery is at
    // least once: a crash before the commit sends the same events again. The entry key makes a copy
    // change nothing, so the ledger applies each event once.
    func (s *Service) Relay(ctx context.Context, n int) (sent int, err error) {
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        rows, err := tx.Query(ctx, q["next_events"], n)
        if err != nil {
          return fmt.Errorf("read outbox: %w", err)
        }
        var ev event
        var ids []int64
        var entries []ledger.Entry
        if _, err := pgx.ForEachRow(rows, []any{&ev.id, &ev.key, &ev.kind, &ev.merchant, &ev.amount, &ev.currency, &ev.ref}, func() error {
          ids = append(ids, ev.id)
          entries = append(entries, ev.entry(s.clearing(ev.ref)))
          return nil
        }); err != nil {
          return fmt.Errorf("read outbox: %w", err)
        }
        for _, e := range entries {
          if _, err := s.Ledger.Post(ctx, e); err != nil {
            return fmt.Errorf("post %s: %w", e.Key, err)
          }
        }
        if s.CrashAfterPost && len(ids) > 0 {
          s.CrashAfterPost = false
          return ErrRelayCrashed // the marks roll back: the events stay unsent
        }
        if _, err := tx.Exec(ctx, q["mark_published"], ids); err != nil {
          return fmt.Errorf("mark published: %w", err)
        }
        sent = len(ids)
        return nil
      })
      return sent, err
    }
    
    SQL: outboxsql
    -- The same transaction as the state change: the event exists if and only if the change does.
    INSERT INTO outbox (key, kind, merchant_id, amount, currency, external_ref)
    VALUES ($1, $2, $3, $4, $5, $6)
    ON CONFLICT (key) DO NOTHING;
    
    SELECT id, key, kind, merchant_id, amount, currency, external_ref
    FROM outbox
    WHERE published_at IS NULL
    ORDER BY id
    LIMIT $1
    FOR UPDATE SKIP LOCKED;
    
    UPDATE outbox SET published_at = now() WHERE id = ANY($1);
    the nightly jobpseudo code
    nightly(file):
      load lines; a seen ref changes nothing
      match all files with the ledger, both ways1
      IF a line is missing in the ledger:
        resolve open calls2, drain the outbox
        match again
      what is left becomes a case3
    1. 1A full outer join shows lines each side lacks. An inner join hides them.
    2. 2A lost reply and a lost webhook leave a pending call. The file reveals it, and the sweeper closes it.
    3. 3A person works it. The job never edits the ledger to force a match.
    Tested source Go: reconcile
    Go: reconcilego
    // Reconcile loads a settlement file and matches every file so far with the ledger, both ways. A
    // line missing in the ledger means a fact never reached us, so it resolves open calls, drains
    // the outbox and matches again. What is left becomes a case. A capture missing at the provider
    // is a timing difference until a later file carries it.
    func (s *Service) Reconcile(ctx context.Context, file string, lines []ledger.ReportRow) (ReconReport, error) {
      var rep ReconReport
      for _, l := range lines {
        if _, err := s.DB.Exec(ctx, q["load_line"], l.Ref, file, l.Amount); err != nil {
          return rep, fmt.Errorf("load line %s: %w", l.Ref, err)
        }
      }
      var err error
      if rep.First, err = s.match(ctx); err != nil {
        return rep, err
      }
      rep.Final = rep.First
      if hasResult(rep.First, "missing in the ledger") {
        if rep.Healed, err = s.Resolve(ctx); err != nil {
          return rep, err
        }
        if _, err := s.DrainOutbox(ctx); err != nil {
          return rep, err
        }
        if rep.Final, err = s.match(ctx); err != nil {
          return rep, err
        }
      }
      if _, err := s.DB.Exec(ctx, q["clear_cases"]); err != nil {
        return rep, fmt.Errorf("clear cases: %w", err)
      }
      for _, r := range rep.Final {
        if r.Result == "matched" {
          continue
        }
        rep.Cases++
        if _, err := s.DB.Exec(ctx, q["open_case"], r.Ref, r.Result); err != nil {
          return rep, fmt.Errorf("open case %s: %w", r.Ref, err)
        }
      }
      return rep, nil
    }
    
    refledgerfilefirst matchafter repair
    cap_10$30.00$30.00missing in the ledgermatched
    cap_13$15.00nonemissing at the providermissing at the provider
    cap_3$40.00$40.00matchedmatched
    cap_7$25.00$24.00amounts differamounts differ
    re_4-$10.00-$10.00matchedmatched

    Recorded: 1 line repaired by a lookup, 2 left. A capture missing at the provider is a capture after the cut-off; it matches on the next file.

    how to reach the ledgerstatus
    Write both databases from the serviceNot approved
    Outbox, relay, entry keyApproved
    Ledger tables in the payments databaseUntil the ledger needs its own scale

    The outbox event commits with the state, and the entry key makes the relay safe to repeat. Each night the provider's file proves the ledger right.

    L

    Card data and PCI scope

    tokens keep the card out
    card data exists only hereHosted fieldprovider's, in the pageProvidercard vaultcardtokenthe page posts token, last 4 digits, amountPayment servicerefuses a card numberPostgrestoken, last 4 digitsauthorize with the token
    methodcard data in our systemsstatus
    Our form posts the card to our serversEvery service and log on the pathNot approved
    Our own vault, encryptedThe vault and all that reaches itOnly with a dedicated reason
    Provider's hosted field, then a tokenNoneApproved

    Tested: after a full payment, a search of every row finds no card number. PCI DSS applies to systems that store, process or transmit card data. Confirm the exact scope with your assessor.

    The card goes from the browser to the provider's hosted field. I store a token and the last 4 digits, so my systems stay out of most of PCI scope.

    M

    See it: a provider that misbehaves

    13 recorded timelines; each ends with one charge

    The provider authorized the card, and the reply was lost. Look it up before any retry.

    step 1 of 8

    Each side after this step

    1. created
    2. authorized
    3. captured
    4. refunded
    serviceunknown calls0
    outbox, unsent0
    providerauthorizations0
    charges0
    captured, refunded$0.00, $0.00
    ledgerentries0
    merchant$0.00
    sum of postings$0.00

    The fake provider lost requests and replies, sent copies and reordered webhooks. Every scenario ended with one charge and a ledger sum of 0.

    N

    Failure cases

    what breaks, and why nobody pays twice
    eventresultwhy it is safesaved by
    A provider call times outClient gets 202; the intent stays pending.The sweeper looks the key up before it sends anything.Intent row
    The key window ends firstThe same key would charge again.The lookup reads records, not keys, so nothing is sent.Lookup
    A slow request lands after the resend2 copies reach the provider.Both carry one key inside the window.Provider key
    The service dies after the provider repliedThe reply is gone.The pending intent leads the sweeper to the result.Intent row
    A webhook arrives 3 timesThe first applies.The event id is a primary key.Fact key
    A forged webhook arrives401, no row.The HMAC does not match.Signature
    The relay dies after postingThe event is sent again.The entry key returns the first entry.Entry key
    Refund and dashboard refund raceThe provider refuses the second.The refused call frees its hold; the first still applies.Gate
    The capture misses the file's cut-offA line is missing at the provider.It stays a case until the next file matches it.Match
    Every webhook is lostThe sweep or the file finds the gap.Webhooks speed things up; no money depends on them.Sweeper
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1Postgres, one relay2+ clearing rows, N relays3+ partitions4+ shards by merchantmore load →
    Capacity against the peak101001k10k100kDemand, average: 116 per secondDemand, average116Demand, peak: 1,157 per secondDemand, peak1,157Ledger, 1 clearing row: 1,000 per secondLedger, 1 clearing row1,000Service path, 32 clients: 2,000 per secondService path, 32 clients2,000Ledger, 16 rows, 8 relays: 3,000 per secondLedger, 16 rows, 8 relays3,000per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres, a separate ledger database, one relay.About 2,000 payments a second through the service, and 1,000 ledger entries.The outbox backlog grows at peak.
    216 clearing rows and N relays. The ref picks the row.About 3,000 entries a second. 8 relays on 1 row gained little.Facts and calls pass memory; vacuum falls behind.
    3Monthly partitions of facts, calls and postings.Old months move to cheap storage. A sweep reads the current month.One primary nears its write limit.
    4Shards by merchant, with a ledger per shard.Each shard adds its own rate. A payment never crosses a merchant.Top of the ladder.

    Demand, derived: 10,000,000 ÷ 86,400 s ≈ 116 a second; 10 times that at peak. The lab provider has no latency, so the path rate bounds the service and Postgres, not the provider.

    One clearing row caps the ledger at about 1,000 entries a second, whatever the number of relays. I split that row before I add any database.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How does the ledger stay exact under load?Each entry claims a unique key, locks accounts in id order, and a trigger refuses an entry that does not sum to 0.T9
    Why not a distributed transaction with the provider?The provider takes part in no protocol of ours. Idempotent calls plus a lookup give the same effect.T7
    The provider has an outage. What then?A breaker stops new calls, and pending calls wait for the sweeper. A second provider takes only new payments, never a payment already in flight.O2
    How do you protect webhooks and secrets?Verify an HMAC in constant time, rotate the secret, and keep tokens scoped to one merchant.O5
    What about provider fees?The settlement file carries them. Post one entry per file: clearing to bank, plus a fee expense. The match runs on the gross lines.T9
    How do you tell the merchant?Another consumer reads the same outbox and sends signed webhooks, with retries and a dead-letter queue.B6
    How do you shard?By merchant, because refunds and reports stay inside one merchant. A directory maps each merchant to a shard.X2
    What locks does the gate take?One row lock on the payment, held for milliseconds. Two payments never wait for each other, except on a hot ledger row.T4
    Q

    Drill

    predict, then reveal

    0 of 10 known

    1. A capture times out. Why not retry at once with the same key?

    2. The lookup says not found. Is it safe to send the call again?

    3. Why commit the intent row before the call and not after?

    4. Why not hold a database transaction across the provider call?

    5. A captured webhook arrives for a payment that is still created. What happens?

    6. A refund webhook arrives before its capture. What happens?

    7. Why an outbox and not a ledger post inside the gate?

    8. The relay posts twice. How many entries does the ledger have?

    9. The settlement file has a capture the ledger lacks. What does the job do?

    10. Two refunds of $60 arrive at once for a $100 capture. How is the second refused?

    R

    Numbers to say

    measured in the lab
    peak
    About 1,157 payments a second from 10 million a day.
    in flight
    About 4,630 open calls at 2 s each.
    service path
    About 2,000 payments a second, 32 clients.
    ledger
    About 1,000 entries a second on 1 clearing row, 3,000 on 16.
    storage
    About 2.4 kB per payment, 24 GB a day.
    faults
    13 scenarios, 300 random webhook orders, a storm of 200 payments: one charge each.

    Postgres 16 on an 8-core laptop, a fake provider with no latency, other workloads on the machine. Use these as orders of magnitude.