AlgoViz

Design a stock exchange

hard 60 min

Pair buyers with sellers by one strict rule, in microseconds, without ever losing an accepted order.

Video lesson · Chapter 1 of 5

Two traders disagree about who was first

0:00 / 5:05

Theory

Read or listen first. About 2 min.

What it is

A stock exchange is a regulated marketplace. Buyers and sellers send orders, and the exchange pairs them at the best available price. This page covers only the computer system, never what anyone should buy or sell.

The centre of it is a matching engine: a program that keeps every waiting order in an order book and applies one rule, best price first and then earliest first. The rest of the system exists to feed it orders in a fair order and to make its results impossible to lose.

Why it exists

Without a shared place, each buyer would have to search for a seller and guess a price. An exchange gathers the offers in one book, so a price comes from everyone's offers and everyone can see it.

People trust it only if the rule is followed every time. A lost order, an order that jumps the queue, or a result that cannot be explained later is worse than a slow page. That is why correctness and order come before every other feature.

A short history

  1. 1971

    Nasdaq starts on 8 February as an electronic stock market. At first it shows quotes and does not trade automatically.

  2. 1992

    Work begins on FIX, a shared message format that brokers and exchanges still use.

  3. 2010

    The flash crash of 6 May lasts about 36 minutes and puts automatic trading pauses high on the agenda.

  4. 2011

    Martin Fowler describes the LMAX trading system: all business logic on one thread, 6 million orders a second in a benchmark.

  5. 2024

    In the United States, standard settlement moves to the next business day (T+1) in May.

Words to know

Order book
All waiting orders for one symbol: bids (to buy) and asks (to sell).
Limit order
Trade at this price or better, otherwise wait in the book.
Market order
Trade now at the best available prices.
Price-time priority
Best price first. At the same price, the earliest order first.
Sequencer
The one place that gives each incoming message its number.
Journal
An append-only log of numbered inputs, written before they are acted on.
Deterministic
The same inputs in the same order always give the same result.
Tick
The smallest price step. Prices are stored as whole numbers of ticks.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3NumbersWork out a number when the answer changes what you build.
  4. 4API and dataThe contract first, then the data that serves it.
  5. 5DesignStart with the smallest system that works. Change it only when something breaks.
  6. 6Deep divesCompare the options before you open them, then say which you would pick.
  7. 7Explain your choicesAnswer first. Then compare your reasoning.
  8. 8By levelThe same question is judged differently for mid, senior and staff.
  9. 9MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Number it. The sequencer gives the order its place and writes it to the journal

Understand it

The toy swap table
me first!me first!

Scope

What are we building?

A system for a service like a national equities exchange: accept orders from brokers, keep one order book per symbol, match, report, and publish prices. Sharing one scarce thing is here too, but with a stricter rule than in Ticketmaster: the order of arrival itself is the product.

  • Order

    One sequence of events that everyone accepts and an auditor can check.

  • Match

    Best price, then earliest, on one thread and in memory.

  • Keep

    Journal first. No accepted order is lost when a machine fails.

  • Tell

    Publish prices to thousands of receivers without favouring one.

Similar systems

KindExamplesWhat differs
Equities exchangeNYSE, Nasdaq, LSEThe problem on this page
Derivatives exchangeCME GroupOther instruments and matching rules
Crypto exchangeBinance, CoinbaseOften also holds customer balances
Brokerage appRobinhood, Interactive Brokers, E*TRADESends orders to markets; has portfolios and customers

The finished system

Where the design ends up

The whole system

Brokers, outside our system, send orders to gateways that check limits. Orders enter one of ten shards. Inside a shard the sequencer numbers the order, writes a three-copy journal and then passes it to the matching engine. A hot standby reads the same journal. Trades and book changes go to the feed publisher and on to subscribers by multicast, or through data gateways. Trades are also stored for reports and archived.
Blue is the order path, green is the copy for recovery, orange is data going out. Dashed means it may lag behind.

Summary

The whole topic in one minute.

An exchange is a queue with rules. One sequencer decides the order of events, a journal makes that order durable, and one thread per symbol applies price-time priority in memory. Nothing in that path waits for a database.

Because matching is deterministic, a standby that replays the same journal has the same book. Symbols are split over shards for volume, prices leave by multicast so nobody is served first, and limits and halts stop dangerous orders before they reach the book.

  • One sequencer per symbol decides the order; clocks never do.
  • Write the input to a majority of journal copies, then match, then report.
  • One thread per symbol needs no locks and can be replayed exactly.
  • Split by symbol for volume. The busiest single symbol sets the limit.
  • Multicast prices with sequence numbers, so receivers can see and repair a gap.
  • Limits before the book, halts around it. A fast wrong order is still wrong.

Sources