Design a Digital Wallet
hard 45 minLet 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
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
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
criticalA crash in the middle loses the money.
Wrongdebit(asha, 5000)credit(lee, 5000)RightBEGIN debit, credit, two entries, keyCOMMITMoney as a float
majorSums drift by fractions of a cent.
Wrongbalance = 0.1 + 0.2 # 0.30000000000000004Rightbalance = 10 + 20 # centsKeys only in a cache
criticalThe cache can forget what the database did.
Wrongif redis.set(key, "running", nx=True): transfer()RightINSERT (sender, key) -- same transaction-- conflict: return the first resultVersion in the balance update
majorAnother payment changes the version and an honest sender is refused.
WrongWHERE balance >= 5000 AND version = $2RightWHERE balance >= 5000Calling partners inside the transaction
criticalLocks wait for somebody else's network, and a rollback cannot unsend.
WrongBEGIN; debit(); bank.send(); COMMIT;RightBEGIN; 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.