AlgoViz

Design a Digital Wallet

hard 45 min

Let 50 million people keep money in an app and send it to each other, at 174 transfers a second.

See it run

Follow the money from account to account: a transfer, a retry, a withdrawal, a bounced deposit and two shards.

Operations

Send $50

Asha has $200, Lee has $75.

Step 1 of 11

Tap Send

Our systemAsha's appWallet serviceLedgerPostgreSQLFraud checkKafkaNotifications

key

7b0e

Asha

200.00

Lee

75.00

The app made one key for this payment and will repeat it with every retry.

Step 1: Tap Send

check sign-in, limits, receiverscore = fraud.check(timeout=200 ms)BEGIN  insert (sender, key)  asha -= 5000 where balance >= 5000  lee  += 5000  insert entries (asha, -5000), (lee, +5000)  insert outbox rowCOMMITrelay -> Kafka -> notifications
Commits
one
Writes
key, 2 entries, 2 balances

Everything that can refuse comes before the first lock, except the balance itself.

In the real world

The same design a digital wallet doing real jobs. Pick one and step through it.

$100 in the wallet and two transfers of $80.

Step 1 of 4

Both arrive

Our systemAsha's appWallet serviceLedgerPostgreSQLFraud checkKafkaNotifications

Asha

100

first

80

second

80

Phone and laptop send at the same moment, with different keys.

Step 1: Both arrive

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Two updates without a transaction

    critical

    A crash in the middle loses the money.

    Wrong
    debit(asha, 5000)credit(lee, 5000)
    Right
    BEGIN  debit, credit, two entries, keyCOMMIT
  • Money as a float

    major

    Sums drift by fractions of a cent.

    Wrong
    balance = 0.1 + 0.2   # 0.30000000000000004
    Right
    balance = 10 + 20     # cents
  • Keys only in a cache

    critical

    The cache can forget what the database did.

    Wrong
    if redis.set(key, "running", nx=True):    transfer()
    Right
    INSERT (sender, key)  -- same transaction-- conflict: return the first result
  • Version in the balance update

    major

    Another payment changes the version and an honest sender is refused.

    Wrong
    WHERE balance >= 5000 AND version = $2
    Right
    WHERE balance >= 5000
  • Calling partners inside the transaction

    critical

    Locks wait for somebody else's network, and a rollback cannot unsend.

    Wrong
    BEGIN; debit(); bank.send(); COMMIT;
    Right
    BEGIN; wallet -> pending; COMMIT;worker sends later

Interview tips

  • Start from zero

    • Entries add up to zero.
    • Own accounts for pending, fees, bank.
    • Balances are kept sums.
  • Size it honestly

    • 174 a second at peak.
    • One primary with a standby.
    • Shards only when tests say so.
  • Distrust the network

    • Same key on every retry.
    • Write before sending.
    • Ask before repeating.
  • Find your errors

    • Recompute balances nightly.
    • Match bank lines daily.
    • Correct with new entries.