In marketplace architecture, a "Wallet" is not a single database row. It is a composite view of financial rights. For the user, it is a UI element showing "Available Balance." For the architect, it is a high-contention data structure that must balance extreme read performance (checking balances before a transaction) with absolute write integrity (preventing overdrafts).
The core engineering challenge is segregating the Performance Layer from the Integrity Layer. Relying solely on summing a transaction log for every balance check is computationally expensive (O(n)), while relying solely on a mutable "balance column" invites race conditions.
The Hot vs. Cold Storage Pattern
Scalable wallet architectures typically split data persistence: The Source of Truth (Cold Store): An immutable, append-only Transaction Ledger (SQL/Postgres). This records every debit and credit. It is ACID-compliant and optimized for write safety. The View Layer (Hot Store): A high-performance cache (Redis/Memcached). This stores the current calculated balance. When a transaction occurs, the system writes to the SQL ledger first, then publishes an event to update the Redis cache. Risk: Cache invalidation. If the cache drifts from the SQL sum, users see incorrect funds. Architectures must implement "Balance Snapshots" or periodic reconciliation jobs to realign the cache with the ledger.
Handling "Pending" vs. "Available" Balances
Marketplaces often deal with funds that are owned but not spendable (e.g., funds in escrow until a service is delivered). Multi-Bucket Structure: A wallet is rarely a single number. It is a collection of "sub-balances" or "buckets": { available: 100, pending: 50, reserved: 20 }. Reservation Logic: When a user initiates a payout, the system does not immediately debit the account. It moves funds from available to reserved. Only when the bank confirms the wire does the system debit reserved. This "Two-Phase Commit" logic prevents funds from vanishing during banking latency.