CodingNodes Space play · ←→ step · R restart

The problem

An electronic stock exchange does one fundamental job that has not changed in fifty years: it matches a buyer with a seller who are willing to trade at the same price. What has changed is the machinery. Orders now arrive as data packets, are checked, sequenced, and matched by software in a few microseconds, and the result is broadcast to every participant before the trader has finished blinking.

The design is a study in opposing pressures. The critical trading path must be fast — millisecond-level round trips — yet it must also be fair and auditable, so that the result of two orders that arrive at the same instant is the same no matter how it is replayed. And it must stay available, because a single second of downtime moves real money.

Today you will build one: trace an order from a broker through the gateway and the risk checks to the matching engine, design the order book, and make the whole thing fast, fair, and recoverable.

Requirements

Functional — what it must do

  • A client, through its broker, can place a new limit order and can cancel one that is still resting in the book.
  • When a buy and a sell are willing to trade at the same price, the exchange matches them and returns a filled execution to both sides.
  • Every participant can see the live order book — the best bids and best asks — in real time.
  • Enforce risk rules before an order is matched, and withhold a user's funds while an order rests in the book so no one can overspend.

Non-functional — how well it must do it

  • Latency: the round trip from an order entering the exchange to its fill returning is in the low milliseconds, with the 99th percentile kept tight and stable.
  • Availability: at least 99.99% during trading hours, with a fast, deterministic recovery when a node fails.
  • Fairness and determinism: two orders that arrive at the same instant must match in the same order on replay, so the result is auditable and dispute-free.
  • Security: authenticate every order, verify identity before an account is opened, and keep the public market-data feed DDoS-resistant.

Scale — how much it must take

  • Tens of thousands of concurrent trading users and at least 100 symbols, moving billions of orders per day through the matching engine.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Symbols
≈ 100
A small-to-medium book. The design must extend to more, but we size for one hundred active symbols.
Concurrent users
≈ 50,000
Trading accounts active at once. Each places and cancels orders, and reads the book.
Orders per day
≈ 1,000,000,000
Across the day. The matching engine must absorb this in a 6.5-hour window.
Average rate
≈ 43,000/s
1 billion orders over the 6.5 trading hours (about 23,400 seconds) is roughly 43,000 orders per second.
Peak rate
≈ 215,000/s
Volume is roughly five times higher around the open and the close, so we build for about 200,000 per second at the peaks.
Matching latency
< 1 ms target
The engine's own share of the round trip. Network and the broker's path add the rest of the millisecond budget.
Book per symbol
≈ 10k orders
A few thousand resting orders on each side at any price cluster. The book must find the best level in constant time.
State to recover
the event log
The authoritative state is the ordered event log, so a crash recovery is a replay, not a reconstruction.

Takeaways

Part 1

Scope: what does the exchange do

An exchange can trade many instruments and order types. Pinning down the subset we support fixes the matching engine's complexity.

  1. 1
    Narrow the instruments

    We scope to stocks only. Options, futures, and currencies each bring their own payoff and settlement rules, and adding them multiplies the matching and risk logic. Limiting the scope to a single instrument class keeps the design focused on the core of matching buyers and sellers.

  2. 2
    One order type, two operations

    We support only limit orders — an order to buy or sell at a price no worse than the one stated. A market order fills at whatever the current best price is, which adds the complexity of price improvement and partial fills. We keep place and cancel as the two operations, and skip conditional and after-hours trading. That is the cleanest correct exchange.

Part 2

The critical trading path

An order crosses a chain of gates before it is matched. Every hop on this path spends the millisecond budget, so each one must be cheap and in order.

  1. 1
    The order's journey

    A client's order enters at a broker, hits the client gateway for validation, authentication, and rate limiting, then moves to the order manager which runs the risk checks. A sequencer assigns it a global order number, and only then does the matching engine see it. The fill travels back the same way to both sides.

  2. 2
    Why the order number matters

    Orders arrive from many brokers at once, so the exchange must impose a single global order. The sequencer is the one place that assigns a number to every order, in the order it accepts them. That number is what makes matching fair: two orders are never matched on the basis of which server happened to receive them first, but on their sequence.

  3. 3
    Risk before matching

    The order manager checks the order against the risk rules before it is sequenced. An order that violates a rule is rejected here, fast, so it never reaches the matching engine and never touches the book. That keeps the engine's job pure: match orders it has already been told are allowed.

Part 3

The order book

The book is the heart of the exchange: a list of buy orders and sell orders for a symbol, organized by price. How fast it can be read and changed is how fast the exchange is.

  1. 1
    Bids and asks

    For each symbol, the book holds two lists. On one side, the bids: buy orders, highest price first. On the other, the asks: sell orders, lowest price first. The best bid and the best ask — the top of each list — are the price the world quotes for that symbol, and the gap between them is the spread.

  2. 2
    Why price is the key

    When a new order arrives, the engine must instantly find every resting order at a price that can trade with it. Organizing the book by price means that lookup is a direct jump to the price level, not a scan. Adding, canceling, and matching an order should each be close to constant time, so the engine's speed does not depend on how many orders are in the book.

  3. 3
    A fill walks the book

    A buy at 101.55 arrives. It can trade against every ask at or below that price. So it matches the best ask at 101.60 — wait, that is above its price, so it does not match at all; it rests. But a buy at 101.70 matches the ask at 101.60 fully, then the ask at 101.70 partially, until it is filled or the price runs out. The walk is always in price order, from the best level outward.

Part 4

Matching: price first, time second

When a new order can trade against resting ones, the engine decides who goes first. The two rules are price priority, then time priority.

  1. 1
    Price priority

    The first rule is that the best price trades first. A buyer at 102 beats a buyer at 101, because the higher bid is more eager and would have accepted a worse price. So when a sell comes in, it matches the highest bid first, then walks down. The book is always sorted so this walk is a straight line.

  2. 2
    Time priority (FIFO)

    Among orders at the same price, the one that arrived first goes first. That is the FIFO rule: the order book remembers the sequence at each price level, and a new order matches the oldest resting order at the best price before any newer one. It is the rule that makes the exchange fair at the price level.

  3. 3
    A fill produces two executions

    When a buy and a sell match, the engine records one trade but emits two executions — one for the buyer, one for the seller — each saying how many shares filled at what price. Both are pushed to their owners' order managers and into the market-data feed, so everyone sees the trade at the same moment.

Part 5

Risk checks and the wallet

Before an order can match, the exchange must be sure the user is allowed to trade and actually has the funds. These checks run on the critical path and must be cheap.

  1. 1
    The rule set

    Risk rules are the exchange's guardrails. A simple one: a user can trade at most one million shares of any single stock per day. Others cap position size, check trading halts, and enforce the exchange's minimum order increments. An order that breaks any rule is rejected before it reaches the sequencer, so it costs the book nothing.

  2. 2
    Withhold, don't just check

    A resting order in the book still holds a claim on the user's money. If the exchange did not reserve those funds the moment the order was placed, the user could place enough orders to cover the same cash twice. So the wallet withholds the required funds when the order rests and releases them only when the order is canceled or filled.

  3. 3
    Release on cancel or fill

    When a resting order is canceled, the withheld funds go back to the user's available balance. When it is filled, the withheld amount is settled against the trade. Either way, the wallet never holds more than the resting orders require, and it never lets the same dollars back two different orders.

Part 6

Fast, fair, and recoverable

The exchange must be fast, but it must also be the same every time it runs the same orders. Event sourcing is the trick that gives you both.

  1. 1
    The event log is the truth

    Every order, cancel, and fill is appended to an ordered event log before the engine acts on it. That log is the source of truth: the in-memory book is just a fast view over it. If a node dies, the recovery is not a reconstruction but a replay — read the log and rebuild the book exactly as it was.

  2. 2
    Deterministic replay

    Because matching depends only on the order of events and not on the wall-clock time they were received, replaying the same log always produces the same book and the same set of fills. That is determinism, and it is what lets two data centers agree on who won a race, and on what a dispute should resolve to.

  3. 3
    Tight, stable latency

    It is not enough that the average round trip is low; the 99th percentile must be low and stable, because a single slow trade in a race is a lost trade. The exchange keeps a histogram of every round-trip time and treats a rising tail as a defect — often a garbage-collection pause or a context switch — and fixes it.

★ Finale

End to end

One buy order against a resting sell: it is validated, risk-checked, sequenced, matched at the best price, the wallet settles, and the trade is broadcast. That is the whole exchange in one picture.

  1. 1
    The whole exchange

    Clients send orders to the client gateway. Validated orders pass the order manager's risk checks and the wallet's hold, take a sequence number at the sequencer, and enter the matching engine. The engine works a per-symbol order book. Every fill and the updated book are pushed to the market-data feed and to both sides.

  2. 2
    A buy enters the path

    A buy of 1,000 shares at 101.70 arrives. The gateway validates it and authenticates the broker. The order manager checks the risk rules — under the daily cap — and the wallet withholds the funds. The sequencer stamps it with the next global number. It is now legal to match.

  3. 3
    It matches the best ask

    The engine looks at the book. The best ask is 101.60, below the buy's 101.70, so it matches. The engine takes as many shares as the resting sell has — 600 — and, if the buy is not yet filled, continues to the next ask level. The trade is recorded and the two executions are emitted.

  4. 4
    The wallet settles, the feed broadcasts

    The wallet settles the matched shares and releases any remainder of the hold. The engine pushes the two executions to the buyer and seller, and the updated book to the market-data feed. Everyone sees the trade and the new best prices at the same instant. The round trip is well inside the millisecond budget.

🌐 In the wild

In the wild

The same order-sequencing, order-book, and deterministic-replay ideas power the real exchanges that move trillions a day. Here is where each piece shows up.

  1. 1
    These exchanges run it

    Everything you just built is a production equity exchange. The client gateway, the risk-and-wallet gate, the sequencer, the matching engine, and the deterministic event log are the same components the large exchanges are built from. Let's match the diagram to the names.

  2. 2
    LMAX: the matching engine as open source

    LMAX built its exchange around a single, lock-free in-memory structure — the Disruptor — and open-sourced it. The core idea is exactly your sequencer-plus-engine: orders flow through a single ordered, in-memory ring with no locks on the hot path. It is the 'fast and deterministic' requirement, taken to the extreme and published for anyone to read.

  3. 3
    IEX: fairness as the product

    The IEX was founded on the argument that speed is the problem: its whole model is about not letting the fastest trader run the market, with a speed bump and a price collar. That is your determinism and fairness section, promoted from a design goal to the business model — the exchange is designed so the result is the same for everyone, not just the colocated ones.

  4. 4
    Coinbase: the same spine, crypto assets

    Coinbase's exchange runs the same order lifecycle you designed — gateway, risk, matching engine, order book, market data — but for digital assets, and it has written about running it at scale on commodity cloud hardware. The instrument is different; the spine is the same, which is why this design generalizes beyond equities.