System design case study C24 · Determinism · Low latency

Design a Stock Exchange Matching Engine

Most systems scale out to go faster. An exchange does the opposite: it keeps each order book on a single thread, in memory, in strict order, because fairness and determinism matter more than anything else.

What you'll be able to explain
  • Explain order books, order types and price-time priority
  • Design a deterministic, single-threaded matching engine with replication
  • Sequence every input so the whole system can be replayed exactly
  • Publish market data to many subscribers with low latency
  • Add risk checks, persistence and failover without losing a single order

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

CLIENTBrokersNETWORKOrder gatewayssessions, validationSERVICEPre-trade riskQUEUE / LOGSequencertotal order + journalWORKERMatching engine Ainstruments 1–500WORKERMatching engine Binstruments 501–1000NETWORKMarket datapublishersSERVICEDrop copytrade reportsFIX / binary
Exchange core: gateways → sequencer → single-threaded matching engines per instrument group → market data.

The 30-second summary

Say it in the interview

"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

  1. How is a market order handled when the book is thin?
  2. How do you run the opening auction?
  3. Why not use a database for the order book?

Model answers to each of these are in the book.