These are the notes for Low-Level Design (LLD) episode 83: designing a digital wallet, an app that holds money for you so you can pay a shop or send money to a friend with a tap. We cover the digital wallet requirements, the main classes (Wallet, Account, Transaction), the transfer, a ledger with double-entry bookkeeping, statements, idempotency keys, transaction states, concurrent transfers with lock ordering for transfers, and offers and cashback.
How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. In the thread programs, which transfer gives up changes from run to run; the notes say so where it matters. People, amounts and offers are made up. Nothing here describes any real wallet app, bank or payment network.
1. The problem: the shopkeeper's khata, and a double tap
A neighbourhood shopkeeper keeps a khata, a credit notebook. Every rupee is written down: "Asha paid 100, took goods for 30". If there's an argument, the notebook settles it. Now Asha pays Rs 500 on her phone, the screen keeps spinning, and she taps "Pay" again: did she pay once or twice? Or she pays two Rs 300 bills from her phone and her laptop in the same second, with only Rs 500 in the wallet: can both succeed? And there's a "10% cashback" offer: where does that money come from?
| Real life | In the design |
|---|---|
| The khata notebook | The ledger |
| "Asha paid 100, took 30": every movement written down | Entries: a debit and a credit for every transfer |
| Asha's page in the khata | Her statement |
| Tapping "Pay" twice on a slow network | A retry; made safe with an idempotency key |
| Spinning, done, or "payment failed" | Transaction states: PENDING, SUCCESS, FAILED |
| Phone and laptop paying in the same second | Concurrent transfers |
| "10% cashback, up to Rs 20" | An offer, paid from a cashback pool account |
2. Requirements and the main classes
Digital wallet requirements, kept small enough for a machine-coding round:
- Add money (a top-up) from a bank.
- Pay a shop or transfer money to another user.
- Show a statement: every payment in and out.
- A payment that is retried must be charged once.
- Two payments at the same moment must never overspend or lose money.
- Offers such as cashback.
- The hard rule: money is never lost and never created from nothing.
The classes:
- Wallet: what the user sees in the app (balance, history, "Pay" button). Behind it is an account.
- Account: a named bucket of money in the books. Asha's account, Rahul's account, and the company's own accounts, such as a cashback pool or the account that represents money arriving from banks.
- Transaction: one movement of money: from whom, to whom, how much, and its state.
- Transfer: the basic action: take money out of one account and put the same amount into another.
3. Attempt 1: a double balance
class Wallet { // attempt: a double, and nothing else
final String owner; double balance;
Wallet(String o, double b) { owner = o; balance = b; } }
class WalletService {
void transfer(Wallet from, Wallet to, double amount) {
from.balance -= amount; // no balance check
to.balance += amount; } } // and no record of what happened
public class Main { public static void main(String[] args) {
Wallet asha = new Wallet("Asha", 100), rahul = new Wallet("Rahul", 0);
WalletService s = new WalletService();
s.transfer(asha, rahul, 0.10); s.transfer(asha, rahul, 0.20); // 10 paise, then 20 paise
System.out.println("Rahul got Rs " + rahul.balance);
s.transfer(asha, rahul, 500); // Asha has less than Rs 100
System.out.println("Asha: Rs " + asha.balance + ", Rahul: Rs " + rahul.balance);
} }
Real output:
Rahul got Rs 0.30000000000000004
Asha: Rs -400.3, Rahul: Rs 500.3
Why it failed
Rahul got Rs 0.30000000000000004: not a real amount of money. Adoublestores numbers as binary fractions (halves, quarters, eighths...). 0.1 has no exact binary form, just as 1/3 has no exact decimal form (0.3333...), so tiny errors creep in and add up.Asha: Rs -400.3: nothing checked the balance, so she spent money she didn't have (an overdraft).- No record: if Asha asks "where did my money go?", there's nothing to show her. And the transfer is two separate updates with nothing tying them together.
Fix 1: money in paise, in a long
Count money in paise, the smallest unit (100 paise = Rs 1), as a whole number in a long (a 64-bit integer: up to about 9.2 × 10¹⁸, so overflow is not a worry for a wallet). Rs 99.70 is 9970. Whole numbers add exactly. Convert to rupees only when printing. (Java's BigDecimal is the other safe choice, for amounts that need more decimal places.)
4. The ledger and double-entry bookkeeping
- A ledger is an append-only list of entries: you only ever add rows; you never edit or delete one. Mistakes are fixed with new rows (a refund is a new transfer back), so the history is always complete.
- Double-entry bookkeeping is the rule accountants have used for centuries: every transfer writes two entries of the same amount: a debit (money going out of one account, written as a minus) and a credit (money coming into another, a plus).
- An account's balance is the sum of its entries. A statement is its entries, listed.
- The sum of all entries in the whole ledger is always zero. If it isn't, money was created or lost: a bug you can detect automatically.
- Money from outside (a top-up from a bank) comes from a system account ("Bank top-ups") that is allowed to go below zero: its negative balance is exactly the money that has come into the wallet system.
import java.util.*;
record Account(String id, String name) {} // a named bucket of money in the books
record Entry(long tx, Account account, long paise, String note) {} // + credit, - debit
class InsufficientFundsException extends RuntimeException { InsufficientFundsException(String m) { super(m); } }
class Ledger {
private final List<Entry> entries = new ArrayList<>(); private long nextTx = 1;
List<Entry> statement(Account a) { return entries.stream().filter(e -> e.account() == a).toList(); }
long balance(Account a) { return statement(a).stream().mapToLong(Entry::paise).sum(); }
long total() { return entries.stream().mapToLong(Entry::paise).sum(); }
long transfer(Account from, Account to, long paise, String note) {
if (paise <= 0) throw new IllegalArgumentException("amount must be positive");
if (!from.id().startsWith("SYS") && balance(from) < paise) throw new InsufficientFundsException(
from.name() + " has " + rs(balance(from)) + ", needs " + rs(paise));
long tx = nextTx++; // double entry: two rows, one tx
entries.add(new Entry(tx, from, -paise, note)); entries.add(new Entry(tx, to, paise, note));
return tx; }
static String rs(long p) { // 9970 paise -> "Rs 99.70"
long a = Math.abs(p); return (p < 0 ? "-" : "") + "Rs " + a / 100 + String.format(".%02d", a % 100); } }
public class Main { public static void main(String[] args) {
Account bank = new Account("SYS-BANK", "Bank top-ups");
Account asha = new Account("W1", "Asha"), rahul = new Account("W2", "Rahul");
Ledger l = new Ledger(); l.transfer(bank, asha, 10_000, "top-up");
l.transfer(asha, rahul, 10, "chai"); l.transfer(asha, rahul, 20, "toffee");
for (Entry e : l.statement(asha)) // Asha's statement
System.out.println(" #" + e.tx() + " " + Ledger.rs(e.paise()) + " " + e.note());
System.out.println("Asha " + Ledger.rs(l.balance(asha)) + ", Rahul " + Ledger.rs(l.balance(rahul))
+ ", sum of ALL entries: " + l.total());
l.transfer(asha, rahul, 50_000, "movie");
} }
Real output:
#1 Rs 100.00 top-up
#2 -Rs 0.10 chai
#3 -Rs 0.20 toffee
Asha Rs 99.70, Rahul Rs 0.30, sum of ALL entries: 0
Exception in thread "main" InsufficientFundsException: Asha has Rs 99.70, needs Rs 500.00
at Ledger.transfer(Main.java:13)
at Main.main(Main.java:28)
- Asha's statement: +Rs 100.00 top-up, -Rs 0.10 chai, -Rs 0.20 toffee. Balances are exact: Rs 99.70 and Rs 0.30.
- Sum of ALL entries: 0, as double entry promises.
- The Rs 500 movie ticket throws
InsufficientFundsException: Asha has Rs 99.70, needs Rs 500.00: a custom exception, a class we made by extendingRuntimeException, so the error says exactly what went wrong. e.account() == acompares two references: "is it the very sameAccountobject?". That is fine here because each account is created once. Records also haveequals, which compares field by field.Math.abs(p)is the absolute value (the number without its sign);String.format(".%02d", a % 100)prints the paise with two digits.
5. Attempt 2: a retried payment pays twice
Asha pays Rs 500. The request reaches the server and the money moves, but the reply is lost on a weak network. Her app sees only a timeout (it stopped waiting). So the app retries, or Asha taps "Pay" again: the same request, a second time.
The program below shows both versions: payNoKey (the attempt) and pay with an idempotency key (the fix), plus transaction states.
import java.util.*;
enum TxState { PENDING, SUCCESS, FAILED }
class Tx { final String key; final long paise; TxState state = TxState.PENDING; String reason = "";
Tx(String k, long p) { key = k; paise = p; }
public String toString() { return key + " " + state + (reason.isEmpty() ? "" : " (" + reason + ")"); } }
class WalletService {
long asha = 100_000, rahul = 0; // paise: Rs 1000 and Rs 0
final Map<String, Tx> byKey = new HashMap<>(); // idempotency key -> its result
Tx payNoKey(long paise) { return run(new Tx("no-key", paise)); }
Tx pay(String key, long paise) {
Tx seen = byKey.get(key);
if (seen != null) return seen; // same key: same answer, no money moves
Tx t = new Tx(key, paise); byKey.put(key, t); return run(t); }
private Tx run(Tx t) {
if (asha < t.paise) { t.state = TxState.FAILED; t.reason = "insufficient balance"; return t; }
asha -= t.paise; rahul += t.paise; t.state = TxState.SUCCESS; return t; } }
public class Main { public static void main(String[] args) {
WalletService a = new WalletService();
a.payNoKey(50_000); a.payNoKey(50_000); // tap, network times out, tap again
System.out.println("No key: Asha Rs " + a.asha / 100 + ", Rahul Rs " + a.rahul / 100);
WalletService b = new WalletService();
System.out.println(b.pay("pay-7f3a", 50_000) + ", retry: " + b.pay("pay-7f3a", 50_000));
System.out.println("With key: Asha Rs " + b.asha / 100 + ", Rahul Rs " + b.rahul / 100);
System.out.println(b.pay("pay-91c2", 80_000)); // only Rs 500 left
} }
Real output:
No key: Asha Rs 0, Rahul Rs 1000
pay-7f3a SUCCESS, retry: pay-7f3a SUCCESS
With key: Asha Rs 500, Rahul Rs 500
pay-91c2 FAILED (insufficient balance)
- No key: Asha Rs 0, Rahul Rs 1000. One ticket, paid twice.
- With the key
pay-7f3a, the retry returns the same transaction, SUCCESS, and moves nothing: Asha still has Rs 500. - The Rs 800 payment with a new key is a transaction in state FAILED (insufficient balance): a record, not a crash.
Idempotency, idempotency keys and transaction states
- An action is idempotent when doing it twice has the same effect as doing it once. Setting a light switch to "on" is idempotent; "pay Rs 500" is not, unless we make it so.
- An idempotency key is a unique id the app creates once per payment intent (usually a random UUID, from
UUID.randomUUID()), and sends with the first try and every retry. A UUID (universally unique identifier) is a 128-bit random id like3f2b8c1e-...; two random ones are practically never equal. - The server stores each key with its result. Key seen before? Return the stored result, move no money. New key? A new payment.
- Transaction states: a payment starts PENDING, then ends as SUCCESS or FAILED. Failed payments are kept as records with a reason, so support can tell Asha exactly what happened. These are the only moves; SUCCESS and FAILED are final (a "refund" is a new transaction, not a change of state).
- With threads, two retries with the same key could arrive at the same moment;
byKey.getthenbyKey.putis check-then-act. The mini project usesConcurrentHashMap.putIfAbsent, which lets exactly one win. In a database: a unique index on the key column.
6. Attempt 3: concurrent transfers
Concurrent transfers are transfers running at the same moment on different threads. Two failures, both on screen:
- No lock: check the balance, then write (with a 20 ms pause standing in for a database call).
- A lock per wallet, taken sender-then-receiver: Asha pays Rahul while Rahul pays Asha.
A deadlock (episode 50) is when two threads each hold one lock and wait forever for the other's. Our demo uses tryLock(1, TimeUnit.SECONDS): try to get the lock, but give up after 1 second and return false, so the program tells us instead of hanging.
import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*;
class Wallet { final String name; long paise; final ReentrantLock lock = new ReentrantLock();
Wallet(String n, long p) { name = n; paise = p; } }
public class Main {
static boolean plain(Wallet from, Wallet to, long p) throws InterruptedException { // no lock
if (from.paise < p) return false; // 1. check
long f = from.paise, t = to.paise; Thread.sleep(20); // ...a database call...
from.paise = f - p; to.paise = t + p; return true; } // 2. write
static boolean locked(Wallet from, Wallet to) throws InterruptedException { // from, then to
from.lock.lock();
try { Thread.sleep(50);
if (!to.lock.tryLock(1, TimeUnit.SECONDS)) return false; // waited 1 s: stuck
try { from.paise -= 100; to.paise += 100; return true; } finally { to.lock.unlock(); }
} finally { from.lock.unlock(); } }
public static void main(String[] args) throws Exception {
Wallet asha = new Wallet("Asha", 50_000), rahul = new Wallet("Rahul", 0); // Rs 500, Rs 0
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<Boolean>> pays = new ArrayList<>(); // phone + laptop, same second
for (int i = 0; i < 2; i++) pays.add(pool.submit(() -> plain(asha, rahul, 30_000)));
System.out.println("Rs 300 twice: " + pays.get(0).get() + ", " + pays.get(1).get()
+ "; Asha Rs " + asha.paise / 100 + ", Rahul Rs " + rahul.paise / 100);
Future<Boolean> f1 = pool.submit(() -> locked(asha, rahul));
Future<Boolean> f2 = pool.submit(() -> locked(rahul, asha));
System.out.println("Asha->Rahul done: " + f1.get() + ", Rahul->Asha done: " + f2.get());
pool.shutdown(); } }
Real output:
Rs 300 twice: true, true; Asha Rs 200, Rahul Rs 300
Asha->Rahul done: false, Rahul->Asha done: true
Rs 300 twice: true, true; Asha Rs 200, Rahul Rs 300: both payments said success. Asha paid Rs 600 out of Rs 500, yet she has Rs 200 left and Rahul received only Rs 300. Both threads read Rs 500 before either wrote, and the second write wiped out the first (a lost update). Rs 300 simply vanished.Asha->Rahul done: false: thread 1 holds Asha's lock and wants Rahul's; thread 2 holds Rahul's and wants Asha's. One of them waited a full second and gave up; only then could the other finish. Which one gives up changes from run to run. With a plainlock()and no timeout, both would wait forever.ReentrantLockis Java's lock class:lock()waits,tryLock(time)waits at most that long,unlock()releases. Always unlock infinally, so an exception can't leave a lock held.
7. The fix: lock ordering for transfers
Lock ordering prevents deadlock: give every wallet a number (an id), and always lock the lower id first, no matter who pays whom. Then both threads want the same lock first; one simply waits its turn, and a circle of waiting can't form. And the balance check and the write both happen while holding both locks, so no other transfer can slip in between.
8. Offers and cashback
- An offer is a rule that decides a reward. It's an interface; each offer is a class: the Strategy pattern again.
PercentCashback(10, 2000)= 10% of the payment, capped at Rs 20 (2,000 paise). - Cashback is never money from thin air. The company puts a budget into a cashback pool account, and cashback is a normal transfer from that pool to the user. So the total money in the system stays the same, and the ledger still sums to zero.
import java.util.concurrent.*; import java.util.concurrent.locks.*;
class Wallet { final int id; final String name; long paise; final Lock lock = new ReentrantLock();
Wallet(int i, String n, long p) { id = i; name = n; paise = p; } }
interface Offer { long cashback(long paise); }
record PercentCashback(int percent, long capPaise) implements Offer { // 10%, up to Rs 20
public long cashback(long paise) { return Math.min(capPaise, paise * percent / 100); } }
public class Main {
static boolean transfer(Wallet from, Wallet to, long p) throws InterruptedException {
Wallet first = from.id < to.id ? from : to, second = first == from ? to : from; // lower id first
first.lock.lock();
try { Thread.sleep(50); second.lock.lock();
try { if (from.paise < p) return false; // check AND write inside the locks
from.paise -= p; to.paise += p; return true; }
finally { second.lock.unlock(); } } finally { first.lock.unlock(); } }
public static void main(String[] args) throws Exception {
Wallet pool = new Wallet(0, "Cashback pool", 100_000), asha = new Wallet(1, "Asha", 50_000),
rahul = new Wallet(2, "Rahul", 0);
ExecutorService ex = Executors.newFixedThreadPool(2);
Future<Boolean> a = ex.submit(() -> transfer(asha, rahul, 30_000)); // phone + laptop
Future<Boolean> b = ex.submit(() -> transfer(asha, rahul, 30_000));
System.out.println("Rs 300 twice: " + a.get() + ", " + b.get() + "; Asha Rs " + asha.paise / 100);
Future<Boolean> f1 = ex.submit(() -> transfer(asha, rahul, 100)); // opposite directions
Future<Boolean> f2 = ex.submit(() -> transfer(rahul, asha, 100));
System.out.println("Asha->Rahul done: " + f1.get() + ", Rahul->Asha done: " + f2.get());
Offer offer = new PercentCashback(10, 2_000); long back = offer.cashback(30_000); // on Rs 300
transfer(pool, asha, back); // cashback comes FROM the pool
System.out.println("Cashback Rs " + back / 100 + ", Asha Rs " + asha.paise / 100 + ", pool Rs "
+ pool.paise / 100 + ", all wallets Rs " + (pool.paise + asha.paise + rahul.paise) / 100);
ex.shutdown(); } }
Real output:
Rs 300 twice: true, false; Asha Rs 200
Asha->Rahul done: true, Rahul->Asha done: true
Cashback Rs 20, Asha Rs 220, pool Rs 980, all wallets Rs 1500
Rs 300 twice: true, false; Asha Rs 200: one payment succeeds, the other is refused, and the money adds up.- Both opposite transfers: done: true. No deadlock, even with a 50 ms pause while holding the first lock.
- Cashback Rs 20: 10% of Rs 300 is Rs 30, but the cap is Rs 20. The pool drops from Rs 1000 to Rs 980; Asha goes from Rs 200 to Rs 220; all wallets together still hold Rs 1500, exactly what we started with (Rs 1000 + Rs 500 + Rs 0).
Lockis the interface;ReentrantLockthe class.Future<Boolean>is a handle to a task's result, collected withget().
9. The class diagram
User ── owns ──▶ Wallet ── has ──▶ Account(id, name) money: long paise, never double
Ledger: Entry(tx, account, ±paise, note) · every transfer = 2 entries (debit −, credit +)
balance(account) = sum of its entries · statement(account) = its entries · sum of ALL = 0
Transaction(idempotency key, amount, state) · TxState: PENDING ─▶ SUCCESS | FAILED
pay(key): seen key → return the first result, move no money
transfer(): lock the LOWER wallet id first, then the other; check + write inside both locks
Offer ◁─ PercentCashback(10%, cap Rs 20) · cashback = transfer FROM the cashback pool account
10. Interview follow-ups
| Question | Answer |
|---|---|
| Many servers, not one JVM? | Java locks protect one JVM's memory. Do the transfer inside one database transaction and lock the two account rows in id order (SELECT ... FOR UPDATE, lower id first): the same lock ordering idea. |
| Two retries with the same key arrive at the same moment? | A unique index on the key column: only one insert wins; the other reads the stored result. In memory: putIfAbsent. |
| How long do you keep keys? | A limited time (for example 24 hours), long enough for every realistic retry. |
| Refunds? | Never edit the ledger. A refund is a new transfer in the opposite direction, linked to the original. |
| Monthly statement? | The account's entries for the month, in date order, with an opening balance (the balance at the start of the month) and a closing balance. |
| Do you sum the whole ledger for every balance? | No: keep a cached balance on the account, updated in the same transaction as the entries, and check it against the ledger regularly (reconciliation). |
| Limits and fraud? | Daily limits per wallet and fraud checks run before a payment becomes PENDING. |
| Paying with a bank, not the wallet balance? | The bank call is slow and can fail: keep the transaction PENDING, and move it to SUCCESS or FAILED when the bank answers. |
11. Common mistakes
| Mistake | What you see (real) | Fix |
|---|---|---|
double for money |
Rahul got Rs 0.30000000000000004 |
long paise (or BigDecimal) |
| No balance check | Asha: Rs -400.3 |
Check; throw InsufficientFundsException or mark FAILED |
| No record of transfers | "where did my money go?" | An append-only ledger, double entry |
| Single entry (only the debit) | totals stop adding up | Debit and credit: sum of all entries = 0 |
| Retry with no key | No key: Asha Rs 0, Rahul Rs 1000 |
Idempotency key: retry: pay-7f3a SUCCESS, Asha Rs 500 |
| Failure as a crash | lost information about what happened | A FAILED transaction with a reason |
| Check, then write, no lock | Rs 300 twice: true, true; Asha Rs 200, Rahul Rs 300 |
Check and write inside the locks |
| Lock sender, then receiver | Asha->Rahul done: false (stuck) |
Lock the lower id first |
| Cashback "from nowhere" | totals grow, books don't balance | Transfer from a cashback pool account |
| Editing past entries for a refund | history lost | A new reverse transfer |
Mini project: a small wallet service
One program that puts it together: system accounts (bank, cashback pool), user accounts, a ledger, idempotency keys with putIfAbsent, transaction states, lock ordering, a cashback offer, a refund as a reverse transfer, statements, and a load test with 4 threads making 4,000 random transfers.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
enum TxState { PENDING, SUCCESS, FAILED }
record Entry(long tx, String account, long paise, String note) {} // + credit, - debit
class Account {
final int id; final String name; final boolean system; // system: a company account
long paise; // cached balance, guarded by lock
final Lock lock = new ReentrantLock();
Account(int id, String name, boolean system) { this.id = id; this.name = name; this.system = system; }
}
class Transaction {
final long id; final String key; final Account from, to; final long paise;
TxState state = TxState.PENDING; String reason = "";
Transaction(long id, String key, Account from, Account to, long paise) {
this.id = id; this.key = key; this.from = from; this.to = to; this.paise = paise;
}
public String toString() {
return "#" + id + " " + from.name + "->" + to.name + " " + Money.rs(paise) + " " + state
+ (reason.isEmpty() ? "" : " (" + reason + ")");
}
}
class Money {
static String rs(long p) { long a = Math.abs(p); return (p < 0 ? "-" : "") + "Rs " + a / 100 + String.format(".%02d", a % 100); }
}
interface Offer { long cashback(long paise); }
record PercentCashback(int percent, long capPaise) implements Offer {
public long cashback(long paise) { return Math.min(capPaise, paise * percent / 100); }
}
class WalletService {
private final List<Entry> ledger = Collections.synchronizedList(new ArrayList<>());
private final ConcurrentHashMap<String, Transaction> byKey = new ConcurrentHashMap<>();
private long nextTx = 1;
private synchronized long nextId() { return nextTx++; }
Transaction pay(String key, Account from, Account to, long paise) {
if (paise <= 0) throw new IllegalArgumentException("amount must be positive");
Transaction fresh = new Transaction(nextId(), key, from, to, paise);
Transaction seen = byKey.putIfAbsent(key, fresh); // one winner per key, even at the same moment
if (seen != null) return seen;
move(fresh);
return fresh;
}
private void move(Transaction t) {
Account first = t.from.id < t.to.id ? t.from : t.to, second = first == t.from ? t.to : t.from;
first.lock.lock();
try {
second.lock.lock();
try {
if (!t.from.system && t.from.paise < t.paise) { t.state = TxState.FAILED; t.reason = "insufficient balance"; return; }
t.from.paise -= t.paise; t.to.paise += t.paise;
ledger.add(new Entry(t.id, t.from.name, -t.paise, t.key));
ledger.add(new Entry(t.id, t.to.name, t.paise, t.key));
t.state = TxState.SUCCESS;
} finally { second.lock.unlock(); }
} finally { first.lock.unlock(); }
}
Transaction refund(Transaction original) { // a new reverse transfer, never an edit
if (original.state != TxState.SUCCESS) throw new IllegalStateException("only a SUCCESS can be refunded, this is " + original.state);
return pay("refund-" + original.key, original.to, original.from, original.paise);
}
List<Entry> statement(String account) {
synchronized (ledger) { return ledger.stream().filter(e -> e.account().equals(account)).toList(); }
}
long ledgerTotal() { synchronized (ledger) { return ledger.stream().mapToLong(Entry::paise).sum(); } }
}
public class Main {
public static void main(String[] args) throws Exception {
WalletService w = new WalletService();
Account bank = new Account(0, "Bank", true), pool = new Account(1, "CashbackPool", true);
Account asha = new Account(2, "Asha", false), rahul = new Account(3, "Rahul", false), shop = new Account(4, "ChaiShop", false);
w.pay("fund-pool", bank, pool, 50_000);
System.out.println(w.pay("topup-1", bank, asha, 100_000));
Transaction chai = w.pay("pay-c1", asha, shop, 3_000);
System.out.println(chai + ", retry: " + w.pay("pay-c1", asha, shop, 3_000));
Offer offer = new PercentCashback(10, 2_000);
System.out.println(w.pay("cb-pay-c1", pool, asha, offer.cashback(chai.paise)));
System.out.println(w.pay("pay-big", asha, rahul, 500_000));
System.out.println(w.refund(chai));
ExecutorService ex = Executors.newFixedThreadPool(4); // 4 threads, 4,000 random transfers
List<Account> people = List.of(asha, rahul, shop);
List<Future<?>> jobs = new ArrayList<>();
for (int t = 0; t < 4; t++) {
int seed = t;
jobs.add(ex.submit(() -> {
Random r = new Random(seed);
for (int i = 0; i < 1_000; i++) {
Account a = people.get(r.nextInt(3)), b = people.get(r.nextInt(3));
if (a != b) w.pay("load-" + seed + "-" + i, a, b, 1 + r.nextInt(500));
}
}));
}
for (Future<?> f : jobs) f.get();
ex.shutdown();
long users = asha.paise + rahul.paise + shop.paise;
System.out.println("after the load test: users hold " + Money.rs(users) + ", pool " + Money.rs(pool.paise)
+ ", ledger total " + w.ledgerTotal());
long fromStatement = w.statement("Rahul").stream().mapToLong(Entry::paise).sum();
System.out.println("Rahul: balance " + Money.rs(rahul.paise) + ", sum of his statement " + Money.rs(fromStatement)
+ ", match: " + (fromStatement == rahul.paise));
}
}
Real output:
#2 Bank->Asha Rs 1000.00 SUCCESS
#3 Asha->ChaiShop Rs 30.00 SUCCESS, retry: #3 Asha->ChaiShop Rs 30.00 SUCCESS
#5 CashbackPool->Asha Rs 3.00 SUCCESS
#6 Asha->Rahul Rs 5000.00 FAILED (insufficient balance)
#7 ChaiShop->Asha Rs 30.00 SUCCESS
after the load test: users hold Rs 1003.00, pool Rs 497.00, ledger total 0
Rahul: balance Rs 26.64, sum of his statement Rs 26.64, match: true
Notes on the design:
- Transaction #1 funds the cashback pool (it isn't printed). Ids jump from #3 to #5 because the retry of
pay-c1built a transaction (#4) that lost theputIfAbsentand was thrown away; the retry returned #3, the original. - Cashback on the Rs 30 chai is Rs 3.00 (10%, under the Rs 20 cap), paid from the pool.
- The Rs 5000 payment is FAILED (insufficient balance).
- The refund #7 is a new transfer from the chai shop back to Asha; the original #3 stays in the ledger.
- After 4,000 concurrent random transfers, users still hold Rs 1003.00 (Rs 1000 top-up + Rs 3 cashback), the pool Rs 497.00, and the ledger total is 0. Rahul's balance changes from run to run (the threads interleave differently), but it always matches the sum of his statement.
Collections.synchronizedListmakes the list safe to add to from many threads; reading it (the stream) is done insidesynchronized (ledger).
Practice
1. Asha has Rs 50.00. Write the ledger entries for: top-up Rs 100 from the bank, pay the chai shop Rs 12.50. What is the sum of all entries?
Answer
Before: whatever gave Asha her Rs 50 (say tx #1: Bank −5000, Asha +5000). Tx #2: Bank −10000, Asha +10000. Tx #3: Asha −1250, ChaiShop +1250. Asha's balance = 5000 + 10000 − 1250 = 13750 paise = Rs 137.50. The sum of all entries is 0, as always.
2. Why is "set Asha's balance to Rs 500" idempotent, while "add Rs 500 to Asha's balance" is not? Which one is a payment?
Answer
Setting a value twice leaves the same value; adding twice adds Rs 1000. A payment is an "add/subtract", so it needs an idempotency key to be safe to retry.
3. In section 7, why does locking the lower id first prevent deadlock?
Answer
A deadlock needs a circle: T1 waits for a lock T2 holds, and T2 waits for one T1 holds. If every thread takes locks in the same global order (lower id first), the thread that holds the lower lock can always get the higher one eventually, and no thread holding a higher lock ever waits for a lower one. No circle can form.
4. Add a FlatCashback(2500) offer: Rs 25 back on any payment of Rs 200 or more.
Answer
record FlatCashback(long paise) implements Offer { public long cashback(long p) { return p >= 20_000 ? paise : 0; } } (Rs 200 = 20,000 paise). Only pay the cashback transfer when the amount is above zero. Nothing else changes.
5. What goes wrong if cashback is added with asha.paise += 2000 instead of a transfer from the pool?
Answer
Money appears from nowhere: the total money in the system grows by Rs 20, there are no ledger entries for it (Asha's statement doesn't match her balance), and the company can't see how much the offer cost.
6. How would you make a daily limit of Rs 10,000 per wallet?
Answer
Before moving money, sum today's debit entries for the sender (or keep a daily counter, reset each day) and mark the transaction FAILED with reason "daily limit" if the new amount would cross 1,000,000 paise. Do the check inside the locks, like the balance check.
Quick quiz
Rahul has Rs 0. Asha pays him Rs 200 with key pay-1; the reply times out. The app retries with key pay-1. Then Asha pays Rs 50 with key pay-2. How much does Rahul have? (a) Rs 200 (b) Rs 250 (c) Rs 400 (d) Rs 450
Answer
(b) Rs 250. The retry with pay-1 returns the stored result and moves no money; pay-2 is a new payment. Rs 200 + Rs 50 = Rs 250. (d) is what you get if the key does nothing.
Interview questions
- What are the main classes of a digital wallet? Wallet, Account, Transaction, Entry (ledger row), a WalletService, offers, and system accounts like a cashback pool.
- Why not use
doublefor money? Binary fractions can't hold 0.1 exactly:0.30000000000000004. Use alongof paise orBigDecimal. - What is a ledger? An append-only list of entries; balances and statements are derived from it.
- What is double-entry bookkeeping? Every transfer writes a debit and a credit of the same amount; all entries sum to zero, which detects bugs.
- What is an idempotency key? A unique id per payment intent, created by the client and sent with every retry; the server returns the stored result for a seen key.
- What are the transaction states? PENDING, then SUCCESS or FAILED; failed ones are kept with a reason; refunds are new transactions.
- Two payments at the same moment overspend the wallet. Why, and how do you fix it? Check-then-act without a lock; do the check and the write while holding the account's lock (or in one database transaction).
- How do you avoid deadlock in transfers? Lock ordering: always lock the lower account id first.
- How is cashback paid? As a transfer from a funded cashback pool account, so no money is created.
- What changes with many servers? Database transactions with row locks in id order, and a unique index on idempotency keys.
Glossary
| Term | Meaning, with an example |
|---|---|
| Digital wallet | An app that holds money for you, so you can pay or send money with a tap |
| Digital wallet requirements | Top up, pay, transfer, statement, safe retries, safe concurrency, offers, no money lost or created |
| Wallet | What the user sees in the app: balance, history, a Pay button |
| Account | A named bucket of money in the books: Asha's account, the cashback pool |
| System account | A company account, such as "Bank top-ups" or the cashback pool; may go below zero |
| Transaction | One movement of money: from, to, amount, state |
| Transfer | Money out of one account and the same amount into another |
| Top-up | Adding money to the wallet from a bank |
| Paise | The smallest unit of the rupee; 100 paise = Rs 1; Rs 99.70 = 9970 paise |
| long | Java's 64-bit whole-number type; holds paise exactly |
| double | Java's binary floating-point type; can't hold 0.1 exactly: 0.30000000000000004 |
| Binary fraction | A fraction made of halves, quarters, eighths...; 0.1 is an endless one |
| BigDecimal | Java's exact decimal number class, another safe choice for money |
| Overdraft | Spending more than the balance: Rs -400.3 |
| Ledger | An append-only list of every money movement: the khata |
| Append-only | You only add rows; you never edit or delete one |
| Entry | One ledger row: transaction id, account, ±paise, note |
| Double-entry bookkeeping | Every transfer writes a debit and a credit of the same amount |
| Debit | Money going out of an account: −10 paise for chai |
| Credit | Money coming into an account: +10 paise for the shop |
| Balance | The sum of an account's entries |
| Statement | An account's entries, listed: "#2 -Rs 0.10 chai" |
| Opening balance | The balance at the start of a statement period |
| Reconciliation | Checking cached balances against the ledger regularly |
| Custom exception | An exception class you write: InsufficientFundsException extends RuntimeException |
| Timeout | Giving up waiting after a set time |
| Retry | Sending the same request again after a timeout or error |
| Idempotent | Doing it twice has the same effect as doing it once |
| Idempotency key | A unique id per payment intent, sent with every retry: pay-7f3a |
| UUID | A 128-bit random id, from UUID.randomUUID(); practically never repeats |
| Transaction states | PENDING, SUCCESS, FAILED |
| PENDING | Started, not finished yet |
| SUCCESS / FAILED | The payment happened / did not, with a reason: "insufficient balance" |
| Refund | A new reverse transfer, never an edit of the original |
| enum | A Java type with a fixed list of values: enum TxState { PENDING, SUCCESS, FAILED } |
| Concurrent transfers | Transfers running at the same moment on different threads |
| Thread | One line of work running in a program |
| ExecutorService / thread pool | A team of ready threads: Executors.newFixedThreadPool(2) |
| Future | A handle to a task's result, collected with get() |
| Race condition | The result depends on which thread runs first |
| Check-then-act | Checking and acting as two steps with a gap between them |
| Lost update | One thread's write wipes out another's: Rs 300 vanished |
| Lock | Lets only one thread at a time into a piece of code |
| ReentrantLock | Java's lock class: lock(), tryLock(time), unlock() |
| tryLock with timeout | Try to get a lock, give up after a time and return false |
| Deadlock | Two threads each hold one lock and wait forever for the other's (episode 50) |
| Lock ordering for transfers | Always lock the lower account id first, so no circle of waiting can form |
| putIfAbsent | ConcurrentHashMap method: put only if the key is missing; exactly one caller wins |
| Unique index | A database rule that refuses a second row with the same key |
| Offer | A rule that decides a reward; here an interface |
| Cashback | Money given back after a payment: 10% up to Rs 20 |
| Cap | An upper limit: 10% of Rs 300 = Rs 30, capped to Rs 20 |
| Cashback pool | A company account funded with the offer budget; cashback is a transfer from it |
| Strategy pattern | One interface, one class per rule (episode 34): each offer is a class |
| Record | A short Java class for plain data: record Entry(long tx, Account account, long paise, String note) |
Summary
- The digital wallet requirements give Wallet, Account and Transaction, and one basic action: the transfer.
- A
doublebalance gave Rs 0.30000000000000004, an overdraft of Rs -400.3, and no record. Money is alongcount of paise. - A ledger with double-entry bookkeeping writes a debit and a credit for every transfer; balances and statements come from the entries, and all entries sum to 0.
- A retry without a key charged Asha twice; an idempotency key makes the retry return the first result. Transaction states (PENDING, SUCCESS, FAILED) keep failures as records.
- Concurrent transfers without a lock let two payments succeed and lost Rs 300; locks taken sender-then-receiver deadlocked. Lock ordering (lower id first) with the check inside the locks fixes both.
- Offers and cashback are strategies, paid by a transfer from a cashback pool, so the total never changes.
- Next episode: an in-memory file system: files and folders with the Composite pattern, paths, mkdir, ls and cd.