🎓 A1Learner
🔍
0 of 64 lessons completed

Design a Stock Exchange

A stock exchange is a market system that pairs buy orders with sell orders under set rules. Every trade is recorded once, in order, as the shared truth for all traders.

The ask

An order is an instruction to buy or sell a set number of shares at a stated price limit.

An order book is the ordered list of buy orders and sell orders that still wait for a match. Buy orders sort by price from high to low and sell orders sort by price from low to high.

A matching engine is the part that pairs buy orders with sell orders under the market rules. It produces trades when a buy price meets a sell price.

Fairness is a rule, not a hope. The same inputs in the same order give the same trades for everyone.

Estimate the scale

The market takes 100,000,000 orders a day.

Trading is compressed into a 6.5-hour trading day. 6.5 x 3,600 = 23,400 seconds of trading.

100,000,000 / 23,400 = about 4,274 orders per second while the market is open.

The peak minute runs at 10 times the open average. 4,274 x 10 = about 42,740 orders per second at peak.

API and data

The operations are place an order, cancel an order, read the order book and read trades.

An order carries a trader account, a share, a side, a count of shares, a price limit and a unique order reference.

The side is buy or sell, stated in full. Orders are buy orders and sell orders throughout the design.

The unique reference works as an idempotency key. A repeated place request returns the stored order instead of a second order.

Trades carry the buy order, the sell order, the share count and the trade price. The trade record is final once written.

High-level design

A gateway checks each order for shape, account standing and price sanity. Bad orders are refused before they reach the book.

Accepted orders enter one ordered stream per share. A sequencer stamps each order with a sequence number as it arrives.

The matching engine reads the stream in sequence order and updates the order book for that share.

Trade reports fan out from the engine. Traders, clearing services and market data feeds all read the same trade stream.

The order book lives in memory for speed. A replicated log on disk holds every accepted order for recovery.

Deep dive: the matching engine

The engine holds one book per share. A hot share gets a busy book and a quiet share gets a quiet one.

One engine thread owns one book. A single owner removes locks and makes the order of matches plain.

A new buy order checks the best sell price first. When its limit covers that price, a trade happens at once.

Any unfilled part stays on the book. It waits as an open buy order at its price.

Cancels follow the same stream as orders. A cancel that arrives after a trade finds nothing left to cancel.

Deep dive: price first, then time

Price comes first because the market rewards the best price. The highest buy price and the lowest sell price meet first.

Time comes next at the same price. The earliest order at a price fills before a later order at that price.

A worked case makes the rule concrete. A buy order with a limit of 52 units waits ahead of a later buy order at the same limit.

A sell order with a limit of 50 units can meet the waiting buy order. The sell order fills against the earlier buy order first, and the later buy order waits for the next sell order.

No trader can jump the queue by sending faster after the fact. Sequence order at the gateway fixes each place in line.

The open and the close

Orders pile up before the open. The first minutes carry the peak rate and the engine must hold its order under that rush.

Capacity is planned from the peak figure, not the average. Headroom absorbs news days when volume jumps past the plan.

At the close, open orders expire or carry to the next trading day by market rule. The book state at close is stored and checked.

Market data readers see a delayed copy of the book. Trading never waits on data readers.

Failures and recovery

The replicated log is the recovery story. A new engine copy replays accepted orders in sequence order and rebuilds the same book.

A fencing token stops an old engine copy from writing after a new copy takes over. Two engines never match the same book at once.

Checksums on the log catch damaged records. A damaged tail is cut at the last good record and trading resumes from there.

If the engine halts, the market halts for that share. A fair pause beats unfair trades.

Evaluation and trade-offs

One ordered stream gives fairness and a clean rebuild. It also caps speed for a single hot share.

Memory speed serves the match path. Disk holds the log that makes the memory safe to trust.

The design gives up geographic spread for the core match. Traders far away accept a longer round trip of about 150 milliseconds across an ocean.

The gain is trust in every trade. Price first, then time, applied in sequence order, leaves no room for favour.

Scale at a glance

MeasureValue
Orders a day100,000,000
Trading seconds a day23,400
Average rateabout 4,274 per second
Peak rateabout 42,740 per second

Exercise

In what order does the matching engine pair orders?