0
0
LLDsystem_design~7 mins

Balance calculation algorithm in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When a system handles multiple transactions like deposits, withdrawals, and transfers, calculating the correct balance becomes error-prone if done naively. Mistakes such as double counting, race conditions, or inconsistent state can cause incorrect balances, leading to user distrust and financial loss.
Solution
The balance calculation algorithm ensures accurate and consistent balance updates by processing transactions in a controlled order and applying atomic operations. It typically maintains a ledger of all transactions and calculates the balance by summing them or updates the balance incrementally with each transaction while preventing concurrent conflicts.
Architecture
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Transaction │──────▶│ Balance Store │──────▶│   User View   │
│    Input      │       │ (Database or  │       │ (API/Frontend)│
└───────────────┘       │  In-memory)   │       └───────────────┘
                        └───────────────┘

This diagram shows how transactions flow into the system, update the balance store, and then reflect in the user's view.

Trade-offs
✓ Pros
Ensures accurate and consistent balance updates even under concurrent transactions.
Prevents race conditions by using atomic operations or transaction logs.
Supports auditability by maintaining a ledger of all transactions.
✗ Cons
Maintaining a full transaction ledger can increase storage and processing overhead.
Incremental balance updates require careful concurrency control to avoid conflicts.
Calculating balance from the ledger on-demand can be slower than using cached balances.
Use when the system handles frequent concurrent transactions and requires strong consistency and audit trails, typically in financial or wallet systems with thousands of transactions per second.
Avoid when the system has very low transaction volume (under 100 transactions per day) where simple balance updates without concurrency control suffice.
Real World Examples
Stripe
Stripe uses precise balance calculation algorithms to ensure merchant accounts reflect accurate funds after payments, refunds, and fees, preventing financial discrepancies.
PayPal
PayPal maintains a transaction ledger and uses atomic balance updates to handle millions of concurrent transactions without errors or double spending.
Robinhood
Robinhood calculates user balances in real-time by processing trades and deposits atomically to avoid incorrect portfolio valuations.
Code Example
The before code updates balance directly without any concurrency control, risking race conditions. The after code uses a lock to ensure atomic updates and keeps a transaction ledger for audit and consistency.
LLD
### Before: naive balance update without concurrency control
class Account:
    def __init__(self):
        self.balance = 0

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
        else:
            raise Exception("Insufficient funds")


### After: balance update with transaction log and atomic lock
import threading

class Account:
    def __init__(self):
        self.balance = 0
        self.lock = threading.Lock()
        self.transactions = []  # ledger

    def deposit(self, amount):
        with self.lock:
            self.balance += amount
            self.transactions.append(('deposit', amount))

    def withdraw(self, amount):
        with self.lock:
            if self.balance >= amount:
                self.balance -= amount
                self.transactions.append(('withdraw', amount))
            else:
                raise Exception("Insufficient funds")
OutputSuccess
Alternatives
Event Sourcing
Stores all changes as events and rebuilds balance by replaying events instead of direct updates.
Use when: Choose when you need full audit history and the ability to reconstruct state at any point in time.
Snapshot with Incremental Updates
Periodically saves balance snapshots and applies incremental transactions to reduce computation.
Use when: Choose when transaction volume is very high and replaying all transactions each time is too slow.
Summary
Balance calculation algorithms prevent errors like double counting and race conditions in financial systems.
They use atomic operations and transaction ledgers to maintain consistent and auditable balances.
Choosing the right approach depends on transaction volume, concurrency, and audit requirements.