Design a Bank Account System
0%
Editorial Solution
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
TransactionType Enum
Account Hierarchy
Design Patterns
Template Method: Account Operations
Strategy Pattern: Interest Calculation
Observer Pattern: Transaction Notifications
Define Class Members / Write Code
Transaction (Immutable)
Account with Thread Safety
BankService with Deadlock Prevention
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Per-Account Locking
Deadlock Prevention via Lock Ordering
ReadWriteLock for Balance Queries
Horizontal Scaling
Create/Explain Your Diagrams
Future Improvements
Table of Contents
A bank account system sounds like a simple balance tracker: deposit adds, withdrawal subtracts. But underneath, the system must guarantee that concurrent operations from multiple ATMs never produce overdrafts, that transfers between accounts are atomic (both succeed or neither takes effect), that every operation creates an immutable audit record, and that different account types (checking, savings) enforce different rules through polymorphism. The design challenge is building a thread-safe financial system where money is never created or destroyed by race conditions.
Interview Dialogue
Functional Requirements
- Deposit, Withdraw, and Transfer - Deposit adds funds to an account. Withdraw removes funds, rejecting the operation if balance is insufficient. Transfer atomically debits one account and credits another.
- Accurate Balance and Overdraft Prevention - Account balance is always non-negative for standard accounts. Every operation validates fund sufficiency before execution.
- Transaction History - Every deposit, withdrawal, and transfer creates an immutable Transaction record with timestamp, type, amount, and resulting balance. History is append-only.
- Multiple Account Types - Checking and savings accounts with different rules (savings may have monthly withdrawal limits or earn interest).
Non-Functional Requirements
- Thread Safety - Multiple ATMs or banking channels may operate on the same account simultaneously. Balance checks and updates must be atomic to prevent overdrafts and lost updates.
- Auditability - Transaction records are immutable once created. The system preserves a complete, tamper-proof history.
A customer walks up to an ATM and inserts their card. The system needs to look up who this person is, find the right account, check the balance, and process the withdrawal, all while another ATM across town might be hitting the same account at the same instant. That interaction reveals every core object.
Start by scanning the requirements for nouns. Each one is a candidate class. "Customer" with "name, ID, and contact details" maps directly to a Customer class. "Account" holding a "balance" and "transaction history" becomes Account. "Deposit, withdrawal, transfer" suggest a Transaction record. "Checking and savings" point to CheckingAccount and SavingsAccount subclasses. "Audit record with timestamp, type, amount" reinforces Transaction as an immutable value object. Not every noun survives. "ATM" is an access channel rather than a domain class, but the nouns give you a strong starting lineup to refine.
Walk through a customer using an ATM and see where the objects emerge.
A Customer walks up with a name, ID, and contact details. They own one or more accounts. The Customer is the human identity; accounts are the financial containers.
The customer selects their checking account. An Account holds an account number, an owner (Customer) reference, a balance, and a list of Transaction records. It provides deposit(), withdraw(), and getBalance() methods.
Why store balance as a field rather than computing it from transactions? Computing from transactions means scanning the entire history on every balance check. For an account with 10,000 transactions, that is 10,000 additions per query. Storing the balance gives O(1) reads. The trade-off is that the stored balance must always match the sum of transactions, which the lock ensures.
Each operation creates a Transaction: an immutable record with a unique ID, type (DEPOSIT, WITHDRAWAL, TRANSFER_IN, TRANSFER_OUT), amount, timestamp, resulting balance, and optional counterparty account. Immutability makes transactions thread-safe to read and tamper-proof for auditing.
A BankService orchestrates multi-account operations like transfers. It handles deadlock prevention through consistent lock ordering by account number.
A TransactionType enum (DEPOSIT, WITHDRAWAL, TRANSFER_IN, TRANSFER_OUT) categorizes each transaction for reporting and filtering.
Why an enum for TransactionType instead of strings? Strings like 'deposit' and 'Deposit' both compile fine but mean different things at runtime. An enum constrains the set at compile time - the compiler rejects any value not in the enum, eliminating an entire class of silent bugs.
Composition: Account owns Transactions
Transaction records are created by Account operations and stored in the Account's history list. They have no identity outside the Account. If an Account is closed and archived, its transactions go with it.
Composition: Customer owns Accounts
A Customer has one or more Accounts. The accounts are created for this customer and linked to their identity. Closing a customer relationship closes their accounts.
Immutable Value Object: Transaction
Once created, a Transaction's fields cannot be modified. This is stronger than composition: the child is not just lifecycle-bound but also state-frozen. This ensures the audit trail is tamper-proof.
Service: BankService orchestrates Accounts
BankService has a registry of all accounts and provides cross-account operations. It does not own accounts (they are owned by Customers) but coordinates operations between them. This is a service relationship, not ownership.
Lock Ordering: BankService prevents deadlocks
Transfer locks two accounts. BankService always locks accounts in ascending account-number order, preventing circular wait (the necessary condition for deadlock).
Why a separate BankService instead of putting transfer logic on Account? A transfer requires coordinating two accounts that know nothing about each other. If Account handled transfers, it would need to reach into another Account and manage its lock - violating encapsulation and creating tight coupling between peers.
TransactionType Enum
Four types. TRANSFER_IN and TRANSFER_OUT are separate because each account sees the transfer from its own perspective: the source account records TRANSFER_OUT, the destination records TRANSFER_IN.
Account Hierarchy
The base Account class handles deposit, withdraw, getBalance, and transaction history. Subclasses add type-specific rules:
- CheckingAccount might allow a small overdraft or charge monthly fees.
- SavingsAccount might limit monthly withdrawals to 6 (as per banking regulations) or calculate interest.
Both subclasses inherit the core balance management and thread safety from Account. They override withdraw() to add their specific rules (checking the monthly withdrawal count for savings, applying overdraft fees for checking).
Why inheritance here? CheckingAccount and SavingsAccount share significant behavior (balance tracking, transaction recording, lock management). They differ in specific rules. An abstract base class captures the shared behavior, and subclasses add rule-specific overrides. This is a legitimate use of inheritance because the subclasses are genuinely specialized versions of the parent.
Why not use an interface instead of an abstract class for Account? An interface cannot hold the balance field, the transaction list, or the ReentrantLock. Each subclass would re-implement identical deposit(), getBalance(), and lock management code. The abstract class captures hundreds of lines of shared stateful behavior that an interface cannot.
Template Method: Account Operations
Account.deposit() and Account.withdraw() follow a template: acquire lock, validate, update balance, create transaction, release lock. Subclasses override the validation step (SavingsAccount checks monthly limit) but inherit the lock management and transaction recording. The base class ensures that locking is never forgotten.
Strategy Pattern: Interest Calculation
Different account types calculate interest differently. SavingsAccount earns compound interest. CheckingAccount might earn nothing. A future MoneyMarketAccount might have tiered rates. An InterestStrategy interface with calculateInterest(double balance, int days) allows each account type to use a different strategy without modifying the Account class.
Observer Pattern: Transaction Notifications
When a transaction occurs, the system may need to notify fraud detection, send email receipts, or update a dashboard. An AccountObserver interface with onTransaction(Transaction) allows these concerns to register with the Account and receive notifications without the Account knowing about fraud detection or email services.
Build this one bottom-up: immutable Transaction first, then single-account operations on Account, and only then BankService.transfer(). Transfer is what interviewers ask about, but it is only convincing if deposit and withdraw are already correct under one account lock.
Transaction (Immutable)
The first class to implement is Transaction because everything else depends on it. Every deposit, withdrawal, and transfer creates one. Notice that all fields are final and there are no setters. Once a Transaction is created, its record is frozen forever.
All fields are final. No setters. The transactionId is generated automatically. The timestamp captures the exact moment of creation.
Account with Thread Safety
The Account class is where thread safety lives. The natural question is: why a ReentrantLock instead of synchronized methods? Because the transfer operation in BankService needs to acquire two locks before modifying either account, and synchronized methods do not expose the lock object for external coordination.
Do not treat balance validation and deduction as two separately safe steps. Checking funds outside the same lock that performs the debit recreates the classic double-withdrawal race, even if both lines look correct in isolation.
BankService with Deadlock Prevention
BankService is the only class that coordinates multiple accounts. The critical design choice is the lock ordering: always lock the lower-numbered account first. This is often the first thing interviewers probe, because getting it wrong means deadlocks in production.
The transfer method acquires both locks before checking balance or modifying either account. This makes the entire transfer atomic. The consistent lock ordering (by account number) prevents deadlock.
Run and Test
Browse the complete solution code and run it. Try modifying the code to experiment with the design.
Single Responsibility Principle
- Account manages balance and single-account operations.
- Transaction records a single financial event.
- Customer holds identity and account relationships.
- BankService orchestrates multi-account operations.
Open/Closed Principle
- Adding SavingsAccount with interest or CheckingAccount with overdraft requires subclassing Account. BankService and Transaction require no modification.
- Adding an InterestStrategy requires implementing one interface. Account gains a strategy field but its core logic is unchanged.
Liskov Substitution Principle
- SavingsAccount and CheckingAccount can replace Account anywhere. A SavingsAccount withdraw() may enforce additional rules but still honors the base contract (rejects insufficient funds, records transactions).
Interface Segregation Principle
- If AccountObserver were added, it would have one focused method: onTransaction(Transaction). Implementations are not forced to handle unrelated events.
Dependency Inversion Principle
- BankService depends on Account (the abstraction), not on specific account types. Transfer works with any Account subclass without modification.
Per-Account Locking
Think about it this way: a bank has millions of accounts, but at any given moment, most of them are idle. Locking the entire bank for one withdrawal would be like closing every highway because one intersection has a red light.
Each Account has its own ReentrantLock. Operations on different accounts run in parallel with zero contention. Only operations on the same account (or overlapping transfer pairs) contend. A bank with 1 million accounts has 1 million independent locks, enabling full parallelism.
The double-withdrawal race, made concrete:
- Thread A reads account.balance = $100
- Thread B reads account.balance = $100
- Thread A checks $100 >= $80, passes validation
- Thread B checks $100 >= $80, passes validation
- Thread A sets balance = $100 - $80 = $20
- Thread B sets balance = $20 - $80 = -$60
- Bug: Both withdrawals succeeded. The bank lost $60.
Deadlock Prevention via Lock Ordering
BankService.transfer() always locks accounts in ascending account-number order. This eliminates circular wait, the necessary condition for deadlock. The ordering is stable because account numbers are unique and immutable.
The lock-ordering strategy in BankService.transfer() is the most important design decision. Without it, deadlocks between concurrent transfers would freeze the system. Always lock accounts in ascending account-number order.
In interviews, the deadlock prevention via lock ordering is the most impressive design detail. Walk through the scenario: 'Transfer A-to-B and B-to-A both lock A first because A has the lower account number. No circular wait. No deadlock.'
ReadWriteLock for Balance Queries
Balance queries (getBalance, getTransactionHistory) are read operations. Multiple ATMs displaying the same account balance should not block each other. A ReadWriteLock allows concurrent reads while serializing writes (deposit, withdraw, transfer).
Horizontal Scaling
For a distributed banking system, per-account locks become distributed locks (e.g., Redis-based). The lock ordering strategy still applies: always lock accounts in ascending order across nodes. Transactions become distributed transactions using a two-phase commit or saga pattern.
Junior: explain the check-then-act race condition on balance.
Mid-level: design the transfer with deadlock prevention via lock ordering.
Senior: discuss distributed locking and saga patterns for cross-node transfers.
Why a ReadWriteLock instead of a simple mutex? A mutex blocks all concurrent access, even when multiple threads only want to read. A ReadWriteLock allows unlimited concurrent readers while still ensuring exclusive access for writers, dramatically improving throughput in read-heavy workloads.
Below is the class diagram for the bank account system.
Key points to highlight in an interview:
- Customer owns Accounts (composition). Account owns Transactions (composition). The lifecycle cascades: closing a customer closes accounts, which archives transactions.
- Transaction is immutable (all final fields). This is the tamper-proof audit trail.
- BankService has a plain association arrow to Account, not composition. It coordinates accounts but does not own them.
- The lock in Account is the thread-safety mechanism. BankService accesses it via getLock() for cross-account transfers.
Interest Calculation
Savings accounts earn interest calculated daily and credited monthly. A scheduled job iterates over all savings accounts, computes accrued interest using the InterestStrategy, and creates deposit transactions automatically.
Fraud Detection and Limits
Monitor transactions for suspicious patterns: unusually large amounts, high frequency, or geographic anomalies. Enforce configurable daily withdrawal and transfer limits. Flag or block suspicious activity pending human review.
Multi-Currency Support
Accounts hold balances in specific currencies. Transfers between different currencies apply exchange rates from a pluggable rate provider. Currency conversion is handled as a separate concern with its own service.
Statement Generation
Monthly statements aggregate transactions by type, compute totals, and generate PDF reports. The immutable Transaction history makes this straightforward: query transactions by date range and format.
Distributed Transactions
For a distributed banking system, replace per-account locks with distributed locks. Use saga patterns for cross-node transfers. Implement event sourcing where the transaction log is the source of truth and balances are derived projections.
Try this problem yourself
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Editorial Solution
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
TransactionType Enum
Account Hierarchy
Design Patterns
Template Method: Account Operations
Strategy Pattern: Interest Calculation
Observer Pattern: Transaction Notifications
Define Class Members / Write Code
Transaction (Immutable)
Account with Thread Safety
BankService with Deadlock Prevention
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Per-Account Locking
Deadlock Prevention via Lock Ordering
ReadWriteLock for Balance Queries
Horizontal Scaling
Create/Explain Your Diagrams
Future Improvements