Systemsfor Aravinda
0 / 78 core
Week 11 · Case studiesAdvanced

Design a stock exchange

2 hours · optional track

Read first: Consistency models, Consensus and Raft

In one sitting

One process owns the book for a symbol and assigns a sequence to every accept, cancel, and trade. Price-time priority is that sequence plus the price. You replicate the log and fan the events out. You do not run a second matcher, and you do not let a distributed log make the matching decision.

A new-grad loop rarely needs a matching engine. This page is the optional advanced track, and it is still worth an evening, because the follow-ups are about what you refuse to distribute and how a standby is fenced. One sequencer for a hot symbol is the same shape as one row for the last hotel room, with a public order of events and a harsher definition of “first.” The matcher itself is the part to be able to redraw. Co-location is why the page is advanced: a seat in the same building changes when an order arrives, and it does not create a second book. That explanation comes after the book is clear.

Requirements

The user is a trading participant submitting orders, and a second user is anyone consuming the public market data. You are designing the matching venue for listed symbols, not a brokerage screen.

Functional requirements:

  • Accept a limit order: symbol, side, price, quantity, and a client order id.
  • Cancel an order that is still resting.
  • Match crossing orders into trades.
  • Publish one sequence of accepts, cancels, and trades that every participant can replay.

Non-goals:

  • Options, spreads, and auctions. Name them as out of scope so “match a buy and a sell” stays the problem.
  • Margin, credit checks, and the clearing house. You emit a trade to a clearer. You do not build the risk system in the same loop.
  • A retail app, account funding, or tax lots.
  • Cross-symbol atomic trades. If two symbols must move together, that is a different product and it wants a different discussion. Here, symbols are independent.

The fairness rule, said before any box is drawn: the best price trades first, and at the same price the earlier order trades first. “Earlier” means the sequence the matcher assigned, not a timestamp on the sender’s machine.

Estimation

Every number in this section is an interview assumption. It is not a published figure from any venue.

  • 1,200 listed symbols.
  • The busiest symbol averages 2,000 orders per second across the day and peaks at 25,000. Both rates are assumptions about a busy open, not a measurement. The peak is 25,000 / 2,000 = 12.5× the average.
  • An inbound order message is 200 bytes.
  • One order in four produces a public event (a trade or a visible book change). A public event is 100 bytes.
  • 300 subscribers want the public stream for that symbol.
busy symbol, day     2,000 * 86,400 = 172,800,000 orders
shortcut             2,000 * 100,000 = 200,000,000

peak ingress         25,000 * 200 B = 5 MB/s
average ingress      2,000 * 200 B = 400 KB/s

public events        25,000 / 4 = 6,250 per second at peak
log append           6,250 * 100 B ≈ 0.6 MB/s once

unicast to 300       300 * 0.6 MB/s ≈ 180 MB/s
sends                6,250 * 300 = 1,875,000 sends/s

A day is 86,400 seconds. The 100,000-second shortcut overshoots the daily count (200 million versus 173 million) and is still the right first move. Five megabytes a second into the matcher is nothing for a NIC. The book is an in-memory structure. The number that hurts is 1.9 million sends a second if the matcher itself talks to every subscriber.

Latency numbers belong on the ack, not on a made-up match time. A main-memory reference is about 100 ns. A same-datacenter round trip is about 0.5 ms, which is 5,000 of those references. Comparing two prices is lost in the noise. Waiting for a local standby to take the log is the 0.5 ms you can defend without inventing a benchmark. A cross-country round trip is tens of milliseconds and does not belong on the match ack.

High-level design

Many order gateways accept connections and forward messages. They do not sort orders against each other and they do not match. For each symbol, one matcher process owns the book. It alone decides trades and it alone assigns the next sequence number. It appends each decision to a log. A hot standby replays that log and does not accept orders. A fanout tier reads the log and serves market data. Other symbols are other matcher processes, on other machines if you need the cores.

flowchart LR
  gw[Order gateway]
  matcher[Symbol matcher]
  book[In memory book]
  seqlog[Sequence log]
  standby[Hot standby]
  fanout[Market data fanout]
  gw --> matcher
  matcher --> book
  matcher --> seqlog
  seqlog --> standby
  seqlog --> fanout

The decision is single-threaded. The bytes do not have to be. A helper can write the network fanout from the log. A helper cannot run a second matching loop “to keep up.” Two loops are two exchanges.

Deep dive

One book, price then time

Keep two sides. Bids are buys, ordered by price descending. Asks are sells, ordered by price ascending. Each price level is a queue in arrival order. The matcher is a loop over one symbol’s orders.

A new buy limit arrives. While its limit is at or above the best ask and it still has quantity, it trades with the order at the front of that ask queue. Assumption, and you should say it: the trade price is the resting order’s price. The incoming order is the one that crossed the spread, so the resting price is the price both sides already accepted. When the incoming order can no longer cross, what remains of it rests in its own price queue.

A worked book:

Order Side Price Qty Arrival
A sell 101 10 1
B sell 100 15 2
C sell 101 8 3

An incoming buy for 20 at 101 does this:

  1. The best ask is B at 100, which is a better price than A even though A arrived first. Trade 15 at 100. The buy has 5 left. B is done.
  2. The next ask level is 101. A is in front of C because A arrived earlier. Trade 5 at 101. The buy is done. A has 5 left.
  3. C does not trade.

The book that remains is A with 5 at 101, then C with 8 at 101. Nothing rests from the buy. A later sell does not jump A just because the sender owns faster hardware. Time priority is the queue inside the price level. Price priority is which queue you look at first.

A market order, if you allow one, is a limit that walks the book until it fills or hits a protection price you set. Say the protection price exists so a thin book does not trade at a nonsense level. Then leave it. The interview is the limit book.

Cancels name the matcher-assigned order id, or the client order id, and they remove that order from its queue if it is still resting. A cancel of an order that already traded is a no-op, not an error that untrades.

The sequence is the clock

Clocks on the gateways are a poor definition of “first.” Two gateways can receive two orders, and the one with the lagging clock can still have received its order later. The matcher assigns a monotonic sequence when it accepts the event. That sequence is the order. Equal timestamps do not need a tie-break story if you never use the timestamp as the order.

Every outbound event carries the sequence: order accepted, cancel accepted, trade. A consumer who sees 1000 and then 1002 has a hole at 1001. It must not apply 1002 as a delta on top of 1000. The book would skip a cancel or a trade and stay wrong until someone noticed. Consistency models have a name for the property you want on this stream: a consistent prefix. Recovery is “retransmit from 1001” or “give me a snapshot taken at sequence S and I will apply S+1 onward.” Publish a full book snapshot every few seconds, labeled with its sequence, so a slow consumer can jump instead of replaying the day.

The client order id makes a retry safe. If the gateway times out, it resends the same client order id. The matcher returns the original accept if that id is already in the log. It does not rest a second order. That is idempotency on the ingress, and it is load-bearing once you ack only after the standby has the record and the client cannot tell a lost ack from a lost order.

What you do not distribute

Do not distribute the matching decision for one symbol. Do not distribute sequence assignment. Do not keep two live copies of the book that both accept orders. Do not hand the log to a group of consumers and let “whoever reads first” trade. A log is the record of decisions. Consumers who match from it are a second matcher, and a rebalance would move the book mid-trade.

You do distribute the work that is not the decision:

  • Gateways, as many as the connections require. They forward. They do not rank.
  • The fanout of a sequence that has already been assigned.
  • Other symbols. The AAPL book and the MSFT book share nothing that has to be locked together. Scale by adding symbols to machines, not by splitting one symbol across threads.
  • A standby that has the log and will not become a matcher until it holds the lease.

Durability is the log, not the client’s hope. Update the in-memory book and append the decision to the local log and the standby. Ack the client only after the standby has the record. Publish market data from the log, so a trade cannot reach the world and then fail to be recoverable. If the process dies after it has matched in memory and before the append, the memory is gone and the standby does not have the trade. The client retries with the client order id. You must not have published that trade. Publishing ahead of the log is the durability bug.

The standby ack costs about one same-datacenter round trip, the 0.5 ms above. You pay it because an acked order is one you can rebuild. You do not wait for another region. Consensus on every order would put a quorum round trip on the match to elect a value the single matcher already owns. Raft is the wrong tool for the hot path and the right tool, or a lease with a fencing token, for the much rarer question of which process is allowed to be the matcher. Two majorities cannot both be the matcher if promotion is a real lease. Two processes that both append because the old one woke up are a split brain, and they will trade the same resting sell against two buys.

Pipeline the I/O. Keep one thread that pulls the next inbound order, walks the book, and assigns the sequence. Another thread can ship bytes the log has already committed. The invariant is one decider. It is not “one core does the sockets too” as a point of pride.

Tradeoffs

Choice What you gain What you spend
One matcher per symbol Price-time is a queue you can point at A hot symbol is one core’s decision rate, and you shed work around it
Several matcher threads per symbol A diagram that looks scaled out Two notions of “first,” locks around the book, and trades that depend on scheduling
Ack after a local standby has the log A crash does not lose an acked order About 0.5 ms, and a standby that can stall ingress
Ack before the log is durable A faster ack A client believes an order that failover cannot rebuild
Fanout tier over unicast Gaps are just a stream you can resume Bandwidth grows with subscribers, delivery is staggered
Multicast plus a recovery path One send, closer to simultaneous delivery You build gap detection, because UDP will not
Match by consuming a shared log Familiar machinery Consumers become matchers and rebalance becomes a correctness bug

Failure modes

Dependency down. The clearer is down. Stop accepting new orders for the affected symbol and keep the sequence honest, rather than trading into a void you cannot record. Gateways are down for some participants. The matcher does not wait for them. Their orders are simply not here yet. The standby is down. If your rule is “ack after standby,” ingress stalls or you refuse orders. That is the trade you already named. Do not quietly switch to ack-from-memory and hope.

Retry storm. Clients time out at 0.5 ms plus a blip and resend. The client order id turns the resend into a lookup. Without it, a single buy rests twice and can trade twice. Bound the gateway accept queue. When the matcher is behind, reject at the gateway with a clear “try again” instead of buffering without a limit. An unbounded gateway queue is how a 100 ms stall becomes a memory leak and then a flood of stale orders.

Hot partition. The busy symbol is the hot key, and you may not shard it. Shed everything that is not the decision: historical charts, risk reports, ad-hoc queries. Those read the snapshot, not the match thread. If one symbol’s peak of 25,000 orders/s is beyond what the loop can do on the hardware you have, the answer is a simpler book and less work per order, or a product limit. It is not a second matcher.

Consistency. Split brain is the consistency failure. The old matcher pauses, the standby takes the lease and a new fencing token, the old matcher resumes and keeps assigning sequences. You now have two books. The old process has to notice a revoked lease, or its append has to be rejected because the fencing token is stale. Until you can say that sentence, you do not have failover. You have a coin flip.

Durability. A trade published from memory before the append is the durability failure. Crash, promote the standby, and the public tape contains a trade the rebuilt book never had. Publish from the log. Related and milder: an async standby loses the tail. Clients must reconcile by client order id, and you must have told them the ack did not mean “on the standby.” Pick the sync local ack unless you have a measured reason not to.

In the interview

Open by saying this is usually past a new-grad loop, then spend the five minutes on one symbol. One book, price queues, arrival order inside a price, one sequence, a standby that is not a writer. The number is an assumed peak, 25,000 orders/s and 5 MB/s, against a fanout that becomes 180 MB/s if you unicast from the matcher. The bottleneck is the single decision plus the fanout, not disk. The tradeoff is the 0.5 ms standby ack.

Skip multicast, rack maps, and any binary protocol by its trade name unless the interviewer asks. Skip a lecture on Paxos. If they ask why the page is advanced, the answer is co-location and multicast: wire length and gap-tolerant fanout, not a more complicated book.

The question that usually follows is “why not match in the consumers of a log?” Because the consumer would decide, and two consumers would decide differently. The log stores the sequence after the matcher creates it. The next question is failover. Walk the lease, the fencing token, and the client order id.

Check yourself

Two threads match the same symbol so the busy open can use two cores. What invariant did you lose?

A single arrival order. Each thread has its own idea of which order was first, or they take a lock and you are back to one thread plus contention. An order that walks several price levels has to see one book. Two books will trade the same resting sell twice or skip a price level. Scale by giving other symbols their own matcher.

In the book where A sells 10 at 101, B sells 15 at 100, and C sells 8 at 101, a buy of 20 at 101 arrives. Who trades, at what price, and what is left?

B trades first because 100 is a better price for the buyer: 15 shares at 100. A is ahead of C at 101, so A trades 5 at 101. The buy is filled. A still rests 5 at 101, and C still rests 8 at 101. The trade price is the resting order’s price, which was the assumption.

Two gateways timestamp orders with their own clocks. Why is the matcher's sequence the arrival order instead?

Clocks disagree, and a later receipt can carry an earlier timestamp. The matcher is the single place both orders actually meet, so the sequence it assigns is the definition of earlier. Downstream systems detect a missing sequence and refuse to apply a later event on top of a hole.

Which pieces can be many processes, and which piece stays one per symbol?

Gateways, fanout readers, and matchers for other symbols can be many. The standby can be a second process only while it is not accepting orders. The live book, the matching decision, and the sequence assignment for one symbol stay one. A log consumer that matches is a second decider.

The matcher acks a trade, publishes it, and crashes before the append. The standby is promoted. What does the public see?

A trade that the rebuilt book cannot reproduce. That is the bug. Append to the log the standby will replay, then ack, then publish from that log. If you die before the append, the client retries with the same client order id and no public trade has to be undone.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes; Jeff Dean, Numbers Everyone Should Know.