Commerce & payments · Advanced

Stock exchange matching engine

Sequencer plus single-threaded, in-memory order books, with trades fanned out to market data and clearing.

Every part, and why it is there

Broker firms

Exchanges do not talk to the public directly; brokers send orders for their customers over long-lived FIX or binary connections and care about microseconds.

Order gateway (FIX)

Terminates broker sessions with minimal overhead and does parsing and validation off the hot path. Layer-4 balancing keeps latency low and predictable.

Pre-trade risk checks

Rejects orders that break limits, such as a fat-fingered price, or an order the broker cannot afford, before they reach the book.

Positions & limits

Broker limits and running exposure kept in memory so each check is a lookup, not a database query.

Sequencer

Gives every order a single, increasing sequence number. That total order is what makes the exchange fair and its results exactly reproducible.

Sequenced order log

The sequenced orders are written to a durable, replayable log before matching. If the engine crashes, a standby replays the log and arrives at the identical book.

Matching engine (per symbol)

Keeps each order book entirely in memory and matches by price, then time. One thread per symbol means no locks; you scale by spreading symbols across cores and machines.

Executions

Every fill and book change is published once and consumed by everyone who needs it. Nothing downstream can slow the matching engine.

Market data publisher

Broadcasts prices and book updates to subscribers. It is a separate system, so a flood of market-data subscribers never delays order entry.

Tick history

Every price change, stored by time, for charts, audits and regulators.

Clearing & settlement

After a trade, works out who owes whom cash and shares and hands it to settlement. This runs at normal database speed because it is off the matching path.

Trades & accounts DB

The durable record of trades and account balances. It is updated from the executions stream, never read by the matching engine.

Asked in interviews at

  • coinbase
  • robinhood
  • stake
  • databricks
  • wise
  • mongodb
  • amazon

Concepts used here

  • Server-Sent Events: Build a live score page from one HTTP response that never ends: a few lines of plain text per event, a browser that reconnects by itself, and an id that lets it catch up on what it missed.
  • Segment tree: Build a tree of totals over a ramen shop’s daily sales, then answer any “days l to r” question and absorb any change in about 20 steps for a million days.

Learn more

All system design examples