Designing a Payment Wallet System
Difficulty: Medium Patterns: Command, Observer, Singleton Asked at: PhonePe, Razorpay, PayTM, Google Pay, Amazon
Functional Requirements
- Create Wallet — register a new wallet for a given user ID with an initial balance of zero
- Credit / Debit — add money (credit) or withdraw money (debit) from a wallet with overdraft prevention
💡 Credit means money in, debit means money out — the bank’s vocabulary, not a card type. Overdraft prevention means a debit that would push the balance below zero is refused outright rather than allowed and chased later. - P2P Transfer — atomically debit sender and credit receiver in a single operation
💡 Peer-to-peer (P2P) = wallet to wallet, with no merchant in the middle. “Atomically” means an onlooker never sees a state where the sender has been debited but the receiver has not been credited. - Transaction History — maintain a full ledger of all operations with timestamp, type, amount, and balance-after
💡 A ledger is an append-only list of money movements — you never edit a past row, you add a correcting one. Real wallets go further with double-entry bookkeeping, where every rupee leaving one account is written as a matching entry arriving in another, so the books must sum to zero. - Idempotent Operations — given the same transaction ID, the system returns the same result without re-executing (no double-spend)
💡 Idempotent = running the same request twice has the same effect as running it once. It is what makes a retry after a network timeout safe, and without it a dropped response means a customer pays twice. - Balance Inquiry — retrieve current wallet balance in O(1)
Non-Functional Requirements
- Thread-safety — concurrent credits, debits, and transfers must not corrupt balances or produce race conditions
💡 Thread-safety = correct results even when several threads run through the same code at once. A race condition is the failure it prevents: two debits both read a balance of 100, both decide 80 is affordable, and the wallet ends up at -60. - Atomicity for transfers — a P2P transfer either completes fully (both debit and credit) or not at all
- Audit trail — every balance mutation is recorded immutably in the ledger for reconciliation
💡 Immutably = eachTransactionis built once and then never modified, so history cannot be rewritten. Reconciliation is the payoff: you can replay every entry and check the computed balance matches the stored one.
Core Entities
| Entity | Description |
|---|---|
Wallet |
Holds user ID, current balance, transaction ledger, and a lock for thread-safety |
Transaction |
Immutable record: txn ID, type, amount, balance after, timestamp, counterparty |
TransactionType |
Enum: CREDIT, DEBIT, TRANSFER_IN, TRANSFER_OUT |
WalletService |
Singleton orchestrator — manages all wallets, enforces idempotency, executes transfers |
TransferCommand |
Encapsulates a P2P transfer as a command object (Command pattern) |
WalletObserver |
Interface notified on balance changes (Observer pattern) |
IdempotencyStore |
Tracks processed transaction IDs to prevent duplicate execution |
💡 The one money rule worth saying out loud before you write the amount field: currency belongs in exact integer paise or a BigDecimal, never in binary floating point, because a double cannot represent 0.10 exactly and the rounding error compounds across a ledger. Learn more →
Class Diagram
classDiagram
class TransactionType {
<<enumeration>>
CREDIT
DEBIT
TRANSFER_IN
TRANSFER_OUT
}
class Transaction {
-String txnId
-TransactionType type
-long amountPaise
-long balanceAfterPaise
-LocalDateTime timestamp
-String counterpartyUserId
+getTxnId() String
+getType() TransactionType
+getAmountPaise() long
+getBalanceAfterPaise() long
+getTimestamp() LocalDateTime
}
class Wallet {
-String userId
-long balancePaise
-List~Transaction~ ledger
-ReentrantLock lock
+credit(long amountPaise, String txnId) Transaction
+debit(long amountPaise, String txnId) Transaction
+getBalancePaise() long
+getStatement() List~Transaction~
}
class WalletObserver {
<<interface>>
+onBalanceChange(String userId, long oldPaise, long newPaise)
}
class TransferCommand {
-String txnId
-Wallet sender
-Wallet receiver
-long amountPaise
+execute() boolean
}
class WalletService {
-Map~String, Wallet~ wallets
-Set~String~ processedTxnIds
-List~WalletObserver~ observers
-ReentrantLock globalLock
+createWallet(String userId) Wallet
+credit(String userId, long amountPaise, String txnId) Transaction
+debit(String userId, long amountPaise, String txnId) Transaction
+transfer(String fromId, String toId, long amountPaise, String txnId) boolean
+getBalancePaise(String userId) long
+getStatement(String userId) List~Transaction~
+addObserver(WalletObserver)
}
WalletService --> Wallet
WalletService --> WalletObserver
WalletService --> TransferCommand
Wallet --> Transaction
Transaction --> TransactionType
TransferCommand --> Wallet
💡 Reading the arrows: a dashed arrow with a hollow head (<|..) would mean “implements this interface”, and the plain arrows here (-->) mean “holds a reference to” — so WalletService --> Wallet says the service owns the wallets, not that it inherits from one. Learn more →
Key classes:
WalletService— the front door and the only class that coordinates. It owns the wallet registry, the idempotency store and the observer list, and every public operation starts here.Wallet— one user’s balance plus their ledger plus their own lock. It enforces its own invariants (no negative amounts, no overdraft) so no caller can leave it in an illegal state.Transaction— one immutable row of history: what happened, how much, the balance it left behind, when, and who the other party was. This is the audit trail.TransferCommand— a transfer packaged as an object with anexecute()method. It is the class that knows the two-wallet locking rule, which keeps that tricky logic out of bothWalletandWalletService.WalletObserver— the notification boundary. Push alerts, fraud checks and analytics implement this and get called after balances change, without the wallet knowing they exist.TransactionType— the fixed set of four movements. KeepingTRANSFER_OUTdistinct fromDEBITis what lets a statement show a peer transfer differently from a withdrawal.
Design Patterns
| Pattern | Where | Why |
|---|---|---|
| Command | TransferCommand encapsulates P2P transfer logic |
Decouples transfer execution from the service. Enables undo/retry, logging of operations as first-class objects. |
| Observer | WalletObserver notified on balance changes |
Decouples notifications (SMS, push, audit log) from core wallet logic. Adding a new notification channel = one new observer. |
| Singleton | WalletService is the single entry point |
Ensures one authoritative source of truth for wallet state, idempotency store, and observer registry. |
💡 Command pattern = turn “do this thing” into an object with an execute() method, instead of a method buried in a service. Because the transfer is now a value, you can log it, queue it, retry it or hand it to an undo stack.
Discussion
Newest first