Build a Stock Trading Application Backend
System DesignModel answerLast updated
Design the architecture for a consumer stock trading app handling order execution, account management, real-time market data, and settlement.
You need to architect a backend system for a consumer-facing stock trading application. Users should be able to fund their accounts, view live price quotes, place and cancel stock orders, and see their portfolio holdings and performance.
Your design should address:
- Account management: User registration with identity verification, linking bank accounts, depositing and withdrawing funds, and tracking cash balances
- Market data: Receiving price feeds from external sources and delivering current quotes to connected clients with low latency
- Order handling: Accepting buy and sell orders (market orders, limit orders, and stop orders), validating that users have sufficient funds, preventing duplicate submissions, and managing order state through the lifecycle
- Execution flow: Sending orders to external venues (exchanges or broker-dealers), receiving fill confirmations, and updating user portfolios
- Portfolio tracking: Maintaining current holdings, calculating profit/loss, handling stock splits and dividends, and providing cost basis for tax reporting
- Data storage: Choosing appropriate databases for orders, account balances, trade history, and price data
- Service boundaries: Breaking the system into services with clear APIs, deciding between synchronous and asynchronous communication, and using message queues where appropriate
- Correctness and consistency: Ensuring users cannot spend the same dollar twice, no trade confirmations are lost, and account balances always reconcile
- Performance and scale: Handling peak load when markets open (30-50x normal traffic), managing millions of concurrent quote subscriptions, and dealing with backpressure
- Reliability: Designing for high availability during trading hours, handling failure scenarios like downstream service outages, and implementing disaster recovery
- Compliance and monitoring: Maintaining audit logs, detecting suspicious activity, tracking system health, and having fallback procedures
Estimate realistic traffic numbers and explain your architectural choices and tradeoffs. Consider how you would extend the design to support additional asset types later.
Hints
Hint 1
The order submission path and the market data streaming path have completely different performance characteristics—one is low-throughput and requires strong consistency, the other is high-throughput and can tolerate some data loss.
Hint 2
To prevent users from placing orders that exceed their buying power, you need atomicity between checking the balance and reserving funds. Think about transaction boundaries and database sharding strategies.
Hint 3
Orders go through many state transitions (submitted, routed, filled, cancelled). Event sourcing can help you maintain a complete audit trail while projecting the current state.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Stock Trading Platform Architecture
1. Requirements and Scale Estimation
First, let's establish the functional scope and performance targets.
Core capabilities:
- Identity verification and bank account linking
- Cash deposits and withdrawals (ACH transfers)
- Real-time price quotes for thousands of stocks
- Order placement supporting market, limit, and stop orders
- Order cancellation
- Portfolio view with holdings, cost basis, and profit/loss
- Handling corporate actions (splits, dividends)
Performance requirements (prioritized):
- Financial correctness: No duplicate trades, no overspending, complete audit trail
- Availability: 99.9%+ uptime during market hours (especially at market open)
- Latency: Orders acknowledged under 100ms (p99), quotes delivered under 500ms
Traffic estimates:
| Metric | Volume |
|---|---|
| Registered users | 20M total, 5M daily active |
| Orders per day | 5M (average 200/sec over 6.5 trading hours) |
| Market open surge | 10,000 orders/sec for 5-10 minutes |
| Concurrent quote streams | 2M websocket connections, 20 symbols each |
| Inbound market data | 10,000+ securities, millions of updates/sec at peak |
| Tick data storage | Multiple TB per day |
Key insight: Order processing is low-throughput but must be correct. Market data distribution is high-throughput but can tolerate occasional drops. Design these as separate subsystems.
2. API Design
Order submission (synchronous):
POST /api/orders
{
"idempotency_key": "client-generated-uuid",
"account_id": "...",
"symbol": "AAPL",
"side": "buy|sell",
"quantity": 100,
"order_type": "market|limit|stop",
"limit_price": 150.00,
"time_in_force": "day|gtc"
}
→ 201 {"order_id": "...", "status": "accepted|rejected", "message": "..."}
DELETE /api/orders/{order_id} → 202 (cancellation requested)
GET /api/orders?status=open
GET /api/accounts/{id}/summary (cash, buying_power, positions)
GET /api/accounts/{id}/history
Streaming (async over WebSocket):
WS /api/stream
Subscribe: {"type": "quotes", "symbols": ["AAPL", "MSFT", ...]}
Subscribe: {"type": "orders"}
Subscribe: {"type": "positions"}
Idempotency: The idempotency_key ensures that retries don't create duplicate orders. Store it with a unique constraint and return the existing order if the key already exists.
3. High-Level Architecture
┌─────────────┐
│ Clients │
└──────┬──────┘
│
┌──────▼──────────────────────┐
│ API Gateway / Load Balancer │
│ (auth, rate limiting) │
└──────┬──────────────────────┘
│
├─────────────────────────────────────────────┐
│ │
┌──────▼─────────┐ ┌───────▼──────────┐
│ Account Service │ │ Market Data │
│ (KYC, funding) │ │ Aggregator │
└──────┬─────────┘ └───────┬──────────┘
│ │
┌──────▼──────────┐ ┌────────────┐ ┌─────▼──────────┐
│ Order Service │─────▶│ Event Bus │◀─────│ Quote Streamer │
│ (validation, │ │ (Kafka) │ │ (WebSocket) │
│ routing) │ └─────┬──────┘ └────────────────┘
└──────┬──────────┘ │
│ │
┌──────▼──────────┐ ┌─────▼──────────┐
│ Risk Manager │ │ Portfolio Svc │
└──────┬──────────┘ │ (positions, │
│ │ P&L, basis) │
┌──────▼──────────┐ └────────────────┘
│ Ledger Service │
│ (balances) │
└─────────────────┘
│
┌──────▼──────────┐
│ External │
│ - Exchanges │
│ - Market Makers │
│ - Clearing │
└─────────────────┘
4. Core Components Deep Dive
Account Management & Funding
- KYC/Identity verification: Integrate with third-party providers (e.g., Onfido, Jumio) for document verification and anti-money laundering (AML) checks
- Bank linking: Use Plaid or similar to verify bank accounts securely
- ACH transfers: Initiate deposits/withdrawals through a bank partner. ACH takes 2-4 business days to settle
- Instant deposits: Credit accounts immediately up to a risk-based limit (e.g., $1,000) before ACH clears. If the transfer fails, freeze the account and recover funds
Ledger Service (Double-Entry Accounting)
This is the source of truth for all money movements.
Schema:
ledger_entries:
- entry_id (PK)
- account_id (indexed, sharded)
- transaction_id (groups debits/credits)
- amount (decimal)
- entry_type (credit/debit)
- category (deposit, trade, fee, dividend, hold)
- reference_id (order_id, transfer_id, etc.)
- timestamp
Every financial operation creates balanced entries:
- Deposit: debit cash, credit "pending_deposit"
- Buy order hold: debit cash, credit "reserved_for_orders"
- Trade execution: debit "reserved", credit "equity_value"
Buying power calculation:
available_cash = sum(cash credits) - sum(cash debits) - sum(holds)
buying_power = available_cash + margin_available (if margin account)
Cache current balances per account in Redis with a TTL, fallback to database aggregation.
Order Management System (OMS)
State machine:
NEW → VALIDATED → RESERVED → ROUTED → WORKING
↓ ↓ ↓ ↓ ↓
REJECTED ←─┴──────────┴─────────┴────→ FILLED
↓ ↓
PARTIAL ← CANCELLED
Pre-trade validation (must be atomic):
- Check account status (approved, not restricted)
- Verify symbol is tradable (not halted)
- Validate price (reject orders outside reasonable bounds)
- Check regulatory constraints (pattern day trader rules, short sale restrictions)
- Reserve buying power
Critical transaction:
BEGIN TRANSACTION;
SELECT available_cash FROM account_balances
WHERE account_id = ? FOR UPDATE;
-- Check sufficient funds
IF available_cash >= required_amount THEN
INSERT INTO ledger_entries (hold entry);
INSERT INTO orders (status='VALIDATED');
COMMIT;
ELSE
ROLLBACK;
Sharding strategy: Partition by account_id so all orders and balance operations for one account hit the same shard. This ensures local transactions prevent double-spending.
Order Routing
Smart Order Router (SOR):
- Route to venues based on: fill probability, price improvement statistics, payment for order flow agreements, and latency
- Most retail orders go to wholesalers (market makers like Citadel Securities) who provide price improvement
- Fall back to exchanges if wholesalers don't respond or for certain order types
FIX protocol gateways:
- Maintain persistent FIX sessions with each venue
- Handle sequence number gaps and replays on reconnect
- Deduplicate execution reports by venue-provided
exec_id
Stop order handling:
- Stop and stop-limit orders are held internally in a "stop engine"
- Subscribe to real-time last-sale prices
- When trigger condition is met, generate a child market or limit order
- Partition stop engine by symbol for parallel processing
- Persist stop orders to survive restarts
Execution Processing
Execution reports arrive asynchronously via FIX.
Flow:
- Receive execution report from venue
- Deduplicate by
exec_id(idempotent processing) - Update order state in database
- Publish event to Kafka:
{"event": "fill", "order_id": "...", "exec_id": "...", "qty": 50, "price": 150.25} - Multiple consumers read the stream:
- Portfolio service: updates positions and tax lots
- Ledger service: converts hold to settled trade
- Notification service: alerts user
- Compliance service: reports to CAT/FINRA
Event sourcing: Store every order state change as an immutable event. The current order status is a projection. This provides a complete audit trail and enables replay for debugging.
Portfolio & Positions
Position tracking:
- Maintain separate tax lots for cost basis (FIFO by default)
- Calculate unrealized P&L at read time:
(current_price - cost_basis) * quantity - Realized P&L is recorded when lots are closed
Corporate actions (daily batch job):
- Stock splits: Multiply quantity, divide cost basis to preserve total value
- Dividends: Create ledger credits on payment date
- Mergers/symbol changes: Remap using internal instrument IDs independent of ticker symbols
- Special handling: Cancel or adjust open orders on split effective dates
Market Data Pipeline
Inbound feeds:
- Connect to Securities Information Processor (SIP) feeds and/or direct exchange feeds
- Feeds deliver trades, quotes, and NBBO (national best bid/offer)
Normalization layer:
- Parse binary protocols (ITCH, OUCH, FIX)
- Standardize message format
- Publish to in-memory pub/sub (Redis Streams or dedicated message bus)
Quote fanout service:
- Maintain millions of persistent WebSocket connections
- Each connection subscribes to 10-30 symbols
- Use geographic distribution and horizontal scaling (100k connections per node)
- Send only deltas/updates, not full snapshots on every tick
- Implement backpressure: if a client can't keep up, skip intermediate updates and send latest
Price cache:
- Redis with last price per symbol
- TTL of 1 second (stale quotes are dangerous)
- Used for stop order triggers and portfolio P&L calculations
Historical storage:
- Real-time: Last 7 days in ClickHouse or TimescaleDB (columnar time-series optimized)
- Archive: Compress and move to S3/Parquet for long-term retention
5. Consistency and Correctness
Strong consistency requirements:
- Ledger entries and account balances
- Order state and fill records
- Position quantities
Solution: Use PostgreSQL or CockroachDB with ACID transactions. Shard by account_id so related operations are co-located.
Eventual consistency acceptable:
- Market data delivery
- Portfolio display (can lag fills by a few seconds)
- Historical reports
Reconciliation:
- Nightly three-way reconciliation: internal ledger vs. clearing broker statements vs. venue trade files
- Any discrepancy triggers alerts for investigation
- This catches silent bugs before they compound
6. Failure Modes and Reliability
High availability:
- Active-active regions for API services and market data
- Active-passive for order routing (FIX sessions are stateful)
- Postgres with streaming replication or multi-region CockroachDB
Circuit breakers:
- If risk service is down, reject new orders rather than fail open
- If market data feed stalls, freeze stop order triggers and notify users
Message queue durability:
- Kafka with replication factor 3
- Consumers track offsets and can replay on failure
Graceful degradation:
- If quote streaming fails, fall back to polling last-price cache
- If portfolio service is slow, serve cached positions with a staleness indicator
Disaster recovery:
- Continuous backup of ledger and order databases
- RTO: 15 minutes (switchover to DR region)
- RPO: 0 for ledger (synchronous replication), <1 minute for orders
7. Scale and Performance Optimization
Handling market open surge (10k orders/sec):
- Horizontal scaling of order service (stateless)
- Database connection pooling with PgBouncer
- Pre-warm caches before market open
- Use asynchronous acknowledgment: return "accepted" immediately after validation, process routing asynchronously
Market data throughput:
- Vertical scaling for normalization layer (high CPU)
- Horizontal scaling for quote fanout (high connection count)
- Multicast for internal distribution to reduce network load
Database optimization:
- Partition orders table by date
- Index on (account_id, status, created_at)
- Use read replicas for portfolio queries
- Cache hot data in Redis (balances, last prices)
8. Monitoring and Compliance
Observability:
- Latency metrics at every hop (order submission → validation → routing → ack)
- Order funnel metrics (submitted → rejected → filled)
- Market data lag (feed timestamp vs. processing timestamp)
- WebSocket connection health and message drop rates
Audit trail:
- Immutable event log of every order state change
- All API requests logged with user_id and IP
- Regulatory reports: CAT (Consolidated Audit Trail), FINRA trade reporting
Anomaly detection:
- Pattern detection for wash trading, layering, spoofing
- Unusual withdrawal patterns (anti-money laundering)
- Rapid order cancellation rates
9. Extensions
Options trading:
- Add options-specific Greeks calculation
- Multi-leg order support (spreads, straddles)
- Different settlement cycle (T+1 for options)
- Complex margin requirements
Cryptocurrency:
- 24/7 operation (no market hours)
- Direct custody vs. omnibus accounts
- Blockchain settlement tracking
- Higher price volatility requires tighter risk controls
Common Mistakes to Avoid:
- Treating order submission as fire-and-forget (need acknowledgment)
- Using eventual consistency for account balances (enables double-spending)
- Not deduplicating execution reports (can result in phantom fills)
- Forgetting to cancel open orders on corporate actions
- Insufficient rate limiting (enables abuse)
- Not having a kill switch to halt all trading in emergencies