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.

Bids (Buyers)
QtyPriceTotal
Spread
--
Asks (Sellers)
PriceQtyTotal
Trade Log
Bid Orders0
Ask Orders0
Trades0
Last 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.

Best Bid--
Best Ask--
Spread--
Mid Price--

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.

Incoming Order
--
Resting Orders (Price-Time Priority)
Fills
AlgorithmPrice-Time
StepIdle
Fills0
Remaining--

Latency Optimization Strategies

Stock exchanges compete on latency. Click each strategy to see its impact on the order processing pipeline. Lower is better.

Network
500 us
Kernel
200 us
Sequencer
50 us
Matching
5 us
Publish
100 us
Total: 855 us
Colocation

Place trading servers in the same datacenter as the exchange. Reduces network round-trip from ~500us to ~5us.

Network: -99%
Kernel Bypass (DPDK/RDMA)

Skip the OS kernel network stack entirely. Packets go straight from NIC to userspace via memory-mapped buffers.

Kernel: -95%
FPGA / Hardware Acceleration

Implement order validation and risk checks directly in FPGA hardware. Deterministic sub-microsecond processing.

Sequencer: -90%, Matching: -80%
UDP Multicast for Market Data

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.

Throughput--
Daily Messages--
Daily Storage--
Yearly Storage--
Matching Engines--
Gateway Servers--
Network BW--
RAM per Engine--

Architecture

Traders / Brokers
Gateway (FIX Protocol)
Sequencer
Matching Engine
Market Data Publisher
Price feeds (UDP multicast)
Trade Store (WAL)
Append-only journal
Clearing & Settlement
T+1 / T+2 settlement
Order Flow
Trader → Gateway → Sequencer → Matching Engine → Execution Report
Market Data Flow
Matching Engine → Publisher → UDP Multicast → All Subscribers

Key Design Decisions

Consistency vs Availability

Strong Consistency (CP)
  • Every order must be sequenced deterministically
  • No duplicate executions allowed
  • Single sequencer avoids split-brain
  • Failover takes 10-50ms (market pauses)
vs
High Availability (AP)
  • 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

In-Memory Matching
  • 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
vs
Persistent Storage
  • 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.

Stock exchanges are the ultimate low-latency distributed system -- master order matching, sequencing, and the tradeoffs between speed and correctness.