System design interview: design a stock exchange
An electronic exchange accepts buy and sell orders, matches them by price and then by arrival time, and publishes every trade and book change to the market. The design centres on a deterministic matching engine: orders pass risk checks, a sequencer gives each one a position in a single replicated log, and a single-threaded engine per group of symbols replays that log in memory, which makes it fast, fair and recoverable.
By Evin JohnPublished 8 min read
1. Clarify the requirements
An exchange is an unusual prompt: latency and fairness matter more than scale, and the interviewer will care about correctness under failure. Pin the scope down.
- Functional: brokers submit limit orders (buy 100 shares at 52.10 or better) and cancel them; the exchange matches orders and reports fills to both sides; everyone receives market data (best bid and offer, book depth, trades).
- Non-functional: very low and, above all, predictable latency from order in to acknowledgement out; strict fairness (no participant can jump the queue); no accepted order or trade is ever lost; high availability during trading hours.
- Out of scope unless asked: clearing and settlement, the brokers' own apps, opening and closing auctions (mention them), complex order types beyond limit, market and cancel.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Order messages | 100 million a day (new orders, cancels, replaces) over a 6.5-hour session | about 4,300 a second on average |
| Bursts | the open, the close and news spikes run far above average | design for about 150,000 messages a second |
| Symbols | about 8,000 listed instruments | busiest symbol at, say, 5% of traffic: about 7,500 messages a second at peak |
| Event log | about 3 events of about 120 bytes per order message | about 36 GB a day: small |
| Order book memory | a few million resting orders at about 100 bytes each | well under 1 GB: fits in one server's memory |
Nothing here needs a large cluster. The challenge is doing each step in microseconds, the same way every time, and never losing state.
3. Define the interface
NewOrder { client_order_id, account, symbol, side, type: LIMIT|MARKET, price_ticks, qty, time_in_force }
Cancel { client_order_id, orig_client_order_id }
-> Ack { client_order_id, exchange_order_id, seq }
-> Reject { client_order_id, reason }
-> Fill { exchange_order_id, price_ticks, qty, leaves_qty, trade_id }
Market data (one-to-many feed): BookUpdate { symbol, side, price_ticks, total_qty }, Trade { symbol, price_ticks, qty }Prices travel as integer ticks (52.10 with a 0.01 tick becomes 5210), never as floating point, so two equal prices always compare as equal.
4. Sketch the data model
| Structure | Contents | Why |
|---|---|---|
| Order book per symbol | Bids sorted high to low, asks low to high; at each price a FIFO queue of orders | Best price and time priority in constant or logarithmic time |
| Order index | exchange_order_id -> order | Cancels and replaces find the order directly |
| Sequenced event log | seq, input message, resulting events | Persisted and replicated before acknowledging; replaying it rebuilds every book |
| Account risk state | buying power, positions, open order totals | Pre-trade checks; lives with the risk service, not the engine |
5. Matching: price-time priority
An incoming buy order matches against the lowest asks as long as their price is at or below the buy price, oldest first at each level, and trades at the resting order's price. Whatever is left rests on the book. Sells mirror this. The sketch below is the logic only; a production engine uses arrays or linked lists per price level, not heaps with lazy deletes.
import heapq
from itertools import count
class OrderBook:
def __init__(self):
self.bids, self.asks = [], [] # heaps of (key, seq, order_id)
self.live = {} # order_id -> [side, price, qty]
self.seq = count()
def submit(self, oid, side, price, qty):
fills = []
book = self.asks if side == "buy" else self.bids
crosses = (lambda p: p <= price) if side == "buy" else (lambda p: p >= price)
while qty and book:
key, _, rid = book[0]
if rid not in self.live: # cancelled: drop lazily
heapq.heappop(book); continue
rprice = key if side == "buy" else -key
if not crosses(rprice):
break
rest = self.live[rid]
traded = min(qty, rest[2])
fills.append((rid, oid, rprice, traded)) # trade at the resting price
qty -= traded; rest[2] -= traded
if rest[2] == 0:
heapq.heappop(book); del self.live[rid]
if qty: # rest the remainder
self.live[oid] = [side, price, qty]
own = self.bids if side == "buy" else self.asks
heapq.heappush(own, (-price if side == "buy" else price, next(self.seq), oid))
return fills
def cancel(self, oid):
return self.live.pop(oid, None) is not None
b = OrderBook()
b.submit(1, "sell", 10100, 5); b.submit(2, "sell", 10000, 3)
b.submit(3, "buy", 10100, 6) # [(2, 3, 10000, 3), (1, 3, 10100, 3)]6. The architecture
- Participants
- Broker systems
- Entry
- Order gateways
- Pre-trade risk checks
- Core
- Sequencer and replicated input log
- Matching engine per symbol group
- Standby engine on the same log
- Output
- Output event log
- Execution reports to brokers
- Market data publisher
- Post-trade
- Trade store
- Clearing and reporting feeds
- CheckThe gateway validates the message; risk rejects orders beyond the account's limits or far outside the current price (a fat-finger band).
- SequenceThe sequencer assigns the next number and the log is replicated before anything downstream acts on it. This number is the fairness order.
- MatchThe engine for that symbol applies the order to its book, producing acks, fills and book updates, all tagged with the input sequence.
- PublishExecutions go back through the gateway; market data goes out on a one-to-many feed so every participant gets the same update at about the same time.
7. Deep dives
- Why single-threaded. Two threads touching one book need locks, and locks make latency unpredictable and order nondeterministic. One thread per symbol group, fed by an in-memory ring buffer, does each match in microseconds with no contention. Scale out by giving each engine a different set of symbols.
- Determinism and recovery. Given the same input log, the engine must produce the same output: no wall-clock reads, no random numbers, no iteration over unordered maps. Then a standby that replays the log has identical state and can take over, and a crashed engine can be rebuilt from a snapshot plus the log since it.
- Failover without double trades. The standby processes the same inputs but its outputs are suppressed. On failover it starts publishing from the next output sequence the primary did not publish; downstream consumers ignore sequence numbers they have already seen.
- Latency. Keep the hot path in one process per stage, avoid garbage collection pauses and system calls, pin threads to cores, and keep the engine close to the gateways. Very low-latency venues go further with kernel-bypass networking and co-location; mention them as options, not requirements.
- Market data fairness. Publish book updates on a feed that reaches everyone at once (multicast inside a data centre is a common choice), with sequence numbers so receivers detect gaps and request a retransmission or a snapshot.
- Halts and circuit breakers. If a price moves too far too fast, the engine stops matching that symbol and later reopens it with an auction. Model it as a state on the book, driven by sequenced control messages, so replay still works.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| Matching engine host fails | Symbols on it stop trading | Promote the standby, which already has identical state from the same log |
| Sequencer fails | No new orders accepted | Replicated log with a leader and followers; a follower becomes leader with no gap in sequence numbers |
| Market data receiver misses packets | Its view of the book is wrong | Sequence numbers, retransmission requests, periodic snapshots |
| Broker session drops | Its resting orders stay live | Optional cancel-on-disconnect per session |
| Runaway algorithm floods orders | Engine queue grows, others slowed | Per-session message rate limits and kill switches in the gateway and risk layer |
9. Trade-offs to discuss
- Persist before or after matching. Writing the input to the replicated log before matching costs latency but means a crash loses nothing that was acknowledged. Matching first and logging later is faster and unsafe; for an exchange, log first.
- More symbols per engine or fewer. Fewer symbols per engine spreads load but needs more machines and standby pairs; busy symbols may each get their own engine.
- Strong consistency on the core, eventual elsewhere. The book and sequence must be exact; reporting, dashboards and history can lag. That split is the consistency and CAP trade made explicit. Payments-style idempotency around fills is covered in design a payment system.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Two brokers send buy orders at the same price a microsecond apart. Who gets filled first?
- Candidate
- Whoever the sequencer stamped first. Priority comes from the sequence number, not from gateway arrival or clock time, so every engine replica and every replay agrees.
- Interviewer
- And if the engine crashes right after a fill?
- Candidate
- The order was in the replicated log before matching. The standby has processed the same input, so its book already reflects that fill. It resumes publishing from the next unsent output number, and receivers drop anything they have already seen.
- Explain price-time priority with a two-line example before drawing boxes.
- Make determinism the reason for single-threaded matching and for the log.
- Keep everything that is not matching off the hot path.
Practicing this design with Natively
Exchange questions tend to come up in trading and infrastructure loops, where interviewers press hard on failure handling. Practise answering out loud on a mock call; Natively transcribes the exchange and can suggest a talking point when you blank on recovery or fairness. You can also ask it to sketch the sequencer and engine layout as a diagram, or screenshot a matching example you wrote and have it checked.
Questions people ask
How does a stock exchange matching engine work?
It keeps an order book per symbol with bids sorted from highest and asks from lowest, each price level holding orders in arrival order. An incoming order trades against the best opposite prices while they cross its limit, oldest first, at the resting order's price, and any remainder rests on the book.
Why are matching engines single-threaded?
One thread per group of symbols needs no locks, so latency stays low and predictable, and the same input always produces the same output. That determinism lets a standby replay the same log and hold identical state. Throughput scales by spreading symbols across engines.
What does the sequencer do in an exchange?
It gives every accepted order a single increasing sequence number and writes it to a replicated log before matching. That number defines time priority and fairness, and replaying the log rebuilds the order books after a failure.
How does an exchange avoid losing trades when a server fails?
Inputs are persisted and replicated before they are matched, and a standby engine processes the same log with its output suppressed. On failover it publishes from the next output sequence number, and downstream systems drop numbers they already received.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
