Notes
Requirements
Fix the scope first. Each user opens a wallet. They can add money from a bank account, send money to any other wallet, see their history, and a shop can refund all or part of a payment. There are limits per transfer and per day. Two rules sit above everything: a retried request never pays twice, and money is never created or lost inside the system. Withdrawing to a bank and cashback are out of scope.
Ask the questions that change the code. Can a user balance go negative? No. One currency? Yes, stored as whole paise in a long, never a double. Do failed transfers appear in history? Yes, with a reason. Can refunds add up to more than the payment? No. Can the same user act from two phones at once? Yes, which tells you concurrency is part of the question, not a bonus.
- users open one wallet each
- add money from a bank account
- send money to another wallet
- see transaction history
- refund all or part of a payment
- limits per transfer and per day
- a retry must never pay twice
- money is never created or lost
- out of scope: bank payouts,
- rewards, currency exchange
- can a balance go negative?
- no, never for a user
- one currency?
- yes, whole paise in a long
- failed transfers in history?
- yes, with a reason
- can a refund exceed the payment?
- no, track what is left
- many devices at once?
- yes, so think about races
Entities
Now the entities. A user owns a wallet. A transaction is the story of one money movement: its type, amount, sender, receiver and status. A ledger entry is one line in a wallet's book, either a debit or a credit. The key relationship is that every completed transaction writes exactly two entries. Keep users thin here; login, profile and KYC documents belong to other services.
Class diagram
Turn them into types. Entries and transactions are facts that never change, so they are Java records. A refund does not edit the original transaction; it is a new one that points back to it. The only mutable class is the wallet, with its own lock, its list of entries and a cached balance. Keeping all changing state in one class keeps the thread safety story short.
enum Side { DEBIT, CREDIT }
enum TxnType { TOP_UP, TRANSFER, REFUND }
record Entry(seq, txnId, walletId,
Side side, long cents, at)
record Txn(id, type, from, to, cents,
status, reason, refundOf)
class Wallet {
ReentrantLock lock;
long balanceCents; // cache
List<Entry> entries; // truth
} Double-entry ledger
Here is the heart of the design: a double-entry ledger. Every transaction writes two entries of the same amount, a debit on one wallet and a credit on another. Adding money is no exception. A system settlement wallet, which stands for the real bank account, is debited and goes negative, while the user is credited. So the sum of every balance in the system is always zero. If it is not, you have a bug, and you can find it.
- add 5,000.00 to the buyer:
- bank wallet DEBIT 5,000.00
- buyer wallet CREDIT 5,000.00
- buyer pays cafe 250.00:
- buyer wallet DEBIT 250.00
- cafe wallet CREDIT 250.00
- sum of every balance
- in the system: always zero
Balance
Should the balance be stored or computed? The entries are the truth, so the balance can always be derived by adding them up. But summing a long history on every payment is slow, so we also keep a cached balance on the wallet. The cache and the entry change together, inside one method, while the wallet lock is held. A reconciliation job recomputes the sum and alerts if the cache ever drifts.
// called with the wallet lock held
void post(Entry e) {
balanceCents += e.side() == CREDIT
? e.cents() : -e.cents();
entries.add(e);
}
derivedBalance(): sum of the entries
nightly check: cache == derived Idempotency
A phone on a weak network taps pay, the reply is lost, and the app retries. Without protection the friend is paid twice. So the app sends an idempotency key with every request, and we store the key with a fingerprint of the request and a future for its result. A retry with the same key gets the same transaction back. The same key with a different amount is a client bug, so we reject it loudly instead of guessing.
Retries can land at the same instant, so check then insert is not enough. Each request puts a slot into a concurrent map with put-if-absent. Exactly one wins and does the work; the others find the winner's future and wait on it. A transfer refused for low balance is still a stored answer, so a retry sees the same failure. Only an invalid request, like an unknown wallet, releases the key.
- app sends key with every request
- store: key -> fingerprint + Future
- same key, same request:
- return the stored transaction
- same key, different amount:
- reject, it is a client bug
- failed for a business reason:
- stored too, retry sees FAILED
- invalid request: key released
Slot mine = new Slot(fp, new Future());
Slot old = idem.putIfAbsent(key, mine);
if (old != null) {
if (!old.fp.equals(fp)) throw ..;
return old.result.join();
}
try { mine.result.complete(work.get()); }
catch (RuntimeException e) {
idem.remove(key, mine); throw e;
} Flow: transfer
Walk the transfer. The idempotency wrapper runs first. Then we lock both wallets, check the sender has enough money and ask the limit policy. If anything fails, we save a failed transaction with the reason. Otherwise we post a debit to the sender and a credit to the receiver, add the amount to the sender's spending for today, and save a completed transaction. Both locks are released at the end.
once(key, fingerprint, () -> {
lock both wallets in id order
if (from.balance < cents) FAILED
reason = limits.check(..)
if (reason != null) FAILED
from.post(DEBIT); to.post(CREDIT);
from.addSpent(today, cents);
return COMPLETED txn
}) Concurrency
Now the classic trap. A transfer must lock two wallets so the debit and credit happen together. Thread one, the buyer paying a friend, locks the buyer, then asks for the friend. At the same moment thread two, the friend paying the buyer, locks the friend, then asks for the buyer. Each holds what the other needs, and both wait forever. That is a deadlock, and a naive solution hits it under load.
The fix is lock ordering. Every thread locks the wallet with the smaller id first, whatever the direction of the money. Both threads now start by locking the buyer, so one waits at the very first step while holding nothing, and no cycle can form. Unlock in finally blocks so an exception never leaves a wallet locked. A single global lock would also be safe, but then every payment in the country waits in one queue.
- thread 1: buyer pays friend
- lock(buyer)
- lock(friend) ... waits
- thread 2: friend pays buyer
- lock(friend)
- lock(buyer) ... waits
- each holds what the other
- needs: both wait forever
Wallet first = from.id.compareTo(to.id)
< 0 ? from : to;
Wallet second = first == from ? to : from;
first.lock.lock();
try {
second.lock.lock();
try { return moveLocked(..); }
finally { second.lock.unlock(); }
} finally { first.lock.unlock(); } Strategy: limits
Limits are a policy that changes with the user's KYC level and with regulation, so they sit behind a limit policy interface: the Strategy pattern. Our basic policy caps each transfer, caps total spending per day and caps the wallet balance. It returns a reason or nothing. The day comes from an injected clock, so a test can move to tomorrow without sleeping. A fully verified user simply gets another policy class.
interface LimitPolicy {
String check(Wallet from, Wallet to,
long cents, LocalDate day);
}
KycLimits(perTransfer 2,000.00,
dailyOut 3,000.00,
maxBalance 10,000.00)
FullKycLimits, MerchantLimits:
new classes, service unchanged Refunds
A refund never edits or deletes the original transaction. It is a new transaction the other way, linked to the original, with its own two entries. Under the locks of both wallets we check how much is left to refund, so two refunds cannot add up to more than the payment. If the shop has already spent the money, the refund fails with a clear reason. A full reversal is just a refund of everything that is left.
- original must be a completed
- transfer
- lock receiver and sender
- (same id order)
- left = amount - refunded so far
- cents over left: FAILED
- receiver too poor: FAILED
- else DEBIT receiver,
- CREDIT the original sender
- original stays untouched
History
Transaction history falls out of the ledger for free. Each wallet's entries, newest first, are its statement, and the transaction id on each line leads to the full details, including the reason for a failure. With millions of rows you page by the entry sequence number using an index on wallet and sequence, never by offset, so new payments arriving do not shift the pages.
tx2008 DEBIT 100.00 refund tx2007 CREDIT 500.00 tx2005 CREDIT 1,500.00 tx3 CREDIT 250.00 real systems: page by entry seq, index on (walletId, seq desc)
Concurrency
Check every shared field. Wallet state is guarded by that wallet's lock, and two wallets are always locked in id order. The cache and the entries change together under that lock. Idempotency is a concurrent map of slots with futures. The amount refunded so far is only changed while both wallets of that payment are locked. Ids come from atomic counters, and transactions and entries are immutable records, safe to share.
- wallet state: its ReentrantLock
- two wallets: lock by id order
- cache + entry: changed together
- idempotency: ConcurrentHashMap
- of request + Future
- refunded so far: updated under
- both wallet locks
- ids and entry seq: AtomicLong
- Txn and Entry: immutable records
Extensibility
Interviewers will stretch it. Withdrawing to a bank is the top-up in reverse. Freezing a wallet is a status the limit policy refuses. Cashback is a transfer from a promotions wallet, so the books still balance. Notifications are observers on completed transactions. On many servers, the locks become row locks taken in id order inside one database transaction, and the idempotency key becomes a unique column.
- withdraw to bank: debit user,
- credit the settlement wallet
- freeze a wallet: a status the
- limit policy checks
- cashback: a promo wallet pays
- notifications: Observer on txn
- many servers: DB transaction,
- SELECT .. FOR UPDATE in id
- order, unique idempotency key
- audit: entries never updated
Testing
The full code is below the player. The demo tops up and retries with the same key, then reuses the key with a new amount and is rejected. Ten threads send the same payment and only one transaction appears. Two threads pay each other a thousand times each and finish without deadlock. A fake clock moves to the next day to reset the daily limit, and every wallet's cache matches its ledger, with all balances summing to zero.
top up 5,000.00, retry: same tx1 same key, 9,000.00: rejected order-77 sent 10 times: [tx3] ping-pong 2,000 transfers: no deadlock pay 2,500.00: over per-transfer limit pay 500.00: daily limit reached next day: COMPLETED refund 200.00: exceeds remaining 150.00 every cache matches its ledger sum of all balances: 0.00
Follow-ups
Expect follow-ups. Why not one global lock? It is correct but every payment waits in one line. Why not try-lock with a timeout? It also avoids deadlock, but you must back off and retry. Store or derive the balance? Both, and reconcile them. What about a popular shop receiving thousands of payments a second? Split its wallet into several sub-wallets and add them up when you read the balance.
- why not one global lock?
- correct but serial
- why not tryLock with timeout?
- works, but needs retries
- balance: store or derive?
- both, and reconcile
- why record failed transfers?
- support, and idempotent retries
- hot merchant wallet?
- shard it into sub-wallets
Say it like this
Here is the short version to say out loud. Every transaction writes a debit and a credit, so all balances sum to zero. The balance is a cache of the entries, updated together under the wallet lock. Every request carries an idempotency key. Two wallets are always locked in id order, so opposite transfers cannot deadlock. Limits are a strategy, and refunds are new transactions, never edits.
- "Every transaction writes two
- entries, so balances always sum
- to zero. The balance is a cache
- of the entries, updated under
- the wallet lock. Requests carry
- idempotency keys. Two wallets
- are locked in id order, so no
- deadlock. Limits are a strategy;
- refunds are new transactions."