System Design

C20

Digital wallet

Design a wallet that moves money between users, exactly once, at thousands of transfers a second.

Not startedSaved in this browser only.
  1. 1Shard by user, and expect almost every transfer to cross shards. With 16 shards, 15 of 16 do.
  2. 2A cross-shard transfer is a saga of 5 commits: a hold, a credit, a capture. Each step has a key, and a row on the source shard drives recovery.
  3. 3The journal is the truth and the balance is a cached projection. Replay proves one against the other.
  4. 4A hot account is one row. Split it into sub-accounts; shards do not help it. Transit accounts need the same split.
C20
    A

    The prompt and requirements

    questions first, then numbers
    "Design a wallet that moves money between users, exactly once, at thousands of transfers a second."
    questionanswer assumed
    How many users?50 million, 5 transfers each a day.
    Peak?3 times the average.
    Money in and out?Deposits and payouts run through a provider, as on the payments sheet.
    Currencies?One. An FX account handles the others later.
    Merchants?Yes. A large merchant takes thousands of credits a second.
    Daily limits?Per sender, per UTC day, exact.
    How long do we keep history?Years, for audit. A reader must see any past balance.
    requirementtarget
    Peak transfers8,681 a second
    Each transfer appliesOnce, under any retry or crash
    Total moneyConserved, checked across shards
    OverdraftNever, under concurrency
    Hot merchant3,000 credits a second
    Crash between shardsFinishes without a person
    Past balancesReadable as of any entry

    Every transfer moves money once, money is never created or lost, and a crash between 2 shards finishes without a person.

    B

    Estimates

    arithmetic shown
    per day
    50 million × 5 = 250 million transfers
    average
    250,000,000 ÷ 86,400 s ≈ 2,894 a second
    peak
    2,894 × 3 ≈ 8,681 a second
    cross share
    16 shards: 1 - 1/16 = 93.8%
    per shard
    2,677 a second on 2 shards ≈ 1,339 each
    shards
    8,681 ÷ 1,339 ≈ 7; take 16, or 21,416 a second
    storage
    250 million × 1.4 kB ≈ 362 GB a day

    Rates and bytes per transfer were measured in the lab: 593 B inside a shard, 1,507 B across, with indexes.

    Peak is about 8,700 transfers a second. Almost all cross shards, so I size for the cross-shard rate.

    C

    API

    methods, bodies, status codes
    callresult
    POST /transfersTo, amount. 200 settled, 202 open, 402 no funds, 403 over the limit, 422 key reused.
    GET /transfers/:idState: open, settled, refused, cancelled.
    GET /users/:id/balanceBalance and available, from the cache.
    GET /users/:id/entriesHistory, by cursor. Takes an as-of entry.
    POST /merchants/:id/payoutsFrom the main account, after a sweep.

    POST calls take an Idempotency-Key header, unique per sender, kept with the transfer.

    A transfer takes an idempotency key per sender. It returns 202 if the saga is still open, and the client polls.

    D

    Data model

    one shard's tables, then SQL
    accountsPKiduser, transitbalancecachedheldon holdallow_negativeCHECK balance - held >= 0journal_entriesPKidUQidempotency_keyfingerprintkindappend onlypostingsPKentry_idPKaccount_idamount+ or -currencyeach entry sums to 0holdsPKidFKaccount_idUQidempotency_keystatusheld, captured…closes oncetransfersPKkeysender:clientfrom_userto_userother shardstateopen, settled…the saga log, source sharddaily_spendPKuser_idPKdayspentcentslimit_claimsone per keyUPDATE refuses over the limit
    placement
    Shard by user id. A directory maps ranges to shards.
    transit
    16 rows on each shard, picked by key. The rows of all shards net to 0.
    money
    bigint cents, one currency per account.
    snapshots, journal rulesql
    -- A balance per account as of one entry. Replay starts here.
    CREATE TABLE snapshots (
      upto    bigint NOT NULL,
      account bigint NOT NULL,
      balance bigint NOT NULL,
      PRIMARY KEY (upto, account)
    );
    
    -- Balance reads and replay walk one account's postings in entry order.
    CREATE INDEX postings_by_account ON postings (account_id, entry_id)1;
    
    -- The journal records what happened. No code path may change it.
    CREATE FUNCTION journal_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
    BEGIN
      RAISE EXCEPTION 'the journal is append only'
        USING ERRCODE = 'restrict_violation';
    END $$;
    
    CREATE TRIGGER journal_append_only BEFORE UPDATE OR DELETE ON journal_entries
      FOR EACH ROW EXECUTE FUNCTION journal_append_only();
    CREATE TRIGGER postings_append_only2 BEFORE UPDATE OR DELETE ON postings
      FOR EACH ROW EXECUTE FUNCTION journal_append_only();
    1. 1A history page and a derived balance walk one account in entry order.
    2. 2The database refuses UPDATE and DELETE, so no code path can rewrite history.
    transfers, limitssql
    -- These tables sit beside the ledger tables on every shard. A cross-shard
    -- transfer has its row on the source shard: the row is the saga log.
    CREATE TABLE transfers (
      key        text        PRIMARY KEY, -- <sender>:<client key>
      from_user  bigint      NOT NULL,
      to_user    bigint      NOT NULL,
      amount     bigint      NOT NULL CHECK (amount > 0),
      currency   char(3)     NOT NULL,
      state      text        NOT NULL DEFAULT 'open'
        CHECK (state IN ('open', 'settled', 'refused', 'cancelled'))1,
      created_at timestamptz NOT NULL DEFAULT now()
    );
    CREATE INDEX transfers_open ON transfers (created_at) WHERE state = 'open'2;
    
    -- One row per sender and day. The UPDATE refuses to pass the limit.
    CREATE TABLE daily_spend (
      user_id bigint NOT NULL,
      day     date   NOT NULL,
      spent   bigint NOT NULL CHECK (spent >= 0),
      PRIMARY KEY (user_id, day)
    );
    
    -- One row per transfer that counted, so a retry never counts twice.
    CREATE TABLE limit_claims (
      key     text   PRIMARY KEY,3
      user_id bigint NOT NULL,
      day     date   NOT NULL,
      amount  bigint NOT NULL
    );
    1. 1Recovery reads the open rows. The steps have their own keys, so the row needs only these 4 states.
    2. 2A partial index keeps recovery cheap when billions of rows are closed.
    3. 3A claim per transfer, so a retry never counts twice.

    Each shard runs the same ledger. I add a transfer row as the saga log, a daily counter, and snapshots. The journal takes only inserts.

    E

    The architecture

    click a step; its path lights up
    Mobile appone key per sendWallet serviceroutes by userRecoveryreads open rowsShard Aledger, transfersShard Bledger, transfersAuditacross shards

    Step 1: Same shard

    • Hash the sender and the receiver. Both land on one shard.
    • Claim the daily limit, then post one ledger entry.

    If it fails

    No funds: the CHECK refuses, and the limit comes back. A retry finds the entry key.

    The service routes by user. A transfer on one shard is one entry. A transfer across shards is a saga, and recovery finishes any that stop.

    F

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresUnique keys and ON CONFLICT DO NOTHINGEach saga step and each limit claim applies once.Idempotent APIs
    PostgresCHECK balance - held >= 0No overdraft and no double spend, under any concurrency.Stock, seats
    PostgresRow locks in id orderTransfers on one shard never deadlock.Multi-row updates
    PostgresDeferred constraint triggerEvery entry sums to 0 at commit.Rules across rows
    PostgresBEFORE UPDATE OR DELETE triggerAn append-only journal.Audit tables
    PostgresConditional upsertA daily counter that refuses to pass the limit.Quotas
    PostgresLOCK TABLE IN SHARE MODE, brieflyA snapshot mark that no late commit can pass.Consistent cuts
    PostgresRollback when a connection endsA crash inside a step leaves nothing.Every transaction
    PostgresPartial index on open rowsRecovery reads few rows.Queues, outboxes
    ServiceA stable hash of the keyA retry picks the same sub-account and the same transit row.Routing

    Postgres gives me balanced entries, unique keys per step, a CHECK that refuses an overdraft, and row locks that order each account.

    G

    Deep dive: the balance

    a derived sum and a cached column
    balanceread, 100,000 postingscan it drift?status
    Column only63 µsYes, and nothing noticesNot approved
    Sum of postings only14.8 msNoSmall histories
    Both, in one transaction, audited63 µsThe audit catches itApproved

    Median of 101 reads on the lab Postgres. The derived read costs 235 times the cached read, and it grows with history.

    2 ways to readpseudo code
    cached(account):
      read one row                          // constant cost1
    derived(account):
      sum every posting of the account      // grows with history2
    1. 1The ledger updates this column in the same transaction as the postings, so a reader never sees a half-applied transfer.
    2. 2An index helps, but each read still visits every posting of the account.
    Tested source SQL: both reads
    SQL: both readssql
    SELECT balance FROM accounts WHERE id = $1;
    
    SELECT coalesce(sum(amount), 0) FROM postings WHERE account_id = $1;

    I keep both. The journal is the truth. The cached balance reads in about 63 µs at any history, and the audit compares them.

    H

    Deep dive: transfers across shards

    5 commits on 2 databases
    Shard AaliceShard Bbobtime: 5 commits, no transaction spans 2 shards1 open rowcount the limit2 holdavailable falls3 credittransit to bob4 capturealice to transit5 close rowsettled↯↯↯↯a crash at any ↯: recovery reads the open row and runs every step again; each step has its own key
    methoda crash in the middlestatus
    Debit, then credit, no logThe money stays in transit, unnoticedNot approved
    2-phase commitLocks stay until the coordinator returnsLow rate, same operator
    Saga: debit, credit, refund on failureThe sender sees a debit that reversesIf a reversal is acceptable
    Saga: hold, credit, captureNo debit until the credit landedApproved
    Move the 2 users to one shardNo saga, if they stay togetherClosed groups only
    same shard: 2 commitspseudo code
    single(key, from, to, amount):
      COMMIT claim the daily limit
      COMMIT one entry, key = client key1
        no funds: give the limit back2, refused
    1. 1The whole money movement is one transaction, so no saga and no transit.
    2. 2A crash between the 2 commits counts against the limit until the client retries: the safe side.
    Tested source Go: single
    Go: singlego
    // single is one ledger entry on one shard. The limit commits first; if the post then fails for a
    // business reason, the limit is given back. A crash between the two counts against the limit
    // until the client retries, which is the safe side.
    func (c *Cluster) single(ctx context.Context, key string, r Req) (string, error) {
      s := c.shard(r.From)
      err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error { return c.claimLimit(ctx, tx, key, r) })
      if err != nil {
        return "", err
      }
      e := ledger.Entry{Key: key, Kind: "transfer", Currency: "USD", Legs: []ledger.Leg{
        {Account: r.From, Amount: -r.Amount}, {Account: c.payee(r.To, key), Amount: r.Amount}}}
      _, err = s.Post(ctx, e)
      if errors.Is(err, ledger.ErrInsufficientFunds) || errors.Is(err, ledger.ErrNoAccount) {
        if _, gbErr := s.DB.Exec(ctx, q["give_back"], key); gbErr != nil {
          return "", fmt.Errorf("give back limit: %w", gbErr)
        }
        return Refused, nil
      }
      if errors.Is(err, ledger.ErrKeyReused) {
        return "", fmt.Errorf("%w: %q", ErrKeyReused, r.Key)
      }
      if err != nil {
        return "", err
      }
      return Settled, nil
    }
    
    across shards: 5 commitspseudo code
    run(transfer):                         // start and resume are one call1
      hold on the sender, key hold:<k>2
        no funds: close refused, STOP
      IF the other shard is silent: STOP     // stays open3
      post credit, key credit:<k>
        no such account4: release, cancelled, STOP
      capture the hold, key debit:<k>5
      close settled
    1. 1Recovery needs no special path, so the common path tests it every day.
    2. 2The hold key comes from the transfer key. A rerun finds the hold.
    3. 3A timeout says nothing about the credit. Cancelling on silence could create money.
    4. 4A refusal is an answer. The hold is released, and no entry exists on either shard.
    5. 5The capture moves the money into transit on shard A, opposite to the transit credit on shard B.
    Tested source Go: the saga · Go: capture, from the money sheet · SQL: the transfer row
    Go: the sagago
    // run takes a transfer forward from wherever it stands. Every step has its own key, so a step
    // that already committed changes nothing. A refusal is final and ends the saga. A timeout is not
    // a refusal: the transfer stays open and recovery tries again, because the credit may have
    // landed. Only an answer from the other shard may cancel.
    func (c *Cluster) run(ctx context.Context, t transfer, crashAt string, inCredit ledger.Fault) (string, error) {
      a, b := c.shard(t.from), c.shard(t.to)
      holdID, err := a.Hold(ctx, t.from, t.amount, "hold:"+t.key)
      if errors.Is(err, ledger.ErrInsufficientFunds) {
        return c.finish(ctx, t, Refused)
      }
      if err != nil {
        return "", fmt.Errorf("hold %s: %w", t.key, err)
      }
      c.saw(t, AfterHold)
      if crashAt == AfterHold {
        return "", ErrCrashed
      }
      if c.Down[c.ShardOf(t.to)] {
        return "", fmt.Errorf("%w: credit %s", ErrShardDown, t.key)
      }
      _, err = b.Post(ctx, ledger.Entry{Key: "credit:" + t.key, Kind: "credit", Currency: t.currency, Fault: inCredit, Legs: []ledger.Leg{
        {Account: c.transit(t.key), Amount: -t.amount}, {Account: c.payee(t.to, t.key), Amount: t.amount}}})
      if errors.Is(err, ledger.ErrNoAccount) {
        if _, err := a.Release(ctx, holdID); err != nil {
          return "", fmt.Errorf("release %s: %w", t.key, err)
        }
        c.saw(t, Released)
        return c.finish(ctx, t, Cancelled)
      }
      if err != nil {
        return "", fmt.Errorf("credit %s: %w", t.key, err)
      }
      c.saw(t, AfterCredit)
      if crashAt == AfterCredit {
        return "", ErrCrashed
      }
      if _, err := a.Capture(ctx, holdID, c.transit(t.key), t.amount, "debit:"+t.key, t.currency); err != nil {
        return "", fmt.Errorf("capture %s: %w", t.key, err)
      }
      c.saw(t, AfterCapture)
      if crashAt == AfterCapture {
        return "", ErrCrashed
      }
      return c.finish(ctx, t, Settled)
    }
    
    // finish closes the transfer. A refused or cancelled transfer gives its limit back.
    func (c *Cluster) finish(ctx context.Context, t transfer, state string) (string, error) {
      err := pgx.BeginFunc(ctx, c.shard(t.from).DB, func(tx pgx.Tx) error {
        tag, err := tx.Exec(ctx, q["close_transfer"], t.key, state)
        if err != nil {
          return fmt.Errorf("close transfer: %w", err)
        }
        if tag.RowsAffected() == 1 && state != Settled {
          if _, err := tx.Exec(ctx, q["give_back"], t.key); err != nil {
            return fmt.Errorf("give back limit: %w", err)
          }
        }
        return nil
      })
      c.saw(t, state)
      return state, err
    }
    
    Go: capture, from the money sheetgo
    // Capture closes a hold and moves amount, at most the held amount, to another account. The rest
    // of the hold returns to the available balance.
    func (l *Ledger) Capture(ctx context.Context, holdID, to, amount int64, key, currency string) (Result, error) {
      return l.run(ctx, NoFault, func(tx pgx.Tx) (Result, error) {
        var from, held int64
        if err := tx.QueryRow(ctx, q["read_hold"], holdID).Scan(&from, &held); err != nil {
          return Result{}, fmt.Errorf("read hold %d: %w", holdID, err)
        }
        if amount <= 0 || amount > held {
          return Result{}, fmt.Errorf("%w: %d of %d", ErrOverCapture, amount, held)
        }
        e := Entry{Key: key, Kind: "capture", Currency: currency, Legs: []Leg{{from, -amount}, {to, amount}}}
        res, err := claim(ctx, tx, e)
        if err != nil || res.Replayed {
          return res, err
        }
        if err := l.lock(ctx, tx, e); err != nil {
          return Result{}, err
        }
        if err := tx.QueryRow(ctx, q["close_hold"], holdID, "captured").Scan(&from, &held); err != nil {
          if errors.Is(err, pgx.ErrNoRows) {
            return Result{}, fmt.Errorf("%w: hold %d", ErrHoldClosed, holdID)
          }
          return Result{}, fmt.Errorf("close hold %d: %w", holdID, err)
        }
        if _, err := tx.Exec(ctx, q["set_held"], from, -held); err != nil {
          return Result{}, fmt.Errorf("lift hold on account %d: %w", from, err)
        }
        return res, apply(ctx, tx, res.EntryID, e)
      })
    }
    
    SQL: the transfer rowsql
    -- 0 rows: a retry or a copy of this transfer.
    INSERT INTO transfers (key, from_user, to_user, amount, currency) VALUES ($1, $2, $3, $4, $5)
    ON CONFLICT (key) DO NOTHING;
    
    -- Recovery reads these. A grace period leaves a transfer that is still running alone.
    SELECT key, from_user, to_user, amount, currency, state FROM transfers
    WHERE state = 'open' AND created_at < now() - $1::interval
    ORDER BY created_at;
    
    -- 0 rows: another runner closed it first.
    UPDATE transfers SET state = $2 WHERE key = $1 AND state = 'open';
    recoverypseudo code
    recover():
      FOR each shard:
        FOR each open row past the grace period1:
          run(transfer)
    1. 1A running transfer stays alone. If 2 runners do meet, the keys make that safe.
    Tested source Go: recover
    Go: recovergo
    // Recover runs every open transfer older than grace, on every shard. A shard that is still down
    // leaves its transfers open for the next pass. It returns how many transfers it closed.
    func (c *Cluster) Recover(ctx context.Context, grace time.Duration) (int, error) {
      closed := 0
      for _, s := range c.Shards {
        rows, err := s.DB.Query(ctx, q["open_transfers"], grace.String())
        if err != nil {
          return closed, fmt.Errorf("read open transfers: %w", err)
        }
        var t transfer
        var open []transfer
        if _, err := pgx.ForEachRow(rows, t.dest(), func() error {
          open = append(open, t)
          return nil
        }); err != nil {
          return closed, fmt.Errorf("read open transfers: %w", err)
        }
        for _, t := range open {
          _, err := c.run(ctx, t, "", ledger.NoFault)
          if errors.Is(err, ErrShardDown) {
            continue
          }
          if err != nil {
            return closed, err
          }
          closed++
        }
      }
      return closed, nil
    }
    

    Tested: 6 crash points, each through recovery and through a client retry; 8 recoveries racing; 16 copies at once; a shard down, then back.

    I place a hold, credit the other shard, then capture the hold. A row on the source shard lets recovery finish, and only a refusal may cancel.

    I

    Deep dive: hot accounts

    one row is one queue
    Payersthousands a secondPickhash(key) % 8sub-account 0sub-account 1sub-account 2sub-account 3sub-account 4sub-account 5sub-account 6sub-account 7sweepMain accountone entry per sweepPayoutsmeasured, 32 clients: 1 row 1,300 a second, 8 sub-accounts 5,300balance = main + sum(subs)
    spread credits, fold them backpseudo code
    payee(user, key):
      n = sub-accounts of user
      IF n = 0: RETURN user
      RETURN sub-account hash(key) % n1       // a retry lands on the same one
    sweep(user):
      one entry2: every sub-account -> main
    1. 1From the key, not at random, so a retry lands on the same sub-account.
    2. 2The sweep is one balanced entry. Payouts read only the main account.
    Tested source Go: pick a sub-account · Go: sweep
    Go: pick a sub-accountgo
    // payee picks the account a credit lands on. A hot account has sub-accounts, and the key picks
    // one, so a retry lands on the same one.
    func (c *Cluster) payee(user int64, key string) int64 {
      if n := c.Hot[user]; n > 1 {
        return subAccount(user, int(hash(key))%n, len(c.Shards))
      }
      return user
    }
    
    // subAccount stays on the owner's shard: it adds a multiple of the shard count.
    func subAccount(user int64, i, shards int) int64 {
      return user + int64(shards)*1_000_000*int64(i+1)
    }
    
    Go: sweepgo
    // Sweep moves each sub-account's balance to the main account in one entry. A payout reads the
    // main account, so payouts need no lock on the sub-accounts that take credits.
    func (c *Cluster) Sweep(ctx context.Context, user int64, key string) (int64, error) {
      s := c.shard(user)
      var moved int64
      legs := []ledger.Leg{{Account: user}}
      for i := range c.Hot[user] {
        id := subAccount(user, i, len(c.Shards))
        var bal int64
        if err := s.DB.QueryRow(ctx, q["cached_balance"], id).Scan(&bal); err != nil {
          return 0, fmt.Errorf("read sub-account: %w", err)
        }
        if bal > 0 {
          legs = append(legs, ledger.Leg{Account: id, Amount: -bal})
          moved += bal
        }
      }
      if moved == 0 {
        return 0, nil
      }
      legs[0].Amount = moved
      if _, err := s.Post(ctx, ledger.Entry{Key: key, Kind: "sweep", Currency: "USD", Legs: legs}); err != nil {
        return 0, err
      }
      return moved, nil
    }
    
    methodratestatus
    One row1,300 a secondNot approved
    8 sub-accounts, sum for the balance5,300 a secondApproved
    Queue credits, apply in batchesnot measuredIf the balance may lag
    Skip row locks with an eventual counternot measuredNot approved
    transit accountscross-shard rate
    1 row on each shard940 a second
    16 rows, picked by key2,700 a second

    Each account row takes one writer at a time, for one commit. The commit time sets the rate of a row.

    One row took about 1,300 credits a second and 8 sub-accounts took about 5,300. The transit accounts needed the same split.

    J

    Deep dive: event sourcing, replay and audit

    the journal is the log
    journal: append only; a trigger refuses UPDATE and DELETEsnapshotfolded into the snapshot; can move to cheap storagethe tailReplaysnapshot + tailmust equalCached balanceone row per accountIf they differthe journal wins; rebuild the cache
    snapshot and replaypseudo code
    snapshot():
      BEGIN; lock the journal in SHARE mode1  // waits for writers in flight
        mark = newest entry id
      COMMIT
      store sum of postings up to mark
    replay():
      balances = latest snapshot
      add every posting after the mark2
    1. 1A lower id can commit after a higher id. The lock ends when every writer in flight has finished.
    2. 2Everything at or below the mark is final, so the tail misses nothing.
    Tested source Go: snapshot and replay · SQL: snapshot
    Go: snapshot and replaygo
    // Snapshot stores every balance as of the newest entry and returns that entry's id. Ids come from
    // a sequence, so a lower id can commit after a higher one. The brief SHARE lock waits for writers
    // in flight, which makes every id at or below the mark final. The sum runs after the lock ends.
    func Snapshot(ctx context.Context, s *ledger.Ledger) (int64, error) {
      var upto int64
      err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        if _, err := tx.Exec(ctx, q["lock_journal"]); err != nil {
          return fmt.Errorf("lock journal: %w", err)
        }
        return tx.QueryRow(ctx, q["last_entry"]).Scan(&upto)
      })
      if err != nil {
        return 0, fmt.Errorf("mark snapshot: %w", err)
      }
      if _, err := s.DB.Exec(ctx, q["take_snapshot"], upto); err != nil {
        return 0, fmt.Errorf("take snapshot: %w", err)
      }
      return upto, nil
    }
    
    // Replay folds the log into balances: the latest snapshot, then every posting after it. It also
    // returns how many postings it read from the tail.
    func Replay(ctx context.Context, s *ledger.Ledger) (balances map[int64]int64, tail int, err error) {
      var upto int64
      if err := s.DB.QueryRow(ctx, q["latest_snapshot"]).Scan(&upto); err != nil {
        return nil, 0, fmt.Errorf("find snapshot: %w", err)
      }
      balances = map[int64]int64{}
      var account, amount int64
      rows, err := s.DB.Query(ctx, q["read_snapshot"], upto)
      if err != nil {
        return nil, 0, fmt.Errorf("read snapshot: %w", err)
      }
      if _, err := pgx.ForEachRow(rows, []any{&account, &amount}, func() error {
        balances[account] = amount
        return nil
      }); err != nil {
        return nil, 0, fmt.Errorf("read snapshot: %w", err)
      }
      rows, err = s.DB.Query(ctx, q["read_tail"], upto)
      if err != nil {
        return nil, 0, fmt.Errorf("read tail: %w", err)
      }
      if _, err := pgx.ForEachRow(rows, []any{&account, &amount}, func() error {
        balances[account] += amount
        tail++
        return nil
      }); err != nil {
        return nil, 0, fmt.Errorf("read tail: %w", err)
      }
      return balances, tail, nil
    }
    
    SQL: snapshotsql
    -- Waits for every writer in flight. A lower id can commit after a higher one, so a max(id) read
    -- without this lock can miss an entry that later lands below the snapshot.
    LOCK TABLE journal_entries IN SHARE MODE;
    
    SELECT coalesce(max(id), 0) FROM journal_entries;
    
    INSERT INTO snapshots (upto, account, balance)
    SELECT $1, account_id, sum(amount) FROM postings WHERE entry_id <= $1 GROUP BY account_id
    ON CONFLICT (upto, account) DO NOTHING;
    replaytime
    From the start, 200,000 postings87 ms
    From a snapshot, 1,000 postings in the tail0.6 ms
    Fold rate2,300,000 postings a second
    the auditpseudo code
    audit():
      each shard: entries sum to 0, cache = journal1
      users + transit, all shards2 = money funded
      no open transfer: transit nets to 03, no holds
      each settled row: 1 debit and 1 credit
      each refused or cancelled row: no entries
    1. 1A test added $0.01 to a cached balance. The audit reported 1 drifted account, and a rebuild repaired it.
    2. 2No single shard can see this rule. It needs a read of every shard.
    3. 3The control below fails here: its money stays in transit with no open row.
    Tested source Go: audit
    Go: auditgo
    // Audit checks each shard's ledger, then the rules no single shard can check: transit rows net to
    // 0, money in user accounts plus transit equals money funded, and each closed transfer has
    // exactly the entries its state promises, on both shards.
    func (c *Cluster) Audit(ctx context.Context) (Report, error) {
      var rep Report
      for _, s := range c.Shards {
        a, err := s.RunAudit(ctx)
        if err != nil {
          return rep, err
        }
        rep.Shards = append(rep.Shards, a)
        var transit, funding, owned, held int64
        if err := s.DB.QueryRow(ctx, `SELECT
          coalesce(sum(balance) FILTER (WHERE id <= $1), 0),
          coalesce(sum(balance) FILTER (WHERE id = $2), 0),
          coalesce(sum(balance) FILTER (WHERE id >= $3), 0),
          coalesce(sum(held), 0) FROM accounts`, TransitRows, Funding, FirstUser).Scan(&transit, &funding, &owned, &held); err != nil {
          return rep, fmt.Errorf("sum accounts: %w", err)
        }
        rep.Transit += transit
        rep.Funded -= funding
        rep.Owned += owned
        rep.OnHold += held
        rows, err := s.DB.Query(ctx, "SELECT key, from_user, to_user, amount, currency, state FROM transfers")
        if err != nil {
          return rep, fmt.Errorf("read transfers: %w", err)
        }
        var t transfer
        var all []transfer
        if _, err := pgx.ForEachRow(rows, t.dest(), func() error {
          all = append(all, t)
          return nil
        }); err != nil {
          return rep, fmt.Errorf("read transfers: %w", err)
        }
        for _, t := range all {
          rep.Checked++
          if t.state == Open {
            rep.Open++
            continue
          }
          debit, credit, err := c.entries(ctx, t)
          if err != nil {
            return rep, err
          }
          want := 0
          if t.state == Settled {
            want = 1
          }
          if debit != want || credit != want {
            rep.Mismatched++
          }
        }
      }
      return rep, nil
    }
    

    Every balance is a fold over the journal. A snapshot makes the replay short, and an audit across shards proves that money is conserved.

    K

    Daily limits and idempotency

    exact under concurrency
    the daily limitpseudo code
    claim_limit(key, user, day, amount):
      insert claim for key; row exists: STOP // a retry counts once1
      add amount to spent for user and day
        WHERE spent + amount <= limit2
      0 rows: refuse, over the limit
    1. 1The claim key is the transfer key.
    2. 2The upsert locks the row, so concurrent sends line up and the sum stays exact.
    Tested source Go: claim the limit · SQL: spend, give back
    Go: claim the limitgo
    // claimLimit counts a transfer against the sender's day, once per key.
    func (c *Cluster) claimLimit(ctx context.Context, tx pgx.Tx, key string, r Req) error {
      day := r.Day.UTC().Format(time.DateOnly)
      tag, err := tx.Exec(ctx, q["claim_limit"], key, r.From, day, r.Amount)
      if err != nil {
        return fmt.Errorf("claim limit: %w", err)
      }
      if tag.RowsAffected() == 0 {
        return nil // a retry: this key already counted
      }
      if r.Amount > c.DailyLimit {
        return fmt.Errorf("%w: %d over %d", ErrDailyLimit, r.Amount, c.DailyLimit)
      }
      var spent int64
      err = tx.QueryRow(ctx, q["spend"], r.From, day, r.Amount, c.DailyLimit).Scan(&spent)
      if errors.Is(err, pgx.ErrNoRows) {
        return fmt.Errorf("%w: user %d", ErrDailyLimit, r.From)
      }
      if err != nil {
        return fmt.Errorf("spend: %w", err)
      }
      return nil
    }
    
    SQL: spend, give backsql
    INSERT INTO limit_claims (key, user_id, day, amount) VALUES ($1, $2, $3, $4)
    ON CONFLICT (key) DO NOTHING;
    
    -- The WHERE clause refuses a sum over the limit, and the row lock orders concurrent spends.
    INSERT INTO daily_spend (user_id, day, spent) VALUES ($1, $2, $3)
    ON CONFLICT (user_id, day) DO UPDATE SET spent = daily_spend.spent + $3
    WHERE daily_spend.spent + $3 <= $4
    RETURNING spent;
    
    -- A refused or cancelled transfer returns its share of the limit, once.
    WITH gone AS (DELETE FROM limit_claims WHERE key = $1 RETURNING user_id, day, amount)
    UPDATE daily_spend d SET spent = d.spent - g.amount
    FROM gone g WHERE d.user_id = g.user_id AND d.day = g.day;
    copies come fromstopped by
    Client retry, double tapKey per sender: transfer row or entry key
    Recovery reruns a stephold:, credit: and debit: keys
    2 runners on one transferSame keys, and a conditional close
    A retry after the limit is fullClaim row: this key already counted
    A key reused for another amountCompared with the first request: 422

    Tested: 16 sends of $10 against a $50 limit let exactly 5 through, on one shard and across shards.

    The daily counter is a row with a conditional upsert. A claim per transfer means a retry counts once, and a cancelled transfer gives its share back.

    L

    See it: crashes between the debit and the credit

    recorded from 2 Postgres databases

    Bob has the money and alice's debit is not posted. The hold keeps alice from spending it.

    step 1 of 9

    Both shards after this step

    shard A

    alice
    $100.00
    on hold
    $0.00
    transit
    $0.00

    shard B

    bob
    $100.00
    transit
    $0.00
    transfer row
    none
    spendable
    $200.00
    total
    $200.00

    In all 9 recorded runs the total stayed at $200.00 and the audit ended clean. The control with no saga row left $40.00 stuck in transit.

    M

    Failure cases

    what breaks, and why money stays right
    eventresultwhy it is safesaved by
    The runner dies after the holdMoney on hold; receiver has nothing.The open row leads recovery to finish the saga.Transfer row
    The runner dies after the creditReceiver paid; sender not debited.The hold keeps the sender from spending it; the capture follows.Hold
    A crash inside the creditThe connection ends.Postgres rolls the entry back, and the retry posts it.Transaction
    The credit commits, the reply is lostThe runner does not know.The retry finds the key and posts nothing.Entry key
    A shard is downTransfers wait, open.Silence never cancels; the hold stays until the shard returns.Recovery
    The receiver does not existShard B refuses.The hold is released, and the limit comes back.Hold
    8 sends spend the same balance2 pass, 6 refused.The CHECK counts holds against the balance.CHECK
    A cached balance driftsThe audit reports it.Rebuild from the journal, which no code path can edit.Trigger
    A snapshot runs during writesIt waits for writers in flight.No entry can commit below its mark afterward.SHARE lock
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One ledger2+ sub-accounts3+ partitions4+ shards5+ transit rowsmore load →
    Transfers a second, 32 clients1001k10k100kDemand, average: 2,894 transfers per secondDemand, average2,894Demand, peak: 8,681 transfers per secondDemand, peak8,681Across 2 shards, 1 transit row: 937 transfers per secondAcross 2 shards, 1 transit row937Across 2 shards, 16 rows: 2,677 transfers per secondAcross 2 shards, 16 rows2,677Inside 1 shard: 7,525 transfers per secondInside 1 shard7,52516 shards, derived: 21,416 transfers per second16 shards, derived21,416transfers per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres ledger. Every transfer is one entry.About 7,500 transfers a second, spread over many accounts.Lock waits on one account.
    2Sub-accounts for hot accounts.A merchant went from about 1,300 to 5,300 credits a second.History slows vacuum and backups.
    3Monthly partitions and snapshots.Old months move to cheap storage. A replay starts at the snapshot.The primary nears its write limit.
    4Shards by user, with the saga and recovery.About 1,300 cross-shard transfers a second per shard.Cross-shard rate stalls near 940: lock waits on transit.
    516 transit rows per shard.2,700 a second on 2 shards; 21,000 on 16, derived.Top of the ladder.

    The 2 lab shards are 2 databases on one Postgres server, so they share a disk. The 16-shard figure assumes the rate grows with shards; read it as an order of magnitude.

    One shard does about 7,500 transfers a second. Sharding costs a saga, so I split hot rows first and size shards on the cross-shard rate.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How does one entry stay exact?A unique key, accounts locked in id order, and a trigger that refuses an entry that does not sum to 0.T9
    Why not 2-phase commit?The participants hold locks until the coordinator decides, so a crash blocks hot rows. The saga holds no lock between steps.T7
    How do you move a user to another shard?Block new transfers for that user, drain open sagas, copy the journal, then flip the directory entry.X2
    Why row locks and not optimistic checks?A hot row conflicts on nearly every attempt, so retries waste the work. A lock queue is the cheaper order.T5
    How do deposits and payouts work?Through a provider, as a payment that credits or debits the funding account when it settles.C19
    Can a user read their own transfer right after?Read balances from the primary of the user's shard. A replica can lag, and a balance must not.X3
    How do you serve statements?Stream journal entries through an outbox into a read store. The journal stays the truth.B6
    P

    Drill

    predict, then reveal

    0 of 10 known

    1. With 16 shards and users placed at random, what share of transfers cross shards?

    2. Why hold, and not debit first?

    3. A crash comes after the credit and before the capture. What does each user see?

    4. The credit call to shard B times out. May the saga release the hold?

    5. Why does each step need its own key?

    6. What did one transit row cost, and why?

    7. A merchant receives 3,000 credits a second. Why not just add shards?

    8. Why does a snapshot lock the journal?

    9. A cached balance disagrees with the sum of postings. Which one is right?

    10. A transfer is refused after it claimed the daily limit. What happens to the limit?

    Q

    Numbers to say

    measured in the lab
    peak
    About 8,700 transfers a second.
    cross share
    93.8% with 16 shards.
    one shard
    About 7,500 transfers a second, 2 commits each.
    2 shards
    About 2,700 a second, 5 commits each.
    hot row
    About 1,300 a second; 5,300 with 8 sub-accounts.
    balance
    63 µs cached, 14.8 ms derived at 100,000 postings.
    replay
    About 2,300,000 postings a second.
    bytes
    593 B inside a shard, 1,507 B across.

    Postgres 16 on an 8-core laptop, 32 clients, median of 3 runs of 1 s. Other workloads shared the machine, so use these as orders of magnitude.