# Matching engine - price-time priority, and why the clock cannot decide who was first

> Teaches why an exchange assigns order with a sequence number instead of measuring it with a clock, and what a single-threaded book buys in return. Every good…

Source: https://tierslate.com/templates/stock-exchange

Payments & ledgers · System design · deep · 8 step walkthrough · 5 tables

Teaches why an exchange assigns order with a sequence number instead of measuring it with a clock, and what a single-threaded book buys in return.

**Own this board: 800 credits.** The first act plays on the page. Owned once with credits, never a subscription.

## What this board gets wrong on purpose

The tension: Every good property on this board - deterministic matching, a standby that recovers by replay, a surveillance answer that is a fact rather than an opinion - is bought by funnelling the entire market through one sequencer and one matching thread. That is one machine’s worth of throughput and one machine’s worth of failure. The failover is drawn as a hot standby replaying the journal, which is honest and incomplete: promotion takes 200-400 ms, during which the market is halted, and the new primary must prove it has consumed every sequence number the old one published or it will re-use numbers that are already on the wire and in a thousand subscribers’ books. Nothing on this board arbitrates that race - there is no external quorum, only a heartbeat, so a network partition that leaves both engines believing they are primary produces two divergent books and two conflicting trade streams, and the only recovery is a busted-trade process run by humans the next morning. The sharding escape hatch (one engine per instrument group) removes the throughput ceiling and does not remove the problem: it multiplies the number of single points of failure, and any order type spanning two instruments loses determinism entirely.

## Practise this as an interview

Take Matching engine - price-time priority, and why the clock cannot decide who was first as a timed system design interview on a blank board - on your own, with the requirements to check yourself against, or with a candidate you invite.

## Start here

### Why this design

A matching engine is the cleanest test there is of whether you know when NOT to distribute something. Interviewers use it to see whether you reach for timestamps, shards and locks by reflex, or notice that fairness needs one agreed order of events and that the live state of a whole national market fits in 768 MB on one machine. Real venues are built exactly this way, and the regulator checks the result: every trade must be reproducible from the journal years later.

### What you will learn

- Why order is ASSIGNED by a sequencer as a monotonic integer rather than measured with a clock: two gateways’ crystals disagree by more than the 300 ns between two orders.
- Price-time priority as a data structure: two price-ordered sides, a FIFO queue per price level, and the tie-break done by sequence number.
- Why one thread on a pinned core beats a locked concurrent book, and how it matches in microseconds at 52,000 messages/s at the open.
- Journal-before-engine, and how determinism turns into the replication strategy: the hot standby recovers by replaying, not by copying state.
- Why market data goes out over A/B multicast with gap replay, at 37 Mbit/s rather than the 9.4 Gbit/s unicast would cost.
- Why 72% of messages are cancels, and why that ratio rather than the trade rate sizes the engine.

### How to read this board

1. Diagram, left to right: IN (gateway, risk check, sequencer, journal), then THE ENGINE (one thread, the book, the standby), then OUT (execution reports and the multicast feed). Press play for the eight-step walkthrough.
2. Then the band underneath: AFTER THE TRADE - drop copy, trade store, clearing and surveillance, all reading the same numbered stream.
3. Page 1 · Requirements - the questions to ask first, and why determinism outranks latency.
4. Pages 2 and 3 · Capacity and Storage - the numbers behind 52,000 msg/s at the open, the 768 MB book and 41 TB of seven-year history.
5. Page 4 · Availability - the sequencer, engine and multicast feed named as single points of failure, and what degrades.
6. Page 5 · How it works - the whole path told end to end - then Page 6 · Deployment plan, including the replay gate that every engine change must pass.
7. The DATA MODEL region between the diagram and these pages: five tables, and the column that matters is orders.sequence.
8. Finish on the deliberate weakness: the whole market funnels through one sequencer and one thread. Failover halts the market for 200-400 ms and nothing arbitrates a split brain - that is the conversation to have.

## 1 · Requirements

An exchange is a fairness machine. Its product is not throughput and not latency - it is the credible claim that the same rules were applied to everybody in the same order, and that the order can be proved afterwards.

### Ask these before designing

- **Continuous trading, or auctions?**Continuous matching is the interesting engine. Opening and closing auctions are a different algorithm - collect, then cross at one price - and most real venues need both, which means two matching modes over one book.
- **Which order types?**Limit and market is a weekend project. Add stop, iceberg, pegged, and self-trade prevention and the state machine triples. Each new type must preserve determinism, which is why order types are added at roughly one per year and not one per sprint.
- **Is there a maker-taker fee?**Fees change behaviour, and behaviour changes load. A rebate for resting orders produces a market where 70-80% of messages are cancels, which is a capacity requirement disguised as a pricing decision.
- **Who may be first?**Strict price-time is one answer. Pro-rata allocation is another, and size-priority is a third. This is a market-structure decision that determines the core data structure, so it cannot be deferred.
- **What happens on a halt?**Not an edge case: circuit breakers fire on ordinary days. Does the book persist across the halt, or is it purged? Both are defensible, and only one can be true.

### Functional

- Accept, amend and cancel orders; every message acknowledged with its sequence number.
- Match strictly by price, then by sequence, and never by timestamp.
- Publish every book change to market data, in sequence, to everybody at once.
- Publish executions privately to the two participants involved.
- Replay any session from the journal and reproduce the same trades, exactly.
- Halt and resume an instrument without losing the book.

### Non-functional

- **Determinism above everything.**Same input sequence, same output, every time, on any machine. Without this there is no standby, no replay, no surveillance and no defence in a dispute.
- **p99 tick-to-trade under 20 microseconds**inside the engine; p99 gateway-to-ack under**250 microseconds**.
- **Fairness is measured, not asserted.**The spread between the fastest and slowest gateway is published; if one path is reliably quicker, participants pay for it and the venue has an integrity problem.
- **No message loss, ever.**The journal is written before the engine sees the message, and an unjournalled message does not exist.
- **Seven years of replayable history**, because that is what a regulator asks for and the unit of the request is "the whole session".

### Explicitly out of scope

Clearing and settlement (drawn, not designed), market surveillance algorithms, colocation and the physical network, listing and corporate actions, fee schedules. This board is about the moment two orders meet.

## The rest of this board

This page publishes the question. The answer - 5 more written pages, an 8-step narrated walkthrough and a 5-table schema - is the board itself, and it opens in Tierslate.

- 5 written pages
- 8 walkthrough steps
- 5 tables (30 columns)

5 pages behind this one:

- Capacity estimation
- Storage estimation
- Availability
- How it works
- Deployment plan

## Related system design templates

- [Double-entry ledger system design](https://tierslate.com/templates/double-entry-ledger) - Teaches why money is stored as immutable movements and read as a derived sum, and what it costs to never update a total.
- [Fraud detection system design](https://tierslate.com/templates/fraud-detection) - Teaches how a risk decision is split between a synchronous call with a hard deadline and an asynchronous review that is allowed to be right.
- [Payment gateway system design](https://tierslate.com/templates/payment-gateway) - Teaches how a payment system stays correct when its authoritative dependency can fail in a way that tells you nothing.
- [Wallet transfers system design](https://tierslate.com/templates/wallet-transfers) - Teaches how money moves between two accounts in one system without ever being in both places or neither, and what it costs to make every step undoable.
- [OTP verification system design](https://tierslate.com/templates/otp-verification) - How a one-time code is issued, rate limited and checked, and why the SMS bill is the attack surface.
- [Subscription billing system design](https://tierslate.com/templates/subscription-billing) - How a recurring charge is driven by a billing clock, proration and dunning, and why plan changes are the hard part.
- [Currency exchange system design](https://tierslate.com/templates/currency-exchange) - Why a quoted FX rate is a short-lived promise with an expiry, and how rounding is a ledger decision.
- [Loyalty points system design](https://tierslate.com/templates/loyalty-points) - Why points are a ledger with expiry and liability, and why a balance column is the wrong answer again.

All 100 system design templates: https://tierslate.com/templates (Markdown: https://tierslate.com/templates.md)
