Design a Trading Platform (DB schemas, consistency)
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2021-10-12
Problem Statement
Design a high-performance trading platform (like Robinhood, Zerodha, or E*TRADE) that supports equities/derivatives trading. The system should allow retail/institutional users to place buy/sell orders, ensure strong consistency for balances and positions, and scale to millions of concurrent users.
Functional Requirements
1.User & Account Management
•Secure login, user profiles, KYC compliance.
•Trading accounts with linked bank accounts.
2.Portfolio & Balances
•Track user balances (cash + securities).
•Support deposits/withdrawals.
3.Order Placement & Matching
•Market, limit, stop-loss orders.
•Real-time order book per instrument.
•Trades matched via a matching engine.
4.Trade Execution
•Atomic execution (funds debited, positions updated).
•Settlement (T+1, T+2) tracking.
5.Market Data Service
•Live tick data (stock price updates).
•Candlestick charts, historical data.
6.Risk & Compliance
•Margin checks, exposure limits.
•Regulatory reporting & auditing.
7.Notifications
•Trade confirmations, order status, margin calls.
Non-Functional Requirements
•Consistency → Balances and positions must always be correct (no double spend).
•Latency → Trades must execute within milliseconds.
•Throughput → Handle 100K+ orders/sec.
•Availability → 99.99% uptime.
•Scalability → Handle peak trading hours & market volatility.
•Auditability → Every trade logged immutably.
Core Components
•API Gateway → Authentication, rate limiting, routing.
•User Service → User accounts, KYC.
•Portfolio Service → Manages balances, positions, and P&L.
•Order Management Service (OMS) → Receives orders, validates funds.
•Matching Engine → Matches buy/sell orders at exchange level.
•Market Data Service → Provides live tick data, charts.
•Settlement Service → Handles T+N settlement, reconciliation.
•Notification Service → Real-time trade/order updates.
•Risk Engine → Margin checks, compliance, fraud detection.
•Audit & Logging Service → Immutable trade history for compliance.
Database Schema (Simplified)
Users & Accounts
1
2Users(user_id PK, name, email, kyc_status, created_at)
3Accounts(account_id PK, user_id FK, cash_balance, margin_limit, created_at)Orders & Trades
1
2Orders(order_id PK, user_id FK, symbol, order_type, side, price, quantity, status, created_at)
3Trades(trade_id PK, buy_order_id FK, sell_order_id FK, symbol, price, quantity, executed_at)
4OrderBook(symbol PK, buy_heap, sell_heap) -- in-memoryPortfolio & Positions
1
2Holdings(user_id FK, symbol, quantity, avg_price, updated_at)
3Transactions(txn_id PK, user_id FK, type, amount, symbol, status, created_at)Market Data
1
2Prices(symbol PK, last_price, updated_at)
3PriceHistory(symbol, ts, open, high, low, close, volume)Consistency Challenges
1.Double Spend Prevention
•Lock balances before placing orders.
•Use transactional DB updates or distributed locks.
2.Atomic Trade Execution
•Matching Engine + Portfolio updates must be atomic.
•Use 2-phase commit or event sourcing (Kafka + idempotent consumers).
3.Eventual vs Strong Consistency
•Balances & holdings → Strong consistency (must be correct).
•Market data feeds → Eventual consistency is acceptable.
4.Idempotency
•Repeated trade/order events must not cause duplicate executions.
Trade Flow Example
1.User places buy order for 10 shares of AAPL @ $100.
2.OMS validates balance (locks $1000).
3.Matching Engine finds a sell order at $100.
4.Trade executed:
•Update Holdings (10 AAPL shares).
•Update Cash Balance (-$1000).
•Log Trade (immutable).
5.Notify both buyer & seller.
6.Settlement Service reconciles trade on T+1.
Key Trade-offs
•In-Memory Order Book (fast) vs Persistent Order Book (durable but slower).
•SQL (strong consistency for trades) vs NoSQL (scalable market data storage).
•Single Matching Engine (low latency) vs Sharded Matching Engine (scalable by symbol).
•Strong Consistency for portfolios vs Eventual Consistency for analytics.
⚡ This design tests your understanding of low-latency trading systems, DB consistency, event-driven architecture, and regulatory compliance.