The whole course ▾

System Design · Mock interview 17 of 20

Design a stock exchange

Updated 22 Oct 2026 · By Akshay, software engineer, India · 9 min read

Design a stock exchange.

Try it first

Before you read the interview, answer the question yourself. Give yourself 10 minutes: say your design out loud, or sketch it on paper. What would you ask? Which numbers matter? Which boxes, and what's the hard part? Then read on, and score yourself with the feedback at the end.

The video for this mock interview is coming soon.

New System Design videos go up at 6 pm. Subscribe on YouTube so you don't miss it.

Got a doubt? Ask in the comments under the video.Subscribe

Requirements

Requirements
Clarifying questions
->
Who connects? -> Brokers, not the public
->
Order types? -> Limit, market, cancel
->
Scale? -> 5,000 stocks, ~500,000 orders/s
->
Speed? -> Microseconds inside
Functional requirements
Place and cancel orders
Match buyers and sellers fairly
Report fills to the brokers
Publish prices and trades to all
Non-functional requirements
->
Strict fairness: price, then time
->
Same input, same result: deterministic
->
Never lose an acknowledged order
->
Market data to everyone at once
Out of scope
Clearing and settlement
Customer accounts: brokers' job
Market surveillance
interviewer
Hi. Today's a fun one. Ready?
candidate
Ready. I'll draw as I go.
interviewer
Design a stock exchange: the system that matches buyers and sellers of shares. Not a trading app, but the exchange itself, which brokers connect to.
candidate
Okay. I'd like to pin down what fair means here, and how fast is fast, because I think those two answers shape everything. A few questions?
interviewer
Go ahead.
candidate
Who connects?
interviewer
Brokers and big trading firms, through dedicated connections. The public goes through their brokers.
candidate
Which order types?
interviewer
Limit orders, which name a price, market orders, which take the best price available, and cancels.
candidate
What scale?
interviewer
About five thousand stocks, and around five hundred thousand orders a second at peak.
candidate
And how fast must matching be?
interviewer
Microseconds, inside the exchange.
candidate
That's a thousand times faster than a normal web app.
candidate
So, what it does. Place and cancel orders. Match buyers with sellers, by clear, fair rules. Report every trade, every fill, back to the brokers involved. And publish prices and trades to everyone who subscribes.
candidate
And how well. Strict fairness: the best price first, and at the same price, whoever came first. Deterministic: the same orders, in the same sequence, always produce exactly the same trades, so any result can be checked and replayed. Never lose an order once it's acknowledged. And market data reaches every subscriber at once.
interviewer
Why at once?
candidate
Seeing a price a millisecond earlier is worth real money.
candidate
I'll leave out clearing and settlement, customer accounts, which brokers manage, and market surveillance. Does that match what you had in mind?
interviewer
Yes. Focus on matching.

Estimation

Estimation
Back of the envelope
500,000 orders/s × ~100 bytes = 50 MB/s
5,000 stocks; busiest: tens of thousands/s
One order book: thousands of price levels
Fits easily in one machine's memory
WHAT THE NUMBERS DECIDE
Thedataissmall;thehardpart
isorder,determinismand
microseconds:onesingle-threaded
engineperorderbook,inmemory.
candidate
Let me size it. I suspect it's smaller than it sounds.
interviewer
How much data flows through this?
candidate
The orders first, then one order book.
candidate
Five hundred thousand orders a second, at about a hundred bytes each, is fifty megabytes a second. Modest. Across five thousand stocks, the busiest get tens of thousands of orders a second each. And one stock's order book, all its waiting buy and sell orders, holds maybe thousands of price levels, and fits easily in one machine's memory.
candidate
So the data is small. The hard part is order, determinism and speed. Microseconds rule out databases and network round trips in the matching path. And strict ordering is easiest when one thread, in memory, handles each order book, one order at a time.
interviewer
Interesting. Most people want to scale out.
candidate
Here I'd scale out by stock, not within one.

API and data

API and data
Buy side
highest price
first
Sell side
lowest price
first
One price
level
orders in arrival
order
Journal
every order, in
sequence
at ₹101
at ₹102
rebuilds
Messages
1
New order: stock, side, price,
quantity
2
Cancel: by order ID
3
<- acknowledged, rejected, filled
4
Market data: a separate
broadcast feed
candidate
Next, how brokers talk to us, and the order book.
interviewer
How do brokers talk to the exchange?
candidate
Not with JSON over HTTP. Every microsecond counts.
candidate
Brokers hold long-lived connections, using a compact binary protocol, or the industry standard called FIX. They send a new order: the stock, buy or sell, the price, the quantity, and their own ID for it. Or a cancel, by order ID. The exchange answers each with acknowledged, or rejected with a reason, and later sends fill reports as trades happen. Market data comes separately, on a broadcast feed.
interviewer
Why fixed-shape messages?
candidate
The engine can read every field at a known position, in nanoseconds, without parsing anything.
candidate
Each stock has an order book, in memory, with two sides. The buy side, sorted from the highest price down. The sell side, sorted from the lowest price up. At each price, one price level holds its orders in a queue, in the order they arrived. And underneath it all, a journal: every order, in sequence, written to disk.
interviewer
Why the journal?
candidate
The book can always be rebuilt by replaying it.

High-level design

High-level design
Broker
Order
gateway
checks and
risk limits
Sequencer
stamps a
sequence
number
Journal
replicated
Matching
engine
one thread
per book
buy 100 @
₹101
1
2
write first
3
seq 9001
4
Fill
reports
Market
data
feed
multicast
Subscribers
every
broker,
every
screen
trade: 100
@ ₹101
5
filled
6
book
changed
7
same moment
EVENT SOURCING
Thejournalofsequenced
ordersisthetruth;the
orderbookisjustits
result,rebuiltbyreplay.
TWO QUESTIONS
Whyisonethreadper
bookfairandfast?And
howdoesacrashlose
nothing?
interviewer
Okay. Follow one order through.
interviewer
Walk me through one order, from the broker to a trade.
candidate
It's a pipeline, where each stage does one thing, very fast.
candidate
A broker sends: buy a hundred shares at a hundred and one rupees. The order gateway checks it: a valid stock, a sensible price, and within that broker's risk limits. Then the sequencer stamps it with the next sequence number, nine thousand and one, and writes it to the journal, replicated, before anything else happens. Only then does it reach the matching engine, one thread per order book, which processes orders strictly in sequence.
interviewer
Doesn't writing the journal first slow every order down?
candidate
A sequential write to a nearby machine takes a few microseconds. That's the price of never losing an order.
candidate
The engine matches the order against the book, and produces events: a trade, a hundred shares at a hundred and one. Fill reports go back to both brokers. And every change to the book goes to the market data feed, which broadcasts it to all subscribers at the same moment, using network multicast: one packet, copied by the network to everyone at once.
interviewer
So nobody gets the price first.
candidate
Exactly.
candidate
And the idea underneath is event sourcing. The truth isn't the order book; it's the journal, the sequenced list of every order. Because the engine is deterministic, replaying the journal always rebuilds the same book and the same trades.
interviewer
So recovery, auditing and testing are all the same thing.
candidate
Yes. Replay.
interviewer
Two things I'd push on. Why is one thread per book both the fairest and the fastest? And when an engine crashes mid-trading, how is nothing lost?
candidate
Both answers come from the journal and the sequencer. Let me start with matching.

Deep dive: matching fairly

Deep dive: matching fairly
Price, then time
1
Best price first: highest buy, lowest sell
2
Same price: first come, first served
3
Buy 100 @ ₹101 meets: 60 @ ₹100, 80 @ ₹101
4
Fills 60 @ ₹100, then 40 @ ₹101
Many threads, with locks
Threads race for the same book
Lock waits cost microseconds
Order depends on scheduling luck
One thread per book
Orders handled strictly in sequence
No locks: millions of orders a second
Deterministic and replayable
interviewer
The rules first, then the threads.
interviewer
Exactly how does matching work, and why one thread?
candidate
The rule first, with an example.
candidate
The rule is price, then time. Best price first: the highest buyer, the lowest seller. At the same price, first come, first served. Say a buy order for a hundred shares, at up to a hundred and one, meets a book with sixty shares for sale at a hundred, and eighty at a hundred and one. It fills sixty at a hundred, then forty at a hundred and one, from whichever seller at that price arrived first. The other forty stay waiting.
candidate
Now, why one thread. Many threads updating one book would need locks, and each lock wait costs microseconds, while which order wins depends on the operating system's scheduling luck: unfair, and impossible to replay. One thread per book, purely in memory, handles orders strictly in sequence, with no locks at all. Designs like this have handled millions of orders a second on a single thread. And different stocks run on different threads and machines, so the exchange still scales out, stock by stock.
interviewer
Two orders for the same stock arrive at the same microsecond, through two different gateways. Who's first?
candidate
The sequencer decides, and its decision is the definition of first. Whatever order it stamps is what the engine sees, the journal records, and every replay reproduces. Exchanges also keep the network paths from every gateway equal, so no broker's position gives them an edge.
interviewer
Why not keep the order book in a database? It's durable and familiar.
candidate
A database write takes hundreds of microseconds, and the engine has a budget of a few microseconds per order. Durability comes from the journal instead: written once, in sequence, very quickly, and the book in memory can always be rebuilt from it.
interviewer
Good.

Deep dive: crashes and the market feed

Deep dive: crashes and the market feed
Never lose an order
1
Journal it before acknowledging
2
A standby engine reads the same journal
3
It rebuilds the identical book
4
The primary dies: it takes over
MARKET DATA, FAIRLY
Multicasttoeveryoneat
once;sequencenumbers
tospotgaps;snapshots
tocatchup.
High-level design
Broker
Order
gateway
checks and
risk limits
Sequencer
stamps a
sequence
number
Journal
replicated
Matching
engine
one thread
per book
buy 100 @
₹101
1
2
write first
3
seq 9001
4
Fill
reports
Market
data
feed
multicast
Subscribers
every
broker,
every
screen
trade: 100
@ ₹101
5
filled
6
book
changed
7
same moment
Standby
engine
same
journal,
same book
same
sequence
EVENT SOURCING
Thejournalofsequenced
ordersisthetruth;the
orderbookisjustits
result,rebuiltbyreplay.
TWO QUESTIONS
Whyisonethreadper
bookfairandfast?And
howdoesacrashlose
nothing?
interviewer
Now, failures, and the market feed.
interviewer
A matching engine crashes in the middle of trading. What's lost, and how quickly is trading back?
candidate
With the journal, the answer is clean.
candidate
An order is written to the journal, and copied to a second machine nearby, before acknowledging it to the broker, so an acknowledged order can't be lost. A standby engine reads the same journal, in the same sequence, as it's written. Because matching is deterministic, it builds an identical book, trade for trade. When the primary dies, the standby takes over, already up to date, within milliseconds.
candidate
So when the primary engine crashes, the standby engine, which has been replaying the same journal all along, is promoted. The sequencer sends new orders to it, and brokers see a pause of milliseconds. No order lost, and no trade done twice, because both engines made exactly the same decisions from the same input.
interviewer
What if both engines fail?
candidate
A third copy of the journal, in another building, can rebuild the book. Slower, but nothing is lost.
interviewer
And if a subscriber misses a market data update?
candidate
Each update carries a sequence number, so a gap is noticed immediately, and the subscriber asks a recovery service to resend it. New subscribers start from a snapshot of the whole book, then apply updates. Fair, and self-checking.
interviewer
A broker's trading algorithm goes wild, sending a hundred thousand orders a second at absurd prices. Then what?
candidate
The gateway enforces limits before the sequencer: orders per second per broker, maximum order sizes, and prices within a band around the last trade. A kill switch can cut a broker off instantly. And if a stock's price moves too far, too fast, trading in it pauses: a circuit breaker for the market.
interviewer
Good.

Wrap-up

Wrap-up
Next steps
1
Clearing and settlement downstream
2
Surveillance reading the journal
3
Opening and closing auctions
4
Watch latency at every hop
INTERVIEWER'S FEEDBACK
Strong:asequencerandjournal,a
single-threaded,deterministicengine,a
replayingstandby,fairmulticast.Nexttime:
howthejournalstaysfast.Verdict:strong
hire.
interviewer
We're nearly at time.
interviewer
What would you improve with more time?
candidate
A few things.
candidate
First, clearing and settlement, reading trades from the journal to move money and shares after the day. Second, surveillance, replaying the journal to spot manipulation. Third, opening and closing auctions, where orders are collected and matched at one price, instead of continuously. And fourth, I'd watch latency at every hop, in microseconds, because a slow hop is unfair to everyone behind it.
interviewer
Which would you do first?
candidate
The watching. In an exchange, a slow hop is a fairness bug.
interviewer
Okay, let's stop there. That was excellent. You saw that the data is small and the problem is order, and you were confident enough not to scale out the matching. A sequencer and a journal before acknowledging, a single-threaded, deterministic engine per book, a standby that replays the same journal, and fair multicast. One thing to add: how the journal itself stays fast enough. I'd say a strong hire.
candidate
Thank you. Sequential writes, in batches, I'd say.
Interviewer's feedback

Strong: a sequencer and journal, a single-threaded, deterministic engine, a replaying standby, fair multicast. Next time: how the journal stays fast. Verdict: strong hire.

Score yourself

Interviewers score these seven things. Give your own attempt a tick for each one you did.

  • Asks before drawing. Agrees what the system does, and how well: scale, speed, consistency.
  • Turns users into requests a second and bytes a day, and says what the numbers decide.
  • A small, clear contract, and a data model that fits how the data is read.
  • A working path end to end before any detail. Every box has a reason.
  • Picks the hard parts, compares two options, and chooses one with a trade-off said out loud.
  • What breaks, what happens then, and how users notice. Retries, duplicates, limits.
  • Thinks out loud, checks in with the interviewer, and takes a hint without losing the thread.

0 of 7

Your progress stays on this device.
New System Design videos at 6 pm

Lessons on weekdays, the week's revision on Saturday, a mock interview on Sunday.