📈 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

Non-functional requirements & scale

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

API design

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

What interviewers expect by level

Practice more system design case studies

PrepGrind runs entirely in your browser, free, no installation required. Loading the interactive playground…