Design: digital wallet

In one sentence

Move money between accounts on different shards as an idempotent debit-then-credit saga recorded in a double-entry ledger; the append-only log makes every balance reproducible, and reconciliation proves no money was created or lost.

Two local transactions on two shards, tied together by a durable state machine; a retried step with the same transfer id is applied once.

How it works

  • With 20 shards, ~95% of transfers span two shards: no local transaction covers both accounts.
  • Run a saga: debit the sender first, then credit the receiver, retrying until it succeeds.
  • The debit is conditional on the balance: the only step allowed to fail for business reasons.
  • Between steps the money sits in a transit account, so the entries always sum to zero.
  • Balances are derived from an append-only ledger: replay it to reproduce or audit any balance.

Check yourself

Answer to mark it learned; your answers aren't scored.

A transfer debited Ana on shard 3. The credit to Luis on shard 11 timed out, then the orchestrator crashed. On restart it finds the transfer in DEBITED. What should it do?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: move a balance from one user's wallet to another's, and show balance and history. Top-ups and withdrawals go through a PSP, which is Design: payment system. Non-functional: money is never created or lost, a transfer happens once however often it is retried, a balance never goes negative, and any past balance can be reproduced for an auditor.

Scale (assumed): 100M wallets and 10k transfers/s at peak. At ~1k write transactions/s per database node (assumed) and two writes per transfer, that is at least 20 shards.

Questions I'd ask:

  1. Must the receiver see the money at once, or within seconds?
  2. One currency or several?
  3. What must auditors be able to reproduce?

API and data model

POST /transfers {from, to, amount, currency} with an Idempotency-Key returns {transfer_id, status}. Accounts are sharded by account_id. Each shard holds accounts(id, balance) and an append-only entries(transfer_id, account_id, amount); a transfers table holds the state machine PENDING → DEBITED → COMPLETED, or FAILED. Amounts are integers in minor units.

Architecture

The transfer service claims the idempotency key and creates the transfer. A durable orchestrator then drives two local transactions: debit the sender on its shard, credit the receiver on theirs. In between, the money sits in a transit account, so the ledger balances at every step. Each step is idempotent on (transfer_id, step).

The hard parts

  1. Two shards, one transfer. With 20 shards, ~95% of transfers cross shards, so no single local transaction covers both accounts. The options are 2PC, TCC or a saga (Sagas & the outbox pattern).
  2. Proving correctness. "The balance column says 40" is not evidence. An append-only double-entry ledger, where each transfer's entries sum to zero, lets you rebuild every balance and compare.
Code Cross-shard transfer as an idempotent saga
pythonCross-shard transfer as an idempotent saga
# Each step is ONE local transaction on ONE shard. UNIQUE(transfer_id, step) on `steps`
# makes a retried or duplicated step a no-op. Amounts are integers in minor units.
def debit_sender(shard, t) -> bool:
    with shard.tx() as tx:
        if not claim_step(tx, t.id, "debit"):
            return True                          # retry: the debit already happened
        n = tx.run("UPDATE accounts SET balance = balance - %s "
                   "WHERE id = %s AND balance >= %s", t.amount, t.sender, t.amount)
        if n == 0:
            tx.rollback()                        # insufficient funds: nothing changed
            return False
        post(tx, t.id, [(t.sender, -t.amount), (TRANSIT, +t.amount)])  # entries sum to zero
        return True

def credit_receiver(shard, t) -> None:
    with shard.tx() as tx:
        if claim_step(tx, t.id, "credit"):       # False on a retry: already credited
            tx.run("UPDATE accounts SET balance = balance + %s WHERE id = %s",
                   t.amount, t.receiver)
            post(tx, t.id, [(TRANSIT, -t.amount), (t.receiver, +t.amount)])

def claim_step(tx, transfer_id: str, step: str) -> bool:
    return tx.run("INSERT INTO steps (transfer_id, step) VALUES (%s, %s) "
                  "ON CONFLICT DO NOTHING", transfer_id, step) == 1

def run_transfer(t) -> str:                      # driven by a durable orchestrator
    if not debit_sender(shard_of(t.sender), t):
        return mark(t, "FAILED")
    mark(t, "DEBITED")                           # past this point, only forward
    retry_until_ok(lambda: credit_receiver(shard_of(t.receiver), t))
    return mark(t, "COMPLETED")
Real example

Ana sends $40 to Luis; her wallet is on shard 3, his on shard 11. The app sends key tr_77. Step 1 on shard 3, one local transaction: check her balance, Ana −4000, transit +4000. Step 2 on shard 11 times out, so the orchestrator retries with the same transfer id; the steps table shows the credit was already applied, so Luis is credited exactly once: transit −4000, Luis +4000.

For ~300 ms the money was in neither wallet, but the ledger showed it in transit, and the transfer's four entries sum to zero.

Trade-offs +3 · −3

+ You gain

  • No distributed locks: each step is a short local transaction on one shard.
  • Money is always somewhere, sender, transit or receiver, and the entries prove it.
  • Any balance at any time can be rebuilt from the log: audits and bug fixes become replays.

− You pay

  • Not isolated: for a moment the sender is debited and the receiver is not yet credited.
  • Needs a durable orchestrator and a monitor for transfers stuck halfway.
  • Hot accounts serialize on one row: high-volume receivers need batching or sub-accounts.

Use it when

Balances you hold and move between your own accounts: wallets, in-app credits, marketplace balances, loyalty points with real value.

Avoid it when

When every account fits one database: use one ACID transaction. When a distributed SQL database such as Spanner or CockroachDB is available, let it run the cross-shard commit for you.

Numbers to know 5
  • Sizing (assumed): 10k transfers/s × 2 local writes ÷ ~1k writes/s per node ≈ 20 shards.
  • With S shards, a transfer stays on one shard with probability 1/S: 20 shards means ~95% cross-shard.
  • Ledger volume: 4 entries per transfer, so 10k transfers/s ≈ 40k entries/s at peak.
  • PostgreSQL ships with 2PC off: max_prepared_transactions defaults to 0.
  • Stripe's Ledger (2024): ~5 billion events a day; 99.99% of dollar volume ingested and verified within four days.
Common pitfalls 4
  • Crediting the receiver first: if the debit then fails, the money is already spent and must be clawed back.
  • Reading the balance, checking it in the app, then writing: two concurrent transfers both pass and overdraw.
  • Refunding the sender after a credit timeout: the credit may have landed, so the refund creates money.
  • No alert on transfers stuck in DEBITED: the money sits in transit and nobody notices.
Interview questions 3

Answer out loud first, then reveal.

Sender and receiver are on different shards. How do you keep the transfer atomic?Show answer

I don't make it atomic; I make it always completable. First a local transaction debits the sender, checking the balance, and moves the money to transit. Then I credit the receiver, retrying with the same transfer id until it succeeds. Each step is idempotent and a durable orchestrator resumes after crashes. 2PC would give atomicity, but it holds locks across shards and blocks if the coordinator dies; I'd only take that from a database built for it, like Spanner.

Why event sourcing? Isn't a ledger table enough?Show answer

An append-only ledger already is the event log. Event sourcing means I treat it as the source of truth and the balance as a cache of it. That buys reproducibility: I can rebuild every balance, say what it was last Tuesday, and replay after fixing a bug. The costs are snapshots to keep replays fast, deterministic code and a read model that may lag. For money I accept those; for a profile page I wouldn't.

The credit step keeps failing. What now?Show answer

First, why. Technical failures, a shard down or a timeout, are retried with backoff for as long as it takes: the money is safe in transit, and an alert fires when a transfer stays DEBITED past a threshold. A business failure, such as a closed receiver account, is the one case that needs compensation: a new transfer from transit back to the sender, with its own entries. I never edit or delete the original debit.

Deep dive 4

2PC vs TCC vs saga

2PC: both shards prepare and hold their locks until a coordinator says commit. Atomic and isolated, but a coordinator crash leaves rows locked, and locks held across two round trips cut throughput. PostgreSQL supports it with PREPARE TRANSACTION, off by default (max_prepared_transactions = 0). TCC (Try-Confirm-Cancel): the same idea in application code. Try reserves the amount on the sender as a hold, Confirm turns the hold into the transfer, Cancel releases it. No database locks between phases, but every participant needs three idempotent operations. Saga: no reservation phase; run the steps in order and compensate on failure. For a transfer I order the steps so compensation is almost never needed: the debit is the only step that can be refused, and it goes first. After it, the credit can fail only for technical reasons, so I retry it.

Never negative, effectively once

Two invariants, both enforced inside a shard's local transaction. No overdraft: UPDATE accounts SET balance = balance - x WHERE id = ? AND balance >= x; zero rows updated means insufficient funds. The row lock serializes concurrent debits on one account, so two transfers can't both spend the last $40. Effectively once: the client's idempotency key maps to one transfer id (Idempotency), and each step inserts (transfer_id, step) under a unique constraint in the same transaction as the balance change, so a retried or duplicated step is a no-op. The orchestrator must be durable too: a workflow engine such as Temporal, or workers scanning the transfers table, so a crash after the debit resumes at the credit instead of forgetting it. A transfer stuck in DEBITED is the alert that matters most.

Event sourcing: audit and reproducibility

Store what happened, not just the result. The source of truth is an append-only log of events per account (TransferDebited, TransferCredited); the balance is a fold over them. That gives auditors three things a balance column can't: rebuild the state from scratch, ask what a balance was at any past moment, and replay after fixing a bug. Replaying from zero is slow, so keep snapshots (the balance as of entry N) and replay only the tail. Reads use a materialized balance, updated in the same transaction as the entry, or asynchronously if you accept lag (CQRS). The rules: events are immutable, corrections are new reversing events, and the code that applies events must be deterministic, with no clock and no randomness, or a replay won't reproduce the same balances.

Reconciliation and hot accounts

Reconciliation is how you find the bug the design said was impossible. Continuously: every transfer's entries sum to zero; the transit accounts, summed across shards, equal the transfers currently in DEBITED; and each stored balance equals the sum of that account's entries. Daily: total wallet balances equal the money actually held in the bank accounts behind them. Stripe tracks the share of its ledger that clears to zero as a quality metric. Hot accounts are the scaling limit: a merchant receiving thousands of payments per second serializes on one row. Append its entries without touching the balance row and fold them in batches, or split the merchant into sub-accounts. Debits still need the strict balance check; credits don't.