Stock Exchange
Ch. 29 Case Studies System designThe problem
An electronic stock exchange does one fundamental job that has not changed in fifty years: it matches a buyer with a seller who are willing to trade at the same price. What has changed is the machinery. Orders now arrive as data packets, are checked, sequenced, and matched by software in a few microseconds, and the result is broadcast to every participant before the trader has finished blinking.
The design is a study in opposing pressures. The critical trading path must be fast — millisecond-level round trips — yet it must also be fair and auditable, so that the result of two orders that arrive at the same instant is the same no matter how it is replayed. And it must stay available, because a single second of downtime moves real money.
Today you will build one: trace an order from a broker through the gateway and the risk checks to the matching engine, design the order book, and make the whole thing fast, fair, and recoverable.
Requirements
Functional — what it must do
- A client, through its broker, can place a new limit order and can cancel one that is still resting in the book.
- When a buy and a sell are willing to trade at the same price, the exchange matches them and returns a filled execution to both sides.
- Every participant can see the live order book — the best bids and best asks — in real time.
- Enforce risk rules before an order is matched, and withhold a user's funds while an order rests in the book so no one can overspend.
Non-functional — how well it must do it
- Latency: the round trip from an order entering the exchange to its fill returning is in the low milliseconds, with the 99th percentile kept tight and stable.
- Availability: at least 99.99% during trading hours, with a fast, deterministic recovery when a node fails.
- Fairness and determinism: two orders that arrive at the same instant must match in the same order on replay, so the result is auditable and dispute-free.
- Security: authenticate every order, verify identity before an account is opened, and keep the public market-data feed DDoS-resistant.
Scale — how much it must take
- Tens of thousands of concurrent trading users and at least 100 symbols, moving billions of orders per day through the matching engine.
Assumptions — the numbers this design is sized for
A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.
Takeaways
- Scope to a single instrument and order type first — stocks and limit orders — so the matching and risk logic stays correct and focused.
- Gate every order through the client gateway, then risk checks and a wallet hold, so only legal, funded orders reach the matching engine.
- Assign a global sequence number at one sequencer: it is what makes matching fair and what makes replay deterministic.
- Keep the order book organized by price so best-bid/ask lookups and matches are constant time, independent of book size.
- Match on price priority first, then time priority (FIFO) at the same price level.
- Withhold a user's funds when an order rests and release or settle them on cancel or fill, so no one can overspend.
- Treat the event log as the source of truth: recovery is a deterministic replay, and the p99 latency tail is a defect to eliminate.
Scope: what does the exchange do
An exchange can trade many instruments and order types. Pinning down the subset we support fixes the matching engine's complexity.
- 1Narrow the instruments
We scope to stocks only. Options, futures, and currencies each bring their own payoff and settlement rules, and adding them multiplies the matching and risk logic. Limiting the scope to a single instrument class keeps the design focused on the core of matching buyers and sellers.
- 2One order type, two operations
We support only limit orders — an order to buy or sell at a price no worse than the one stated. A market order fills at whatever the current best price is, which adds the complexity of price improvement and partial fills. We keep place and cancel as the two operations, and skip conditional and after-hours trading. That is the cleanest correct exchange.
The critical trading path
An order crosses a chain of gates before it is matched. Every hop on this path spends the millisecond budget, so each one must be cheap and in order.
- 1The order's journey
A client's order enters at a broker, hits the client gateway for validation, authentication, and rate limiting, then moves to the order manager which runs the risk checks. A sequencer assigns it a global order number, and only then does the matching engine see it. The fill travels back the same way to both sides.
- 2Why the order number matters
Orders arrive from many brokers at once, so the exchange must impose a single global order. The sequencer is the one place that assigns a number to every order, in the order it accepts them. That number is what makes matching fair: two orders are never matched on the basis of which server happened to receive them first, but on their sequence.
- 3Risk before matching
The order manager checks the order against the risk rules before it is sequenced. An order that violates a rule is rejected here, fast, so it never reaches the matching engine and never touches the book. That keeps the engine's job pure: match orders it has already been told are allowed.
The order book
The book is the heart of the exchange: a list of buy orders and sell orders for a symbol, organized by price. How fast it can be read and changed is how fast the exchange is.
- 1Bids and asks
For each symbol, the book holds two lists. On one side, the bids: buy orders, highest price first. On the other, the asks: sell orders, lowest price first. The best bid and the best ask — the top of each list — are the price the world quotes for that symbol, and the gap between them is the spread.
- 2Why price is the key
When a new order arrives, the engine must instantly find every resting order at a price that can trade with it. Organizing the book by price means that lookup is a direct jump to the price level, not a scan. Adding, canceling, and matching an order should each be close to constant time, so the engine's speed does not depend on how many orders are in the book.
- 3A fill walks the book
A buy at 101.55 arrives. It can trade against every ask at or below that price. So it matches the best ask at 101.60 — wait, that is above its price, so it does not match at all; it rests. But a buy at 101.70 matches the ask at 101.60 fully, then the ask at 101.70 partially, until it is filled or the price runs out. The walk is always in price order, from the best level outward.
Matching: price first, time second
When a new order can trade against resting ones, the engine decides who goes first. The two rules are price priority, then time priority.
- 1Price priority
The first rule is that the best price trades first. A buyer at 102 beats a buyer at 101, because the higher bid is more eager and would have accepted a worse price. So when a sell comes in, it matches the highest bid first, then walks down. The book is always sorted so this walk is a straight line.
- 2Time priority (FIFO)
Among orders at the same price, the one that arrived first goes first. That is the FIFO rule: the order book remembers the sequence at each price level, and a new order matches the oldest resting order at the best price before any newer one. It is the rule that makes the exchange fair at the price level.
- 3A fill produces two executions
When a buy and a sell match, the engine records one trade but emits two executions — one for the buyer, one for the seller — each saying how many shares filled at what price. Both are pushed to their owners' order managers and into the market-data feed, so everyone sees the trade at the same moment.
Risk checks and the wallet
Before an order can match, the exchange must be sure the user is allowed to trade and actually has the funds. These checks run on the critical path and must be cheap.
- 1The rule set
Risk rules are the exchange's guardrails. A simple one: a user can trade at most one million shares of any single stock per day. Others cap position size, check trading halts, and enforce the exchange's minimum order increments. An order that breaks any rule is rejected before it reaches the sequencer, so it costs the book nothing.
- 2Withhold, don't just check
A resting order in the book still holds a claim on the user's money. If the exchange did not reserve those funds the moment the order was placed, the user could place enough orders to cover the same cash twice. So the wallet withholds the required funds when the order rests and releases them only when the order is canceled or filled.
- 3Release on cancel or fill
When a resting order is canceled, the withheld funds go back to the user's available balance. When it is filled, the withheld amount is settled against the trade. Either way, the wallet never holds more than the resting orders require, and it never lets the same dollars back two different orders.
Fast, fair, and recoverable
The exchange must be fast, but it must also be the same every time it runs the same orders. Event sourcing is the trick that gives you both.
- 1The event log is the truth
Every order, cancel, and fill is appended to an ordered event log before the engine acts on it. That log is the source of truth: the in-memory book is just a fast view over it. If a node dies, the recovery is not a reconstruction but a replay — read the log and rebuild the book exactly as it was.
- 2Deterministic replay
Because matching depends only on the order of events and not on the wall-clock time they were received, replaying the same log always produces the same book and the same set of fills. That is determinism, and it is what lets two data centers agree on who won a race, and on what a dispute should resolve to.
- 3Tight, stable latency
It is not enough that the average round trip is low; the 99th percentile must be low and stable, because a single slow trade in a race is a lost trade. The exchange keeps a histogram of every round-trip time and treats a rising tail as a defect — often a garbage-collection pause or a context switch — and fixes it.
End to end
One buy order against a resting sell: it is validated, risk-checked, sequenced, matched at the best price, the wallet settles, and the trade is broadcast. That is the whole exchange in one picture.
- 1The whole exchange
Clients send orders to the client gateway. Validated orders pass the order manager's risk checks and the wallet's hold, take a sequence number at the sequencer, and enter the matching engine. The engine works a per-symbol order book. Every fill and the updated book are pushed to the market-data feed and to both sides.
- 2A buy enters the path
A buy of 1,000 shares at 101.70 arrives. The gateway validates it and authenticates the broker. The order manager checks the risk rules — under the daily cap — and the wallet withholds the funds. The sequencer stamps it with the next global number. It is now legal to match.
- 3It matches the best ask
The engine looks at the book. The best ask is 101.60, below the buy's 101.70, so it matches. The engine takes as many shares as the resting sell has — 600 — and, if the buy is not yet filled, continues to the next ask level. The trade is recorded and the two executions are emitted.
- 4The wallet settles, the feed broadcasts
The wallet settles the matched shares and releases any remainder of the hold. The engine pushes the two executions to the buyer and seller, and the updated book to the market-data feed. Everyone sees the trade and the new best prices at the same instant. The round trip is well inside the millisecond budget.
In the wild
The same order-sequencing, order-book, and deterministic-replay ideas power the real exchanges that move trillions a day. Here is where each piece shows up.
- 1These exchanges run it
Everything you just built is a production equity exchange. The client gateway, the risk-and-wallet gate, the sequencer, the matching engine, and the deterministic event log are the same components the large exchanges are built from. Let's match the diagram to the names.
- 2LMAX: the matching engine as open source
LMAX built its exchange around a single, lock-free in-memory structure — the Disruptor — and open-sourced it. The core idea is exactly your sequencer-plus-engine: orders flow through a single ordered, in-memory ring with no locks on the hot path. It is the 'fast and deterministic' requirement, taken to the extreme and published for anyone to read.
- 3IEX: fairness as the product
The IEX was founded on the argument that speed is the problem: its whole model is about not letting the fastest trader run the market, with a speed bump and a price collar. That is your determinism and fairness section, promoted from a design goal to the business model — the exchange is designed so the result is the same for everyone, not just the colocated ones.
- 4Coinbase: the same spine, crypto assets
Coinbase's exchange runs the same order lifecycle you designed — gateway, risk, matching engine, order book, market data — but for digital assets, and it has written about running it at scale on commodity cloud hardware. The instrument is different; the spine is the same, which is why this design generalizes beyond equities.