Video in progress
How do you design an order matching system for an exchange: latency, strict ordering and failures?
For each instrument, matching runs on a single thread with an in-memory order book, in strict sequence, which is faster than distributed locks and deterministic. Orders are first written to a journal with a sequence number; after a failure the engine replays the journal to reach the same state, and a hot standby applies the same journal in parallel.
📖 Answer
The "stateless service + DB" approach doesn't work here. The requirements: sub-millisecond latency, fair strict ordering (price priority, then time priority), and not a single trade lost.
The order book. For each instrument, two sides in memory: bids sorted by price descending, asks ascending, with a FIFO queue at each price level. A new limit order "eats" the matching prices on the opposite side, and the rest is added to the book.
Why one thread? If all orders of one instrument are applied in a single sequential stream, there are no locks and no races, and the result is deterministic. A well-written single thread handles hundreds of thousands of orders per second and more. Scale comes per instrument: each engine takes its own set of instruments. The LMAX architecture (Disruptor) made this idea popular.
The flow:
- Gateway: authentication, validation, risk checks, with the balance reserved in advance.
- The sequencer gives each order a sequence number and writes it to a replicated journal. From this point the order is "accepted".
- The matching engine reads from the journal, applies it and emits trade events.
- Downstream: balances in the ledger, market data distribution, confirmation to the client, all driven by events.
Failure. The engine is deterministic, so state is restored by replaying the journal; for speed, a periodic snapshot and then the part after it. A hot standby applies the same journal in real time and takes over immediately if the primary dies. To make sure both never emit trades at the same time: a leader lease and an epoch, and dedup on the sequence number in the output events.
The Java side. A GC pause is the enemy here: allocation-free code on the hot path (objects are reused), primitive collections, a low-pause GC (ZGC), and pinning threads to CPU cores.
Protection. Reject orders outside the price band, pause trading temporarily on sharp moves, and rate-limit per user.
In an interview I put the main point like this: where you need strict ordering, a single sequential writer plus a replicated log is often the simplest and fastest solution, not a distributed transaction.
Sign up to mark studied questions and save your progress.