"Design a stock exchange" is the question where the usual advice reverses. In most designs you scale out and accept some staleness. Here a single order must be matched against the book in a strict, agreed order, the same order must produce the same trades every time, and latency is measured in microseconds to milliseconds, not hundreds of milliseconds.
The interviewer wants to see whether you can reason about fairness and determinism. If two orders arrive at the same price, the one that arrived first must fill first, and everyone, including your standby after a crash, must agree which that was. The design that follows from this is surprisingly small: a sequencer that stamps every order with a number, a matching engine that processes the numbered stream one order at a time, and a log that makes the whole thing recoverable and replicable.
This answer scopes to one venue matching orders. Clearing and settlement, regulation and surveillance are out of scope, and you should not describe specific rules. Background on the log is in message queues and on splitting by symbol in data partitioning. A neighboring problem where the winner changes with every accepted offer is Design an Online Auction, and the money side of a trade is Design a Digital Wallet.
Clarify the requirements
Functional requirements:
- Traders place limit orders (buy or sell, quantity, price) and market orders, and can cancel them.
- The exchange matches buy and sell orders and reports trades back to the participants.
- Participants see the order book and trades through a market data feed.
- Orders are checked before entering the book (for example, enough funds or position).
- Every order and trade is recorded permanently.
Out of scope, said aloud: clearing and settlement, options and complex order types, auctions at the open and close, regulatory reporting, and the broker's front end.
Non-functional requirements: these decide the design.
- Strict, fair ordering. Orders at the same price fill by arrival order (price-time priority). The arrival order is a decision the system makes once, and records.
- Determinism. The same ordered input always produces the same trades, which allows replay, audit and replicas.
- Low latency, predictably. Consistent latency matters more than average latency, so avoid anything with unpredictable pauses on the hot path.
- No lost or duplicated orders and no wrong trades. If correctness is in doubt, halt trading in that symbol, because a halt is recoverable and a wrong trade is not.
- High availability through fast failover, with no loss of acknowledged orders.
Estimate the scale
Assume 3,000 symbols, 1 million active traders placing 50 orders a day each (including cancels), so 50 million orders a day.
Average rate: 50M ÷ 86,400 ≈ 580 orders per second. Trading is not uniform, so assume a peak 100× the average at the open or on news: about 58,000 per second across the exchange.
The hottest symbol: suppose one symbol gets 10% of the peak: 5,800 orders per second, say 6,000.
Matching cost: if an in-memory matcher handles one order in about 10 microseconds (an assumption, to be measured), one thread does 100,000 per second, well above 6,000. The matching engine for one symbol can be a single thread, and that is a feature.
Events: each order produces about 3 events (accepted, filled or partly filled, canceled), roughly 100 bytes each: 50M × 3 × 100 B = 15 GB a day, about 27 TB over five years.
Market data fan-out: a hot symbol changes at 6,000 updates a second. With 100,000 subscribers, sending every update to every subscriber is 600 million messages a second, which is not feasible. Conflate: send the book snapshot at most every 100 ms, so 10 updates a second × 100,000 = 1 million messages a second, spread across many edge servers.
"The matching itself is not a throughput problem: one thread per symbol has plenty of headroom. The hard parts are agreeing on one order of events, surviving a crash without losing or reordering any, and telling 100,000 subscribers what happened without melting the network."
Try the numbers in the capacity estimator, where size is the events stored per order.
API and data model
POST /v1/orders { clientOrderId, symbol, side, type, quantity, price? }
-> { orderId, status: accepted | rejected }
DELETE /v1/orders/{orderId}
GET /v1/orders/{orderId}
WS /v1/stream -> executions for my orders; market data subscriptionssequenced input: { seq (per symbol), receivedAt, clientOrderId, action: new|cancel, ... }
order book (in memory, per symbol):
bids: price levels, highest first, each a FIFO queue of orders
asks: price levels, lowest first, each a FIFO queue of orders
index: orderId -> position in its queue (for O(1) cancel)
trades (durable): { tradeId, symbol, seq, price, quantity, buyOrderId, sellOrderId }The order book is a data structure, not a table. Each side is a sorted set of price levels, and each level is a first-in-first-out queue. A new buy that crosses the best ask matches against the front of that queue. The index from order id to its queue position means a cancel does not search. The clientOrderId makes a retried order a no-op: effectively once.
High-level design
The slice worth running is the order path: a gateway, an order service that validates and risk-checks, a sequenced log partitioned by symbol, a matching engine that consumes it and the trade store.
- Clients reach the order gateway service through an API gateway that authenticates participants.
- The order service appends orders to a log partitioned by symbol, and the matching engine reads each partition in order and records trades.
Describe this diagram
Components
- clients (Client)
- gateway (API gateway)
- order gateway (Service)
- sequencer log (Kafka)
- matching engine (Service)
- trade store (PostgreSQL)
Connections
- clients sends to gateway
- gateway sends to order gateway
- order gateway sends to sequencer log
- sequencer log sends to matching engine
- matching engine sends to trade store
Run it, then try raising the load and watch the log and the matching engine. Note that the simulator uses a general partitioned log to stand in for the sequencer. A production exchange would use a purpose-built, far lower-latency log.
The write path: the gateway authenticates the participant and the order service checks the order against pre-trade risk limits. It then appends the order to the sequenced log for its symbol, which assigns the next sequence number and replicates the entry. Only after the entry is durable is the order acknowledged as accepted.
The matching path: the matching engine for that symbol reads the log in sequence order, applies each order to the in-memory book, emits fills and writes them to an outbound log. A trade-store writer consumes that and persists trades, and a market data publisher consumes it and fans out.
The interesting problem: one agreed order, deterministically
Two buyers place orders at the same price within a microsecond of each other. Whoever is first gets filled first. Who is first?
Approach A: a database table with row locks
Insert orders into an orders table and match with queries under SELECT FOR UPDATE.
Good: familiar, durable, and correct for slow markets.
Bad: every order is several disk-backed operations with lock waits, so latency is in milliseconds and unpredictable. Locks do not define a fair order, only a safe one, and the ordering still depends on which transaction wins a lock.
Approach B: a multi-threaded matcher with locks per price level
Many threads match orders at once, locking the price levels they touch.
Good: uses all the cores, which looks like better throughput.
Bad: the results depend on thread scheduling, so the same inputs can produce different trades on different runs. Lock contention at the top of the book, where all the action is, wastes the cores anyway. Replay and replicas cannot reproduce it.
Approach C: a sequencer and a single-threaded matcher per symbol
All orders for a symbol go through one sequencer, which assigns a strictly increasing sequence number and writes the order to a replicated log. One matching engine thread per symbol reads that log in order and applies each order to its in-memory book. Different symbols are independent partitions that run in parallel on different cores or machines.
Good: the sequence number is the priority, so there is no ambiguity about who was first. The matcher is deterministic: the same log gives the same book and the same trades, so a standby that replays the log arrives at exactly the same state. No locks, no contention, and predictable latency.
Bad: a symbol's throughput is bounded by one thread, which is plenty here, and the sequencer is a critical component that must be replicated and fast.
The recommended answer is C. The principle to state is state machine replication: if a deterministic program consumes an agreed, ordered log, any number of copies stay identical, and the log is the source of truth. This is also why parallelism comes from partitioning by symbol, never from threads inside a book.
Diagram, as text
- Orders leads to Pre-trade risk check
- Pre-trade risk check leads to Sequencer: assign seq per symbol
- Sequencer: assign seq per symbol leads to Replicated log
- Replicated log leads to Matching engine: one thread per symbol
- Replicated log leads to Standby engine replays the same log
- Matching engine: one thread per symbol leads to Trades and book updates
- Trades and book updates leads to Trade store
- Trades and book updates leads to Market data publisher
The second decision: durability, failover and market data
When is an order accepted? Acknowledge only after the log entry is replicated to enough nodes to survive a machine failure. That adds latency (a network round trip to the replicas) and is the price of never losing an acknowledged order. Say that the alternative, acknowledging before replication, is faster and can lose orders on a crash, which an exchange cannot allow.
Failover. A hot standby engine consumes the same log and holds an identical book. If the primary fails, the standby takes over from its last applied sequence number, with a short pause for detection. Fence the old primary (an epoch number on the log writer) so a paused primary cannot publish trades after the switch. A consensus protocol such as Raft is the textbook way to replicate and elect the log leader. Where correctness is in doubt, halt the symbol and restart from the log. A visible halt is acceptable, and silently diverging copies are not.
Snapshots. Replaying the whole day's log on restart is slow, so periodically snapshot the book with its sequence number, then recover by loading the snapshot and replaying from there.
Pre-trade risk. Checking a participant's limits or funds before sequencing prevents orders that should never reach the book. Do it before the sequencer to keep the matching path fast, and keep the check's data local (an in-memory limit per participant) so it does not call a database. Funds that back the order are reserved at that moment, and trades settle against them later.
Market data. The matcher emits events: book changes and trades. A publisher turns them into two products: a feed of incremental updates with sequence numbers, so a subscriber detects a gap and requests a snapshot, and snapshots for new subscribers. Conflate for slower subscribers (every 100 ms) and give the fastest consumers a separate path. Fan-out is handled by a tier of edge servers, so the matching engine only ever sends to the publisher.
Bottlenecks and failures
A hot symbol. One thread handles 100,000 orders a second by our assumption, so a symbol at 6,000 is comfortable. If a symbol ever outgrows a thread, optimize the book's data structures (arrays by price tick, preallocated objects), not the threading model.
Garbage collection pauses and other jitter. Latency spikes break fairness and the latency target. Use a runtime and memory discipline that avoids pauses on the hot path, such as preallocation, pinned cores and no allocation per order.
The sequencer fails. Replicate it, and elect a new leader from the log's last committed entry. Orders not yet acknowledged are retried by clients with their clientOrderId, so a retry finds the earlier result.
Replay differs from live. If a standby ever produces different trades from the same log, there is a non-deterministic bug, such as iteration order over a hash map or a read of the wall clock. Compare trade hashes between primary and standby continuously and halt on a mismatch.
A slow market data subscriber. It must not slow the exchange. Drop or conflate for that subscriber, and disconnect it if it falls behind.
Cancel storms. At the open, many cancels and replaces arrive. They are cheap (an index lookup) but still go through the sequencer, so the log must handle the combined rate.
Security and abuse. Authenticate participants and rate-limit per connection. Reject malformed orders before the sequencer, and keep an audit trail of every input.
Trade-offs to name aloud
- One thread per symbol: determinism and no locks, in exchange for per-symbol throughput bounded by a single core.
- Acknowledge after replication: no lost orders, in exchange for a round trip of latency.
- Halt on doubt: a visible, recoverable outage, in exchange for never publishing a wrong trade.
- Conflated market data: much less fan-out, in exchange for slower subscribers seeing coarser updates.
What interviewers listen for
- A working answer: an order book with price levels and queues, price-time priority matching, a trade store and a feed for market data.
- A strong answer: serializes orders per symbol with a sequencer, explains why a lock-based or multi-threaded matcher breaks determinism, partitions by symbol and acknowledges after the order is durable.
- A standout answer: frames it as state machine replication with a hot standby and fencing, snapshots and replay, checks for divergence, halts on doubt, and designs market data with sequence numbers and conflation.
Check your understanding
Common mistakes
Using a relational database as the matching engine. It is the right store for trades and history, and the wrong place to match at exchange latency.
Letting the wall clock decide priority. Clocks disagree. A sequence number settles ties for everyone.
Multi-threading inside one order book. It trades determinism for a small gain at best. Scale by partitioning symbols.
Acknowledging before the order is durable. A crash then loses orders the participant believes were accepted.
Broadcasting every update to every subscriber. The arithmetic fails at scale. Conflate and fan out from edge servers.
Assuming a failover is invisible. Without fencing and divergence checks, two engines can both believe they are primary. Say how you prevent it and when you halt.
Practice
After a failover, the new primary's trades for one symbol differ from the old primary's in the last few seconds. What could cause this, and what do you do?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Both engines read the same log, so ask what else they read, and how you would find the first difference.
Show a strong answer
What it means. A deterministic engine with the same input log must produce the same output, so a difference signals either non-determinism in the engine, a difference in the input log (an entry one saw and the other did not), or the old primary acting after it should have been fenced.
Find the first difference. Compare the output logs by sequence number to find the first diverging entry, then replay the input from the last common snapshot in a test environment with the same binary and look for what changed: a hash map iteration order, a read of the clock or a random number, a version mismatch between the two binaries.
Contain it. Halt the symbol. Decide which trades stand using the log as the record, and notify the affected participants. Do not let the exchange continue with two versions of the truth.
Prevent it. Run primary and standby continuously with periodic state hashes, alert on a mismatch, and add replay tests that run production logs through the engine in CI.
The pattern worth keeping: a replicated state machine is only as safe as its determinism, so continuously verify that copies agree and stop when they do not.
A market data subscriber complains that it sometimes sees a trade without the book change that caused it. How should the feed be designed so clients can detect and repair this?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about sequence numbers, gaps and snapshots.
Show a strong answer
Number every message. Each event on the feed carries the symbol's sequence number from the matching log. A subscriber that sees 1041 followed by 1043 knows it missed 1042.
Provide a repair path. On a gap, the subscriber requests a snapshot of the book at a known sequence number, then applies buffered incremental updates after that number and discards those before. A retransmission service for recent ranges is an alternative for small gaps.
Do not reorder silently. The publisher sends events in sequence order per symbol, and a book change and the trade it caused share a sequence or arrive adjacent in order.
The pattern worth keeping: when delivery is unreliable, make the stream self-describing with sequence numbers, so any consumer can notice a gap and recover without help.
Key takeaways
- Fairness and determinism come first: the sequence number is the priority, not the clock.
- A sequencer plus a single-threaded matcher per symbol gives a deterministic, lock-free core.
- Scale by partitioning symbols, not by threading a single book.
- The log is the source of truth: replicate it, acknowledge after it is durable, and recover by snapshot plus replay.
- Fail over with fencing, and halt on doubt: a visible halt beats a wrong trade.
- Market data needs sequence numbers and conflation, so subscribers can repair gaps and the fan-out stays affordable.
Further reading
- Martin Fowler, "The LMAX Architecture" (2011): a single-threaded, event-sourced, in-memory design for a trading platform.
- Fred B. Schneider, "Implementing Fault-Tolerant Services Using the State Machine Approach: A Tutorial", ACM Computing Surveys (1990).
- Diego Ongaro and John Ousterhout, "In Search of an Understandable Consensus Algorithm", USENIX ATC (2014): the Raft paper.