BLUEPRINT #03Financial & Transactional
Design a Stock Exchange Matching Engine
Referenced Architecture Primitives (4)
Click any primitive to study its algorithmic deep dive10-Stage Structure:1. Requirementsβ2. Sizingβ3. Topologyβ4. Data Modelβ5. AWS Topologyβ6. Deep-Diveβ7. Failuresβ8. SRE Playbooks
1. Problem Statement & Scope Clarification
System Mission
Design an ultra-low latency, deterministic electronic exchange matching engine (similar to NASDAQ, CME, and LMAX) capable of executing hundreds of thousands of limit and market orders per second with strict Price-Time Priority (FIFO), sub-50 microsecond () matching latencies, zero lock contention, and zero data loss.
Functional Requirements
- Order Ingestion (
PlaceOrder): Ingest Limit, Market, and Cancel orders with sub-microsecond parsing using binary protocols (SBE / FIX / ITCH-OUCH). - Deterministic Price-Time Priority (FIFO Matching):
- Orders matched first by Best Price (Highest Bid, Lowest Ask).
- Equal price orders matched strictly by arrival sequence timestamp.
- Order Cancellation & Modification (
CancelOrder/ModifyOrder): Execute cancellations in constant time. - Market Data Feed Dissemination: Broadcast real-time Level 2 (Aggregated Price Depth) and Level 3 (Full Order State) feeds to market participants.
- Asynchronous Clearing & Settlement: Decouple the ultra-low latency matching core from downstream settlement, risk reporting, and regulatory clearing.
Non-Functional Requirements (SLAs & SLOs)
- Ultra-Low Latency: End-to-end matching latency , , .
- 100% Determinism: Replaying the sequenced input log on a backup node MUST produce an identical trade execution tape.
- High Availability: Sub-millisecond failover to a hot-standby replica with zero uncommitted state loss.
- Throughput: Support per matching engine partition.
2. Capacity & Scale Estimation (Back-of-the-Envelope Math)
Ingestion Scale & Latency Budget
- Listed Tradable Symbols: (Equities, Futures, Options).
- Peak Order Ingestion Rate: per active partition.
- Daily Order Volume: (500M orders/day).
- Average Trades Executed: ( fill ratio).
Microsecond Latency Budget Breakdown ( Target)
| Subsystem Component | Target Latency | Implementation Technique |
|---|---|---|
| Network Ingress & Kernel Bypass | AWS Direct Connect 100 Gbps + DPDK / ENA Kernel Bypass | |
| Monotonic Sequencer & Wire Parse | Hardware FPGA / Pinned Sequencer with Simple Binary Encoding (SBE) | |
| LMAX Lock-Free Ring Buffer | Cache-line padded memory ring buffer (Zero CPU context switching) | |
| In-Memory Order Matching | Single-threaded B-Tree / Intrusive Doubly-Linked List in CPU L3 Cache | |
| Synchronous NVMe SSD Journaling | SPDK (Storage Performance Development Kit) append-only WAL | |
| Market Data UDP Multicast | Binary Level 2 UDP Multicast Feed | |
| Total End-to-End P99 Latency | Achieved via zero-allocation, zero-garbage collection C++/Rust |
Memory Sizing for In-Memory Order Books
- .
- Order struct size in memory: (fits exactly in 1 CPU cache line). The entire global order book easily fits into the physical RAM and L3 CPU cache of a single bare-metal server.
3. High-Level Architecture & AWS Component Mapping
Interactive Architecture DiagramSynthesizing vector architecture diagram...
4. In-Memory Order Book Data Structures
To achieve sub-microsecond price lookup and order cancellation:
- Price Levels: Indexed via a Sparse Direct-Indexed Flat Array or Red-Black Tree ordered by price.
- Time Priority at Price Level: Intrusive Doubly-Linked List of
Orderstructs (FIFO queue). - Order Lookup Map: Cache-padded Flat Hash Map (
order_id -> Order*) enabling cancellation without tree traversal.
textSymbol OrderBook (e.g. AAPL): BIDS (Highest Price First): Price: $185.50 -> [Order 101 (100 sh)] <-> [Order 104 (500 sh)] <-> [Order 109 (50 sh)] Price: $185.49 -> [Order 102 (200 sh)] <-> [Order 105 (100 sh)] Price: $185.48 -> [Order 108 (1,000 sh)] ASKS (Lowest Price First): Price: $185.51 -> [Order 103 (300 sh)] <-> [Order 106 (150 sh)] Price: $185.52 -> [Order 107 (400 sh)]
Cache-Line Friendly C++ Order Struct (64 Bytes Aligned)
cppstruct alignas(64) Order { uint64_t order_id; // 8 bytes uint64_t sequence_num; // 8 bytes uint64_t timestamp_ns; // 8 bytes uint32_t account_id; // 4 bytes uint32_t symbol_id; // 4 bytes int64_t price_cents; // 8 bytes uint32_t remaining_qty; // 4 bytes uint8_t side; // 1 byte (0 = BUY, 1 = SELL) uint8_t order_type; // 1 byte (0 = LIMIT, 1 = MARKET) uint8_t padding[18]; // 18 bytes padding to fill exactly 64 bytes Order* prev; // Intrusive list pointer Order* next; // Intrusive list pointer };
5. The LMAX Disruptor Lock-Free Concurrency Engine
Multi-threaded matching engines suffer from thread context switching, OS kernel scheduling jitter, and mutex lock contention ( penalties). The system uses the LMAX Disruptor pattern:
Interactive Architecture DiagramSynthesizing vector architecture diagram...
Why Single-Threaded CPU Pinning Wins
- Zero Mutex Locks: No CPU spinlocks, condition variables, or kernel context switches.
- L1/L2 Cache Warmth: Order book memory stays pinned in CPU L1/L2 cache lines with zero cache eviction from context switches.
- Predictable Execution: Eliminates the long-tail latency distribution ( is nearly identical to ).
Part 2: Production Deep-Dive Locked1 Coin = 24 Hours
Unlock Complete Architecture & Production Runbooks
Your Balance:40 Coins
You have explored the free architectural preview (~48%). Spend 1 Coin to unlock the remaining 6 production deep-dive sections for a full 24 hours.
Sections Included in This 24-Hour Pass:
6. Detailed Order Execution Workflow
7. Matching Engine Architecture Trade-Off Matrix
8. Failure Modes, Resiliency & Critical Edge Cases
9. Production Pitfalls & Anti-Patterns (The "Gotchas")
10. Production Runbook & Observability Guide
11. Interview Strategy & System Design Rubric
Keeps page unlocked for exactly 24 hoursSpend coins to fund LLM & compute infrastructure