Practice/Robinhood/Design a stock trading platform
Design a stock trading platform
System DesignMust
Problem Statement
Design a simplified stock trading platform that supports limit orders for buying and selling stocks, with basic portfolio tracking capabilities at small scale (100 writes per second).
Think of a simplified Robinhood-like brokerage where users submit limit buy and sell orders for publicly traded stocks. The system matches compatible orders (price-time priority), executes trades, settles the transaction, and updates the user's portfolio and order status -- all while maintaining strict financial correctness.
The core challenge is maintaining auction integrity under concurrent bidding pressure while providing sub-second feedback to all participants. Even at small scale (around 100 writes per second), the order book and portfolio ledger require careful thinking about transactions, idempotency, ordering, and failure handling. Interviewers use this problem to test whether you can design for correctness under contention, preserve financial consistency with ACID guarantees, and still provide real-time user feedback. The goal is to right-size the design: simple, reliable, and auditable, with a clear order lifecycle and low-latency updates.
Key Requirements
Functional
- Limit order placement -- users place limit buy and sell orders for specific symbols, prices, and quantities
- Order status tracking -- users view order status (open, partially filled, filled, canceled) and execution history
- Portfolio management -- users view a basic portfolio including cash balance, positions, and recent activity
- Real-time updates -- users receive near real-time notifications when orders are executed and portfolio balances change
Non-Functional
- Scalability -- support approximately 100 order writes per second across the platform
- Reliability -- zero lost orders; guaranteed trade settlement even during partial failures
- Latency -- order validation and acceptance within 200ms; portfolio updates reflected within 1 second of trade execution
- Consistency -- strict enforcement that only valid orders are accepted, balances never go negative, and exactly one side wins each match
What Interviewers Focus On
Based on real interview experiences at Robinhood (7 candidate reports), these are the areas interviewers probe most deeply:
1. Order Matching Engine and Contention
An order book concentrates writes on a few hot symbols and price levels, creating high contention on shared state. The matching engine must process orders deterministically and prevent race conditions that could allow invalid trades.
Hints to consider:
- Design a single-threaded matching engine per symbol that processes orders sequentially, eliminating races without complex locking
- Use price-time priority for matching: orders at the best price match first, and among equal prices the oldest order matches first
- Implement optimistic locking with version numbers on the order book state to catch concurrent modifications
- Database constraints like CHECK conditions provide a last line of defense against invariant violations (negative balances, invalid prices)
2. Financial Consistency and Transaction Design
Trade execution, portfolio updates, and order status changes must be atomic. Separating these across services without a transactional boundary can create money or shares out of thin air after failures.
Hints to consider:
- Use a single PostgreSQL transaction to atomically update both sides of a trade: debit buyer's cash, credit seller's cash, transfer shares, and update order statuses
- Implement the outbox pattern to write both the state change and notification events in one transaction, preventing partial applies
- Design an order state machine with clear transitions (open, partially filled, filled, canceled) to prevent invalid state changes
- Use idempotency tokens on order submissions so retries never create duplicate orders or double-charge customers
3. Real-Time Update Distribution
Users expect to see order fills and portfolio changes appear instantly. However, naively coupling the critical matching path to an unbounded number of WebSocket connections creates performance problems.
Hints to consider:
- Separate the order-processing write path from the notification read path using Kafka as an event stream
- Use WebSocket connections for server-initiated pushes with careful connection management and reconnection logic
- A pub-sub layer (Redis Pub/Sub or Kafka topics per symbol) lets you scale notification workers independently from matching
- Store bid history in an append-only log to provide an audit trail and enable rebuilding state after failures
4. Order Lifecycle and Multi-Step Workflow
Order placement through settlement is a multi-step workflow: validation, fund reservation, matching, execution, settlement, and notification. Each step can fail independently.
Hints to consider:
- Reserve funds (or shares for sell orders) at order placement time so that matched trades always have backing assets
- Use a saga pattern where each step has a compensating action: if matching fails after fund reservation, release the reserved funds
- Design for partial fills where a large order matches against multiple smaller counter-orders across separate transactions
- Consider how you handle situations where the bid is recorded but notifications fail to send