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

    PatternRead-heavy— Price/portfolio reads ≫ order writes
    Order latency< 200 ms ack
    Quote latency< 100 ms tick-to-client
    Availability99.99%— Especially during market hours
    ConsistencyStrong for orders & balances; eventual for quotes
    Retention7 years— Regulatory requirement for trades

    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

    Write QPS (orders)~70/s— 6M orders / 86400
    Peak write QPS~700/s— ~10× at open/close
    Read QPS~2,300/s— 200M reads / 86400
    Peak read QPS~23,000/s— ~10× at open/close
    Order storage~1.5 TB/yr— 6M orders × 250 trading days × 1 KB; ~10 TB over 7 years
    Tick data~100 GB/day— Thousands of symbols × ticks

    5. API design

    POST/api/orders

    Place order: { symbol, side, type, qty, limitPrice? } → { orderId, status }

    DELETE/api/orders/{id}

    Cancel a pending order

    GET/api/quotes/{symbol}

    Latest quote (REST, for one-off reads)

    WS/stream/quotes

    Subscribe to live tick stream for a set of symbols

    GET/api/portfolio

    Positions + cash balance

    6. High-level design

    What each box in the reference diagram is responsible for:

    API Gateway — Auth, rate-limit, routes order vs. price vs. portfolio traffic.
    Order Service — Validates orders, runs risk/buying-power checks, enqueues to the matching engine.
    Order Queue — Per-symbol queue so orders for a symbol are processed in sequence (no races).
    Matching Engine — Maintains the order book per symbol; matches buys/sells and emits fills. Single-writer per symbol for correctness.
    Price Stream Service — Holds WebSocket connections; fans out ticks from pub/sub to subscribed clients.
    Pub/Sub — Broadcasts normalized ticks to all price-stream gateways.
    Quote Cache — Redis last-price per symbol for fast REST quotes and cold-start.
    Portfolio Service — Applies fills to positions + cash transactionally.
    Exchange Feed — Upstream market-data source; normalized before broadcast.

    7. Data model

    Order DB: orders(id, user_id, symbol, side, type, qty, price, status, ts)— Append-heavy, partition by symbol/date
    Portfolio DB: positions(user_id, symbol, qty, avg_cost), accounts(user_id, cash)— Strong consistency, ACID
    Redis: quote:{symbol} → last price— Hot read cache

    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.