Scope
Functional
- Brokers submit limit and market orders (buy/sell), and can cancel or modify them.
- Orders are matched by price-time priority; trades are reported to both sides.
- Publish market data: trades, best bid/offer, and order book depth.
- Pre-trade risk checks (credit limits, price bands, fat-finger checks).
- Trading sessions: pre-open auction, continuous trading, close.
Non-functional
- Matching latency in microseconds (p99 well under 1 ms inside the exchange).
- Determinism and fairness: the same inputs in the same order always produce the same trades.
- Zero loss of acknowledged orders; fast failover.
- Thousands of instruments; peaks of hundreds of thousands to millions of messages/s (most are new orders and cancels).
Out of scope: clearing and settlement, the broker apps, regulatory reporting detail.
Size
- 5,000 instruments; peak 1M messages/s in total, but heavily skewed: the top 50 instruments get most of the traffic.
- A single well-written matching thread handles millions of simple operations per second in memory, so even the busiest instrument fits on one core.
- An order book's live state is small (tens of thousands of resting orders × ~100 B), so everything fits comfortably in RAM.
Decision: shard by instrument, never within an instrument. Each instrument's book is owned by exactly one single-threaded engine.
The order book
For each instrument, the engine keeps two sides:
| Bids (buy) | Asks (sell) | ||
|---|---|---|---|
| Price | Orders, in arrival order | Price | Orders, in arrival order |
| ₹101.50 | A: 200, D: 50 | ₹101.55 | B: 100 |
| ₹101.45 | F: 500 | ₹101.60 | C: 300, E: 75 |
Price-time priority: the best price matches first; at the same price, the earliest order matches first. A new buy at ₹101.60 for 150 shares fills 100 from B at ₹101.55, then 50 from C at ₹101.60, leaving C with 250.
Data structure: per side, a sorted map of price levels (or an array indexed by tick for dense price ranges), each holding a FIFO queue of orders, plus a hash map order_id → order for O(1) cancels.
Architecture
The 30-second summary
"Each instrument's order book lives in memory on a single-threaded matching engine, sharded by instrument. All inputs pass through a sequencer that assigns a gap-free sequence number and replicates them to a journal before acknowledging. Engines are deterministic functions of that journal, so hot replicas stay identical and failover or recovery is just replay. Matching is price-time priority with sorted price levels and FIFO queues. Market data goes out on sequenced multicast with gap recovery, and pre-trade risk runs before sequencing so it never slows the matcher."
Follow-up questions the interviewer may ask
- How is a market order handled when the book is thin?
- How do you run the opening auction?
- Why not use a database for the order book?
Model answers to each of these are in the book.