Design a Stock Exchange
Order Matching Engine, Order Book, Depth Charts, Low-Latency Architecture, and Financial Settlement
A stock exchange matches buy and sell orders for financial instruments in real time. The core component is the matching engine, which maintains an order book per symbol -- a sorted collection of bids (buy orders) and asks (sell orders). Orders are matched using price-time priority: best price first, then earliest arrival. Key challenges: ultra-low latency (sub-microsecond matching), deterministic sequencing (every order gets a unique sequence number), fault tolerance without sacrificing speed, and regulatory compliance (audit trails, circuit breakers). Modern exchanges like NASDAQ process millions of orders per second with median latencies under 10 microseconds.
Order Book Visualizer
Interact with a limit order book. Place limit and market orders, watch them enter the book or get matched instantly. The order book shows bids (green, buyers) and asks (red, sellers) sorted by price.
Order Book Depth Chart
Visualize cumulative order volume at each price level. The area where bids and asks meet reveals the spread -- the gap between the best bid and best ask. A narrow spread indicates high liquidity.
Matching Engine: Price-Time Priority
The matching algorithm follows strict price-time priority: best price is matched first, and at the same price level, the earliest order (FIFO) takes priority. Click "Animate Match" to watch an incoming order get matched against resting orders.
Latency Optimization Strategies
Stock exchanges compete on latency. Click each strategy to see its impact on the order processing pipeline. Lower is better.
Place trading servers in the same datacenter as the exchange. Reduces network round-trip from ~500us to ~5us.
Network: -99%Skip the OS kernel network stack entirely. Packets go straight from NIC to userspace via memory-mapped buffers.
Kernel: -95%Implement order validation and risk checks directly in FPGA hardware. Deterministic sub-microsecond processing.
Sequencer: -90%, Matching: -80%Broadcast trade/quote updates via multicast instead of per-connection TCP. All participants receive data simultaneously.
Publish: -80%Capacity Estimation
Size the infrastructure for a stock exchange. Estimate orders/sec, throughput, and storage requirements.
Architecture
Key Design Decisions
Consistency vs Availability
- Every order must be sequenced deterministically
- No duplicate executions allowed
- Single sequencer avoids split-brain
- Failover takes 10-50ms (market pauses)
- Multi-master replication for zero downtime
- Risk of duplicate or out-of-order fills
- Requires complex reconciliation
- Unacceptable for regulated exchanges
In-Memory vs Persistent
- All active orders in RAM (sub-us access)
- Write-ahead log for durability
- Replay log to rebuild state on crash
- Used by NASDAQ, NYSE, LSE
- Orders persisted to disk on arrival
- Slower but simpler recovery
- Acceptable for crypto / lower-volume exchanges
- SSD NVMe narrows the gap
Single Sequencer
All orders pass through a single sequencer that assigns monotonically increasing sequence numbers. This ensures deterministic ordering -- if the matching engine replays the same sequence, it produces the same fills. The sequencer is the bottleneck by design: correctness over throughput. Failover uses a hot standby that tails the sequencer's journal.
Symbol-Level Partitioning
Each symbol (e.g., AAPL, TSLA) has its own independent order book and can run on a separate matching engine core. Orders for different symbols never interact, enabling horizontal scaling. A gateway routes each order to the correct partition by symbol hash. This is the primary scaling strategy.
Risk Checks & Circuit Breakers
Pre-trade risk checks validate order size, price bands, and account limits before the order reaches the matching engine. Circuit breakers halt trading if a stock moves more than 5-10% in 5 minutes (LULD bands). These must execute in the critical path with nanosecond overhead -- often implemented in FPGA.
Market Data Distribution
Every fill, cancel, and new order generates a market data event. Distribute via UDP multicast for fairness (all subscribers receive simultaneously). Maintain both a Level 1 feed (best bid/ask, last trade) and Level 2 feed (full order book depth). Sequence numbers detect gaps for reliable delivery.