Bird
Raised Fist0
LLDsystem_design~25 mins

Balance calculation algorithm in LLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: Balance Calculation System
Design covers balance calculation logic, transaction processing, concurrency control, and data storage. Out of scope: user authentication, UI design, external payment integrations.
Functional Requirements
FR1: Calculate user account balances based on transactions
FR2: Support deposits, withdrawals, and transfers
FR3: Ensure balance never goes negative
FR4: Provide real-time balance updates
FR5: Handle concurrent transactions safely
FR6: Allow querying balance history
Non-Functional Requirements
NFR1: Support up to 100,000 concurrent users
NFR2: API response time for balance queries under 100ms
NFR3: System availability 99.9%
NFR4: Data consistency must be strong (no lost updates)
NFR5: Handle up to 10,000 transactions per second
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
❓ Question 6
Key Components
Transaction processor
Balance calculator module
Concurrency control mechanism (locks or optimistic concurrency)
Database for storing transactions and balances
Cache for fast balance queries
API layer for client requests
Design Patterns
Event sourcing for transaction history
Command Query Responsibility Segregation (CQRS)
Optimistic concurrency control
Idempotent transaction processing
Snapshotting for balance state
Reference Architecture
Client
  |
  v
API Layer (REST)
  |
  v
Transaction Processor --- Cache (Redis) 
  |                      |
  v                      v
Database (PostgreSQL) <-- Balance Calculator

Components
API Layer
REST API server
Receives client requests for transactions and balance queries
Transaction Processor
Application service
Validates and processes transactions ensuring no negative balance
Balance Calculator
Service module
Calculates current balance from transactions and snapshots
Database
PostgreSQL
Stores transactions, account data, and balance snapshots
Cache
Redis
Stores recent balances for fast read access
Request Flow
1. Client sends transaction request (deposit, withdrawal, transfer) to API Layer
2. API Layer forwards request to Transaction Processor
3. Transaction Processor checks current balance (from cache or DB)
4. If transaction valid (no negative balance), it records transaction in DB
5. Balance Calculator updates balance snapshot and cache
6. API Layer responds with updated balance
7. For balance queries, API Layer reads from cache or calculates from DB if cache miss
Database Schema
Entities: - Account(account_id PK, user_id, current_balance, last_updated) - Transaction(transaction_id PK, account_id FK, type ENUM('deposit', 'withdrawal', 'transfer'), amount, timestamp, status) - BalanceSnapshot(snapshot_id PK, account_id FK, balance, timestamp) Relationships: - One Account has many Transactions - One Account has many BalanceSnapshots Constraints: - Transaction amount > 0 - Account balance >= 0 enforced by application logic
Scaling Discussion
Bottlenecks
Database write throughput limits with high transaction volume
Cache consistency with concurrent updates
Lock contention on accounts with many simultaneous transactions
Latency in balance calculation for large transaction histories
Solutions
Partition database by account_id to distribute load
Use optimistic concurrency control to reduce locking
Implement sharded caches per account range
Use snapshotting and event sourcing to speed up balance calculation
Batch process low priority transactions asynchronously
Interview Tips
Time: 10 minutes to clarify requirements and constraints, 20 minutes to design components and data flow, 10 minutes to discuss scaling and trade-offs, 5 minutes for questions
Emphasize strong consistency to prevent negative balances
Explain concurrency control to handle simultaneous transactions
Discuss caching strategy for fast balance reads
Describe database schema supporting transaction history and snapshots
Address scaling challenges and realistic solutions

Practice

(1/5)
1. What is the main purpose of a balance calculation algorithm in a financial system?
easy
A. To add credits and subtract debits from an initial amount
B. To sort transactions by date
C. To encrypt user data
D. To generate random transaction IDs

Solution

  1. Step 1: Understand the role of balance calculation

    The balance calculation algorithm updates the current balance by adding credits and subtracting debits.
  2. Step 2: Compare with other options

    Sorting transactions, encrypting data, and generating IDs are unrelated to balance calculation.
  3. Final Answer:

    To add credits and subtract debits from an initial amount -> Option A
  4. Quick Check:

    Balance calculation = add credits - subtract debits [OK]
Hint: Balance means adding credits and subtracting debits [OK]
Common Mistakes:
  • Confusing balance calculation with sorting or encryption
  • Thinking balance calculation generates IDs
  • Ignoring subtraction of debits
2. Which of the following code snippets correctly initializes a balance variable to zero in a balance calculation algorithm?
easy
A. balance := 0
B. balance = 0
C. balance == 0
D. balance = 'zero'

Solution

  1. Step 1: Identify correct assignment syntax

    In most programming languages, = assigns a value. So balance = 0 sets balance to zero.
  2. Step 2: Check other options for errors

    := is not standard in many languages, == is a comparison, and assigning a string 'zero' is incorrect for numeric balance.
  3. Final Answer:

    balance = 0 -> Option B
  4. Quick Check:

    Use = for assignment, not == or := [OK]
Hint: Use single = to assign values in most languages [OK]
Common Mistakes:
  • Using == instead of = for assignment
  • Using := which is not common in many languages
  • Assigning string instead of numeric zero
3. Consider this pseudocode for balance calculation:
balance = 100
transactions = [20, -10, 30, -5]
for t in transactions:
    balance += t
print(balance)

What will be the printed balance?
medium
A. 135
B. 145
C. 155
D. 125

Solution

  1. Step 1: Calculate sum of transactions

    Sum = 20 + (-10) + 30 + (-5) = 20 - 10 + 30 - 5 = 35
  2. Step 2: Add sum to initial balance

    Initial balance 100 + 35 = 135
  3. Final Answer:

    135 -> Option A
  4. Quick Check:

    100 + (20 -10 +30 -5) = 135 [OK]
Hint: Add all transactions to initial balance [OK]
Common Mistakes:
  • Adding absolute values instead of signed values
  • Forgetting to add initial balance
  • Miscalculating sum of transactions
4. Identify the bug in this balance calculation code snippet:
balance = 50
transactions = [10, -20, 15]
for t in transactions:
    balance = t
print(balance)
medium
A. The initial balance is not set
B. The transactions list is empty
C. The balance is overwritten instead of updated
D. The loop variable is incorrect

Solution

  1. Step 1: Analyze the loop operation

    Inside the loop, balance = t overwrites balance each time instead of adding.
  2. Step 2: Understand correct update

    It should be balance += t to add each transaction to balance.
  3. Final Answer:

    The balance is overwritten instead of updated -> Option C
  4. Quick Check:

    Use += to update balance, not = [OK]
Hint: Use += to add transactions, not = [OK]
Common Mistakes:
  • Using = instead of += inside loop
  • Assuming transactions list is empty
  • Ignoring initial balance
5. You need to design a balance calculation system that handles millions of transactions per day with real-time updates. Which design choice best supports scalability and accuracy?
hard
A. Ignore debits and only add credits to simplify calculation
B. Use a single database transaction to update balance after each transaction
C. Store all transactions in memory and recalculate balance on every request
D. Batch transactions and update balance periodically with distributed processing

Solution

  1. Step 1: Consider scalability needs

    Millions of transactions require efficient processing; single updates per transaction cause bottlenecks.
  2. Step 2: Evaluate batch processing benefits

    Batching with distributed processing reduces load and maintains accuracy by processing groups of transactions.
  3. Step 3: Reject other options

    Single DB transactions cause slowdowns, in-memory recalculation is memory-heavy and slow, ignoring debits causes incorrect balances.
  4. Final Answer:

    Batch transactions and update balance periodically with distributed processing -> Option D
  5. Quick Check:

    Batch + distributed processing = scalable & accurate [OK]
Hint: Batch and distribute processing for large-scale balance updates [OK]
Common Mistakes:
  • Updating balance per transaction causing bottlenecks
  • Recalculating balance on every request wasting memory
  • Ignoring debits leading to wrong balances