Two brokers send buy orders for the same stock at the same price, three microseconds apart, and only 100 shares are offered. The exchange must give them to the first order, every time, and be able to prove it a year later.
That rule decides the architecture: ordering happens in one place, matching is repeatable, and a backup reaches the primary's state without a round trip per order. This post covers the order book, matching, the sequencer and journal, failover, market data, risk checks and LMAX-style latency techniques.
What the core has to guarantee
| Requirement | Design consequence |
|---|---|
| Fairness: better price first, then earlier order | One sequencer orders all inputs |
| Determinism: same inputs, same trades | No clock reads, randomness or I/O in the engine |
| Low, steady latency | Books in memory, one thread per shard, no locks |
| Auditability | An append-only journal of sequenced inputs |
| Availability without lost orders | Standby engines that replay the same journal |
Scope: a continuous central limit order book; opening and closing auctions follow other rules.
Order types the engine must handle
The SEC's investor bulletin on order types defines the common orders:
| Order | Definition | Engine behavior |
|---|---|---|
| Limit | At a specific price or better | Matches, then rests the remainder |
| Market | At the best available price, which is not guaranteed | Sweeps the other side; add a price protection limit |
| Immediate-or-cancel | Fill what you can now, cancel the rest | Matches, then drops the remainder |
| Fill-or-kill | Fill completely now or not at all | Checks quantity first, then fills or rejects |
| Cancel | Remove a resting order | Unlinks it from its price level |
Modifying an order is subtle. On CME Globex, an order loses its priority when you increase its quantity, change its price or change its account, so nobody can reserve a queue place with a small order and grow it later.
The order book: price levels and FIFO queues
Each side of the book is a sorted map of price levels: bids highest first, asks lowest first. Each level is a FIFO queue, oldest order first, which is time priority. A hash map from order ID to order makes cancels cheap.
final class Order {
long id, priceTicks, qty;
boolean isBuy;
Order prev, next; // neighbors in the same price level
PriceLevel level;
}
final class PriceLevel {
long priceTicks, totalQty;
Order head, tail; // head = oldest order = next to match
}
final class OrderBook {
NavigableMap<Long, PriceLevel> bids = new TreeMap<>(Comparator.reverseOrder());
NavigableMap<Long, PriceLevel> asks = new TreeMap<>();
Map<Long, Order> byId = new HashMap<>(); // a primitive long map in production
}
Adding at an existing price, cancelling and filling are O(1); only a new price level costs O(log n). Store prices as integer ticks, never as floating point. Nasdaq's TotalView-ITCH specification sends prices as integers with four implied decimal places, so $10.02 travels as 100200. Some engines replace the tree with an array of levels indexed by tick offset: constant-time lookups, paid for with memory for empty levels.
A matching walkthrough
The book in the diagram's note has S1 (300 shares) and S2 (200) offered at 10.02, and S3 (500) at 10.03. A buy limit order for 600 at 10.03 arrives:
| Step | Engine action | Trade | Book after |
|---|---|---|---|
| 1 | Best ask 10.02 is within the limit; oldest order first: S1 | 300 at 10.02 | S2 alone at 10.02 |
| 2 | Next in the same queue: S2 | 200 at 10.02 | Level 10.02 removed |
| 3 | Next level, 10.03: S3 | 100 at 10.03 | S3 keeps 400 and its place |
Trades print at the resting price, so the buyer pays 10.02 for 500 shares. A partial fill does not cost S3 its place. That one input produced three trades and execution reports for four orders, all tagged with its sequence number.
The sequencer and the journal
Fairness comes from one component: the sequencer. Every input, including cancels, trading halts and kill switch commands, gets the next sequence number and a timestamp there, and engines process inputs strictly in that order.
Before an engine acts on an input, the input is appended to the journal and copied to the standbys. The books exist only as the result of replaying that journal: event sourcing in its strictest form (see the CQRS and event sourcing diagram). Martin Fowler's article on the LMAX architecture describes this in production: an input stage journals, replicates and unmarshals each message before the single-threaded business logic sees it, and a restart that loads a snapshot and replays a day of journal takes less than a minute.
Replay requires determinism: take time from the sequencer, use integer arithmetic, avoid randomness and hash map iteration order, and never call another service from the engine.
The journal is cheap. At 64 bytes per record, a burst of 1 million inputs per second is 64 MB per second of sequential writes, and a 6.5-hour session averaging 100,000 inputs per second writes about 150 GB.
High availability by replaying the log
A deterministic engine needs no replicated database for failover. Feed a standby the same sequenced input with its output suppressed: at every sequence number it holds the same books as the primary, and if the primary fails it publishes from the next number. LMAX ran two processors in its main data center and a third at a disaster recovery site, all processing every input.
The hard parts move elsewhere:
- Replicate the sequencer's log with consensus, as in the Raft consensus diagram, so a new leader cannot lose or reorder acknowledged inputs.
- Fence the old primary with an epoch number on every output, so a slow one cannot publish after failover.
- Compare output hashes of primary and standby regularly. One nondeterministic line breaks failover silently.
Market data: levels and fan-out
Feeds come in three depths:
| Feed | Contents |
|---|---|
| Top of book (Level 1) | Best bid and ask with sizes, last trade |
| Depth by price (Level 2) | Total quantity at each price, several levels deep |
| Order by order (Level 3) | Every add, execute, cancel and replace |
Nasdaq TotalView-ITCH is order by order. Its Add Order message is 36 bytes, including a timestamp in nanoseconds since midnight and an 8-byte order reference.
Unlike the message brokers compared in pub/sub vs message queues, an exchange feed keeps no per-consumer state. The publisher numbers each message and sends it once, for example over UDP multicast; Nasdaq offers ITCH over MoldUDP64 and SoupBinTCP. Subscribers detect gaps by sequence number and recover from a retransmission service or a snapshot. Slower internal consumers such as surveillance can read events through Kafka, off the hot path.
Pre-trade risk checks and kill switches
An engine executes whatever reaches it. According to the SEC, Knight Capital sent more than 4 million orders in the first 45 minutes after the open on August 1, 2012, while trying to fill 212 customer orders, and lost more than $460 million.
Check before sequencing, in memory: credit limits, price bands around a reference price, maximum order size, duplicates and message rates (a per-firm rate limiter). In the US, Rule 15c3-5 requires broker-dealers with market access to have controls reasonably designed to prevent orders that exceed pre-set credit or capital thresholds, erroneous orders that exceed price or size parameters, and duplicative orders. This is not legal advice; read the rule text.
A kill switch cancels a firm's resting orders and blocks new ones. Send it through the sequencer so every replica applies it at the same sequence number. Exposure limits also need fills, so the risk stage must consume execution reports.
Why low-latency engines avoid locks and garbage
In Fowler's 2011 article, LMAX's business logic processor could handle 6 million orders per second on a single thread in a benchmark. The team's Disruptor paper shows why one thread wins. Incrementing a 64-bit counter 500 million times took:
| Method | Time |
|---|---|
| Single thread | 300 ms |
| Single thread with an uncontended lock | 10,000 ms |
| Two threads with a lock | 224,000 ms |
| Two threads with CAS | 30,000 ms |
An uncontended lock made the loop 33 times slower; contention, about 750 times. So keep one writer per piece of memory, pass messages through preallocated ring buffers instead of locked queues (LMAX's input buffer had 20 million slots), and create no garbage on the hot path. LMAX restarted nightly, mainly to wipe memory so an expensive garbage collection was less likely during trading.
The exchange order path diagram
Diagram contents
- Broker firms
- Order gateway
- Pre-trade risk
- Sequencer
- Matching engines, sharded by symbol
- Engine A–M
- Engine N–Z
- Market data publisher
- Event journal
- Backup engine A–M
- Market data subscribers
- orders
- validated
- accepted
- A–M
- N–Z
- append in order
- replay
- book events
- multicast feed
- execution reports: acks, fills
How to read it:
- Left to right is the order path: broker firms, gateway, pre-trade risk, sequencer.
- The sequencer routes symbols A–M and N–Z to their engines (amber) and appends every input to the journal.
- Each engine runs one thread and sends execution reports back to the gateway (green) and book events to the market data publisher (purple).
- The dashed edge is failover: the backup replays the journal and stays silent until promoted. Each shard has one.
- The note holds the order book and the walkthrough.
Drawing exchange architecture diagrams clearly
- Draw one sequencer. If a reader finds two places where order is decided, the design has a fairness bug.
- Label edges with message types, and show private fills and public market data as separate paths.
- Dash replay and standby paths, so nobody mistakes the backup for an active engine.
- Keep databases off the hot path. A database between sequencer and engine is a different, slower system.
- Collect numbers in one note: tick size, shards, journal growth, failover time.
The walkthrough from requirements to a system design diagram has a general checklist.
Build it in Archboard
- Sign in with Google or GitHub and create a diagram.
- Add an External System from the C4 Model pack named Broker firms, then three Container nodes: Order gateway, Pre-trade risk and Sequencer, each with a technology and a description. Label the edges orders, validated and accepted.
- Add a Frame from the Core pack titled Matching engines, sharded by symbol, with two Container nodes inside: Engine A–M and Engine N–Z. Connect the sequencer to each (A–M, N–Z).
- Below the sequencer, add a Database from the C4 Model pack named Event journal and a Container named Backup engine A–M. Connect the sequencer to the journal (append in order) and the journal to the backup with a dashed edge (replay).
- Add a Container named Market data publisher and an External System named Market data subscribers below it. Connect both engines to the publisher (book events), the publisher to the subscribers (multicast feed) and the frame back to the gateway (execution reports: acks, fills).
- Add a Markdown block from the Core pack with the order book and fills, and short Text notes from the same pack.
To start from text, write the flow as a Mermaid flowchart and convert it with the free Mermaid flowchart tool.
The example uses 12 diagram nodes, within the Free plan.
FAQ
What is a matching engine? The exchange component that keeps each instrument's order book and matches incoming orders against resting ones, for example by price-time priority.
What data structure is used for an order book? Per side, a sorted map of price levels, each a FIFO queue of orders, plus a hash map from order ID to order. Fills and cancels are O(1); a new price level costs O(log n).
What is price-time priority? Better prices execute first, and at the same price, earlier orders execute first. CME Globex calls this FIFO matching.
Why are matching engines single-threaded? Each trade changes the book for the next order, so matching is sequential anyway. One thread per shard avoids locks and keeps results deterministic, which makes replay possible.
How does an exchange fail over without losing orders? Every input is sequenced and journaled before processing, and a standby processes the same sequence with its output suppressed. If the primary fails, the standby takes over at the next sequence number.