📈 Design Stock Trading System — System Design Interview Guide
Hard · High-Frequency & Finance
Design a stock trading platform like Robinhood or Zerodha that processes buy/sell orders with a matching engine, provides real-time price feeds, and maintains a persistent order book.
Open the interactive Stock Trading System design on PrepGrind → Drag load balancers, caches, databases, and queues onto a canvas, run a live traffic simulation to watch latency and bottlenecks under load, and follow the full interview walkthrough below — free, in your browser.
Functional requirements
- Users can place market, limit, and stop orders
- Order book: view bid/ask prices and quantities
- Trade matching: match buy and sell orders by price-time priority
- Real-time price updates via WebSocket/SSE
- Portfolio: view holdings, P&L, transaction history
- Market hours enforcement; pre/post-market support
Non-functional requirements & scale
- Process 1M orders per second at peak
- Trade matching latency < 1ms (low-latency matching engine)
- Price updates must be propagated < 100ms to all subscribers
- No order can be lost or double-processed (exactly-once)
- Audit trail for every order and trade (regulatory requirement)
- Market data replay: reconstruct order book state at any past time
Capacity estimation
Core: matching engine is the most latency-critical component. Written in C++/Rust for nanosecond performance. Order book is in-memory data structure (price-ordered binary search tree). SEBI/SEC regulations require immutable audit trail. Order state: PENDING → PARTIALLY_FILLED / FILLED / CANCELLED / REJECTED.
Core entities
- Order — orderId, userId, symbol, type, side (buy|sell), price?, qty, filledQty, status, createdAt
- Trade — tradeId, buyOrderId, sellOrderId, symbol, price, qty, timestamp
- OrderBook — symbol, bids (price→qty sorted desc), asks (price→qty sorted asc), lastTradePrice
- Position — userId, symbol, qty, avgCostPrice, unrealizedPnL
API design
POST /api/v1/orders— Place order. Body: { symbol, type, side, price?, qty }. Returns { orderId, status }.DELETE /api/v1/orders/:orderId— Cancel pending order.WS wss://market/orderbook/:symbol— Real-time order book updates. Streams bid/ask deltas.GET /api/v1/portfolio— Get holdings, positions, and P&L.
High-level design
Orders → Risk Check → Matching Engine (in-memory per symbol) → Trade events to Kafka → Position Service updates portfolio → Market Data Service broadcasts to WebSocket subscribers.
Deep dives
⚡ Matching Engine Design
In-memory order book per symbol: two sorted data structures — bids (max-heap by price) and asks (min-heap by price). On buy order: compare price with best ask. If buy price >= best ask: trade executes. Price-time priority (FIFO within same price). One matching engine thread per symbol (no locks). Deployed on dedicated bare-metal server with NUMA pinning for < 1μs latency.
📊 Order Book Data Structure
Use a price-level map: price → linked list of orders at that price. O(log P) for matching where P = number of price levels. Alternative: skip list for O(log N) insertion + deletion. Key operations: add order O(log N), cancel order O(1) with hash map by orderId, match O(1) per trade. Snapshot order book every 1 second for recovery.
🛡️ Pre-Trade Risk Checks
Before order reaches matching engine: (1) Funds check — buying power >= order value + fees. (2) Margin check for leveraged accounts. (3) Position limits — max N shares per stock. (4) Self-trade prevention — reject if buyer = seller. (5) Price collar — reject if limit price > 5% away from market (circuit breaker). All checks in < 100μs.
📜 Regulatory Audit Trail
Every order event (placed/modified/cancelled/filled) must be immutably logged. Use append-only Kafka topic with log compaction disabled. Write to TimescaleDB (time-series optimized Postgres). Must store: exact timestamp (microsecond), user ID, IP address, order details, reason for rejection. SEBI requires 5-year retention. Export daily to S3 Glacier for long-term.
Scaling considerations
- One matching engine process per symbol (avoid cross-symbol locking)
- Kafka as durable log between matching engine and downstream services
- TimescaleDB for time-series trade history with native compression
- Market data WebSocket: fan-out to 1M subscribers via pub/sub sharding
- Hot standby matching engine: replicate order book state for failover in < 1s
What interviewers expect by level
- Junior: Describe order placement, order book concept (bid/ask), basic trade matching.
- Mid: Priority queue order book, pre-trade risk checks, Kafka for trade events, position updates.
- Senior: In-memory matching engine internals, order book data structures, low-latency optimizations, audit trail.
- Staff: Sub-millisecond matching, FPGA/kernel bypass networking, regulatory architecture, disaster recovery with zero trade loss.
Practice more system design case studies
- Design URL Shortener
- Design Social Media Feed
- Design Chat System
- Design Video Streaming
- Design Ride-Sharing Platform
- Design E-Commerce Platform
- Design UPI Payment Gateway
- Design Google Docs
- Design Tinder
- Design Google Drive / Dropbox
- Design Instagram
- Design Type-Ahead Search
- Design Web Crawler
- Design Ticket Booking (BookMyShow)
- Design Pastebin
- Design Notification System
- Design Rate Limiter (Standalone)
- Design Simple Web App
- Design Food Delivery (Swiggy)
- Design Live Streaming (Twitch)
- Design Distributed Key-Value Store
- Design Ad Click Aggregation
- Design Monitoring / Metrics (Datadog)
- Design Online Judge (LeetCode)
- Design FB Post Search
- Design Yelp
- Design Cache Layer
- Design Message Queue
- Design Full Production Stack
PrepGrind runs entirely in your browser, free, no installation required. Loading the interactive playground…