Design a Stock Exchange: Microsecond Sequencers, L1/L2/L3 Order Books & Determinism
Where 10 Milliseconds Is an Eternity
Electronic Stock Exchange Matching Engine Architecture
1. The Ultra-Low-Latency Critical Path
Broker (FIX Protocol) ──► [Client Gateway + Risk Checks]
│
▼
[Inbound Sequencer (Order ID)]
│ (Memory-Mapped Ring Buffer / mmap)
▼
[Single-Threaded Deterministic Matching Engine]
├──► Updates In-Memory Order Book (FIFO Price Levels)
└──► Outbound Sequencer ──► Market Data (UDP) & Clearing
Why the Core Matching Engine Is Single-Threaded!
mutex, rwlock) introduces unpredictable OS context-switch stalls and cache-line bouncing (10–100µs jitter).
Instead, run an application loop pinned to dedicated isolated CPU cores (1 engine per ticker symbol group, like AAPL), processing ordered events sequentially from a lock-free mmap ring buffer (similar to the LMAX Disruptor pattern)—zero locks, zero heap allocations, deterministic execution!2. Inside the Order Book: $O(1)$ Price-Time Priority
Bid buy book sorted descending, Ask sell book sorted ascending) optimized for three $O(1)$ hot-path operations (New, Cancel, Match):- Price Level Map (
Hash Map / Tree): Mapsprice -> PriceLevel. - Orders at Each Price (
Doubly Linked List): Enforces strict FIFO time priority; maintaining an auxiliary hash maporder_id -> node_ptrallows cancelling any resting order in $O(1)$ without scanning lists!
Market Data Feed Levels:
- L1 Data: Best Bid and Best Ask prices/quantities only.
- L2 Data: Aggregated order quantities per price level (top 5–20 depth tiers) broadcast via UDP Multicast for ultra-fast broker updates.
- L3 Data: Full individual resting orders and queue positions.
3. Determinism & Hot-Standby Failover (Zero Data Loss)
- Inbound & Outbound Sequencers assign strict monotonic sequence numbers (
seq_id) to every incoming order and outgoing execution event. - Event Sourcing + Raft: Because the matching engine is a 100% deterministic pure state machine (same input sequence $\equiv$ exact same order book state + fills!), Replicated Hot-Standby nodes simply consume the identical sequenced input stream via Raft / Aeron Cluster in real time.
- If the primary matching host experiences a hardware fault, the Hot-Standby takes over in milliseconds with zero lost orders or phantom trades!