Full answer
Requirements
Functional:
- Accept limit and market orders, cancels and modifications for thousands of symbols.
- Match by price-time priority: best price first, and the earliest order at that price first.
- Publish trades and market data; send execution reports to brokers.
Non-functional:
- Matching latency in microseconds to low milliseconds, with very low variance.
- No accepted order is lost; the same input always yields the same trades.
- Fair: no participant gets an unfair ordering advantage.
Capacity estimates
Assumptions: 100,000 orders per second at peak across 5,000 symbols, 200 bytes per log event, a 6.5-hour trading day.
- Log volume: 100,000 x 200 bytes = 20 MB per second; 20 MB x 6.5 x 3,600 = about 468 GB per day.
- Per symbol: busy symbols get a few thousand orders per second; one in-memory single-threaded engine can process more than 1M simple operations per second, so even the busiest symbol fits on one thread.
- Order book memory is small: a few hundred thousand resting orders per symbol at most.
API
Brokers connect over a binary protocol (FIX or a native one) through gateways:
NewOrder {client_order_id, symbol, side: BUY, type: LIMIT, price: 251.50, qty: 100, time_in_force: DAY}
Cancel {client_order_id, orig_client_order_id}
ExecutionReport {order_id, status: PARTIALLY_FILLED, filled_qty: 60, price: 251.45}
MarketData {symbol, best_bid, best_ask, depth levels, last_trade}
Prices are integers in ticks (for example paise or cents), never floats.
Data model
In memory per symbol:
- Bids: price levels sorted high to low; each level is a FIFO queue of orders.
- Asks: price levels sorted low to high.
- Order map: order_id to its node, so cancels are O(1).
Durable:
- Sequenced input log: every accepted command with a sequence number.
- Output log: trades and execution reports, also sequenced.
High-level design
flowchart LR
B[Brokers] --> GW[Order gateways: validation and risk checks]
GW --> SEQ[Sequencer]
SEQ --> LOG[(Replicated input log)]
LOG --> ME1[Matching engine primary]
LOG --> ME2[Matching engine replica]
ME1 --> OUT[(Trade and report log)]
OUT --> MD[Market data publisher]
OUT --> GW
OUT --> CLR[Clearing and settlement]Matching
A buy limit at 251.50 for 100 shares arrives. While its quantity remains and the best ask is at or below 251.50, it trades with the oldest order at the best ask level, removing filled orders. Any remainder rests in the bid book at 251.50, behind earlier orders at that price.
The engine runs on one thread per symbol group: no locks, no shared state, and processing in sequence order. Determinism lets a replica that consumes the same log produce the same book and trades, so failover is a switch to a warm replica, not a recovery from disk.
Bottlenecks and trade-offs
- Sequencer and log are on the critical path; they are replicated synchronously within the data centre (microseconds) before an order is acknowledged.
- Risk checks (credit limits, price bands) happen in gateways before sequencing, so the engine stays simple.
- Latency variance matters as much as average: avoid garbage collection pauses, pin threads to cores, pre-allocate memory and use kernel-bypass networking.
- Fairness. Some exchanges add small randomised or fixed delays to reduce speed races; others offer equal-length cables in co-location.
- Scaling is by partitioning symbols across engines; one symbol is never split, because price-time priority needs a single order.
By level
Fresher: Explain buy and sell queues sorted by price and time, and walk through one match. A fresher should know that every order must be recorded before it is processed.
Mid: Design the in-memory book, sequencer and log, and deterministic replicas. Do the log volume math and explain cancels.
Senior: Discuss latency variance, kernel bypass, risk checks, auctions, cross-site disaster recovery and fairness mechanisms. Expect a clear reason why one book stays on one thread.
Key points
- Single-threaded engine per symbol group with in-memory price-time books
- Sequence orders into a replicated log before matching
- Deterministic replay gives identical replicas and fast failover
- Integer tick prices; O(1) cancels through an order map
- Scale by partitioning symbols, never by splitting one book
Common mistakes
- Using a database transaction per order on the hot path
- Multi-threaded matching on one book with locks
- Floating-point prices
- Acknowledging orders before they are durably sequenced
Follow-ups
- How would you implement stop orders?
- How do you run an opening auction?
- How do you recover if the primary data centre is lost?
Tips
- Explain price-time priority with a small example
- Stress determinism and the input log
- Talk about latency variance, not only average latency
Evaluation rubric
- Correct order book structure
- Durable sequencing before matching
- Deterministic replication and failover
- Latency and partitioning trade-offs