Design a stock trading platform (Robinhood)
A retail brokerage like Robinhood has two very different workloads colliding: a write path (placing/canceling orders) that demands strong consistency and correctness, and a read path (live prices, portfolio) that is massively fan-out and latency-sensitive. The trick is to separate them cleanly.
Real-Time & Messaging, 13 components, about 45 min
1. Scope
In scope
- • Place and cancel market & limit orders
- • Stream live stock quotes to clients
- • View portfolio (positions + cash) and order history
- • Order matching / execution
Out of scope
- • Options, crypto, margin lending
- • Clearing & settlement (T+1) with custodians
- • Tax-lot accounting and regulatory reporting internals
2. Functional requirements
Must have
- • Place a market or limit order and get an ack
- • Cancel a pending order
- • Get a real-time quote for a symbol
- • View current portfolio and order history
Nice to have
- • Price alerts
- • Watchlists
- • After-hours trading
3. Non-functional requirements
4. Back-of-envelope estimation
Assumptions
- • 20M users, 10% active on a trading day
- • Each active user places ~3 orders/day
- • Each active user checks prices/portfolio ~100×/day
- • Order record ~1 KB; tick data is the heavy part
Derived numbers
5. API design
Place order: { symbol, side, type, qty, limitPrice? } → { orderId, status }
Cancel a pending order
Latest quote (REST, for one-off reads)
Subscribe to live tick stream for a set of symbols
Positions + cash balance
6. High-level design
What each box in the reference diagram is responsible for:
7. Data model
8. Deep dives
Why split the order path and price path
Orders need correctness: no double-fills, accurate balances, durable audit trail. Prices need scale: broadcast the same tick to millions of subscribers with low latency. Coupling them would force the safe-but-slower order store to also serve the firehose of reads. Separating lets each scale on its own axis — the matching engine stays a tightly controlled single-writer per symbol, while the price path is a stateless fan-out tier you can scale horizontally.
No double-fills: sequential matching
Route all orders for a symbol through one queue to a single matching-engine instance (or a sharded-by-symbol set). The engine processes the order book sequentially, so two buys can't both fill the same limited liquidity. This is a deliberate single-writer design — throughput per symbol is bounded but correctness is guaranteed. Replicate the engine with a hot standby + event sourcing (replay the order log) for failover.
Streaming prices to millions
Clients open a WebSocket and subscribe to symbols. Upstream exchange ticks are normalized once, published to a pub/sub bus, and each price-stream gateway pushes to its connected subscribers. Cache the last price in Redis so a newly connected client gets an immediate snapshot before the next tick. Conflate ticks (drop intermediate values) for slow clients to avoid backpressure.
Applying a fill to the portfolio
When the matching engine emits a fill, the Portfolio Service must update the position and cash atomically — a transaction (or saga with compensation) that debits cash and credits shares. Emit the fill as an event so order history, portfolio, and downstream analytics all stay consistent via the same log.
9. Bottlenecks
- Matching engine is single-writer per symbol → shard by symbol, hot-standby failover
- Price fan-out → stateless gateways + pub/sub scale horizontally
- Market open/close spikes → autoscale order workers, queue absorbs bursts
- Portfolio writes need ACID → keep on a strongly-consistent store, not eventual
10. Trade-offs
Matching engine architecture
Choose: Single-threaded, in-memory order book per symbol, fed by a sequenced input log; deterministic so it can be replayed.
Instead of: Multi-threaded engine with locks: more cores per symbol, but nondeterministic and slower due to contention.
One symbol's book fits one core; determinism gives replay-based recovery and audit for free.
Durability before acknowledgment
Choose: Write each input event to a replicated log (sequencer) before matching; replicas replay the same log as hot standbys.
Instead of: Persist matched results to a database synchronously: adds milliseconds to every order.
The log is the source of truth; state is derived and rebuildable.
Broker app versus exchange
Choose: Be explicit: a retail broker (Robinhood) routes orders to market makers and exchanges; it does not run the matching engine.
Instead of: Designing an exchange matching engine.
Interviewers often mean one or the other; clarifying this is a requirements signal.
11. Failure modes
Primary matching engine crashes
Trading halts for that symbol.
Mitigation: Hot standby replays the same sequenced log and takes over at the last sequence number within milliseconds.
Market data fan-out falls behind
Clients trade on stale prices.
Mitigation: Multicast or a dedicated fan-out tier with conflation (send latest price, drop intermediate ticks for slow consumers).
Risk check bypassed during a burst
Accounts exceed buying power.
Mitigation: Pre-trade risk is synchronous and in-memory per account; never skip it under load, reject instead.
12. What interviewers probe
Answer each one yourself before opening it.
What data structure is the order book?Show a strong answer
Two price-ordered maps (bids descending, asks ascending) of FIFO queues per price level, plus a hash from order id to node for O(1) cancel.
What latency targets are realistic?Show a strong answer
Exchange matching in microseconds; a retail broker order path in tens of milliseconds end to end, dominated by network and routing.
How do you guarantee fairness?Show a strong answer
Price-time priority from a single sequencer; every order gets a sequence number at entry and matching is deterministic.
How do you reconcile with the clearing house?Show a strong answer
End-of-day trade files compared against the internal ledger; double-entry positions; breaks investigated before settlement (T+1 in the US).
Sign in to track this guide in your curriculum progress.