Skip to content

Part 9 · Blueprint 62

Stock Exchange & Low-Latency Order Matching Engine

13 min reading · Sources · Editorial review pending

Parallel mutation can violate price-time priority unless ownership and ordering are explicit.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Distributed Consensus: Raft & Multi-Paxos, Time, Clocks & Distributed Ordering: Lamport to TrueTime, High-Throughput Ledger & Payment Gateway.

Sixty-second mental model

Problem: Parallel mutation can violate price-time priority unless ownership and ordering are explicit.

Use: Sequence accepted commands and make replay deterministic.

Design boundary: Match accepted orders for one instrument under a deterministic price-time policy. Command order, risk approval, matching and market-data publication are distinct boundaries; exclude actual exchange certification claims.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing order matching. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one order means and which component owns the accepted input sequence.

Think of a price-ranked queue preserving arrival priority. Separate the requester from accepted input sequence, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.

Architecture and worked reasoning

Design boundary: Match accepted orders for one instrument under a deterministic price-time policy. Command order, risk approval, matching and market-data publication are distinct boundaries; exclude actual exchange certification claims.

Responsibilities on the request path

Order matching: responsibilities and request directionMatch accepted orders for one instrument under a deterministic price-time policy. Command order, risk approval, matching and market-data publication are distinct boundaries; exclude actual exchange certification claims.Order admissionInstrument sequenceOrder bookTrade journal
Match accepted orders for one instrument under a deterministic price-time policy. Command order, risk approval, matching and market-data publication are distinct boundaries; exclude actual exchange certification claims.

Workload and limiting resource

Hypothetical buy limit is 100 units at price 105; asks offer 30 at 103 and 50 at 104. Price priority fills 80 units for 30 × 103 + 50 × 104 = 8,290 price units, leaving 20 units unfilled under the chosen rule. Fees and lot/currency rules are separate.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Order matching: mutation boundaryValidate account/risk and assign accepted command sequence. Then: Apply commands deterministically to the instrument book. Then: Persist trade/order consequences before exposing the committed result.Step 1
Validate account/risk and assign accepted command sequence.
Step 2
Apply commands deterministically to the instrument book.
Step 3
Persist trade/order consequences before exposing the committed result.
Validate account/risk and assign accepted command sequence. Then: Apply commands deterministically to the instrument book. Then: Persist trade/order consequences before exposing the committed result.
  1. Validate account/risk and assign accepted command sequence.
  2. Apply commands deterministically to the instrument book.
  3. Persist trade/order consequences before exposing the committed result.

Observation and recovery path

Order matching: observation boundaryReplay from snapshot plus ordered journal. Then: Publish market-data sequence and recovery snapshots. Then: Keep acknowledgement, execution and settlement meanings distinct.Step 1
Replay from snapshot plus ordered journal.
Step 2
Publish market-data sequence and recovery snapshots.
Step 3
Keep acknowledgement, execution and settlement meanings distinct.
Replay from snapshot plus ordered journal. Then: Publish market-data sequence and recovery snapshots. Then: Keep acknowledgement, execution and settlement meanings distinct.
  1. Replay from snapshot plus ordered journal.
  2. Publish market-data sequence and recovery snapshots.
  3. Keep acknowledgement, execution and settlement meanings distinct.

Failure that changes the decision

Hypothetical scenario: A restarted engine replays nondeterministic wall-clock decisions and produces a different book. Persist required inputs and ensure deterministic transition logic.

Attempt this decision before reading the explanation

Can independent matching workers mutate the same instrument concurrently without coordination?

Only under a protocol that preserves its matching order and invariants. Partitioning by instrument is common conceptually, but splitting one hot book requires a justified ordering design.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Hypothetical scenario. Northwind’s ownership service loses contact with a machine. Dev lets each surviving monitor choose an owner. Priya draws two monitors with different observations, each confidently assigning the same work to someone else.

Before you continue: Does agreeing on a new owner automatically prevent the old process from acting elsewhere?

The paused process can still resume. The protected effect boundary needs to reject authority that is no longer current under the selected protocol.

This keeps the consensus history useful without extending its scope beyond what it controls. Follow the generation through the later action as well as through the log.

Those votes choose a leader; they do not commit the settlement command. C first establishes contact as leader. A client then requests “assign settlement job to generation 8” under operation identity K. C durably appends that command at index 21 with term 8 and sends AppendEntries referring to predecessor index 20, term 7. B and D verify that predecessor, persist the new entry and acknowledge. C now knows that C, B and D hold index 21.

Hypothetical scenario. Inspect a Raft-style group with members A, B and C and committed entries through index 20. A majority is two. Any two majorities intersect, but that arithmetic alone does not define the vote rules, log matching, current-term commit condition or safe membership transition.

Store a command with term and index. A new leader's election must satisfy the protocol's log restrictions before it can extend the authoritative history. A snapshot replaces an included prefix only together with the position, term and configuration evidence needed to continue recovery. Installing arbitrary application state is not a substitute for a coherent replicated snapshot.

Membership changes must preserve the protocol's quorum argument; disjoint old and new groups cannot each decide independently. Even a correct agreed log does not automatically fence a remote effect target. Carry a committed generation to that target and require stale-generation rejection there. Distinguish agreement about assignment from enforcement of the assigned work.

Now suppose the agreed authority generation changes from 7 to 8 when ownership moves. The protected resource has durably recorded 8. A resumed worker presents 7; checking 7 < 8 allows the resource to reject that obsolete action. A current worker presenting 8 must still pass authorization and business validation.

If the resource never checks the generation, recording 8 in the coordinator alone cannot stop the old worker's call. If independent resources each remember different generations, the application must define how authority reaches and is enforced by all required effect boundaries.

For command storage, choose 100 accepted commands per second and 200 bytes of logical command payload. The arrival payload is 100 × 200 = 20,000 bytes per second. Retaining one hour without compaction yields 20,000 × 3,600 = 72,000,000 bytes, or 72 MB. Protocol metadata, replicas and snapshots are excluded. Snapshotting reduces retained history only under a correct state and recovery procedure.

Try a variation before continuing: only C and B acknowledge index 21, while D becomes unreachable. May C apply this new entry as committed? The chosen majority is three; C and B supply only two. C must not treat this new current-term entry as committed from those acknowledgements. A separate database conditional update may be simpler if the application already has a suitable authoritative store; a custom two-vote shortcut is not an equivalent alternative.

Layer 3 · Internals

A price-time matching engine sequences accepted commands and applies them to an explicitly ordered book. A limit buy order may match eligible sell orders according to the chosen price and arrival rules; cancel and replace operations also need positions in the same relevant ordering. Store prices in declared integer ticks and quantities in declared units to avoid unintended numeric comparisons.

A single owner of the mutable book can make the transition function deterministic; it does not remove the need for durable input, replication and recovery. The LMAX Disruptor is an inter-thread event-processing mechanism, not a universal instruction that every exchange must use one architecture. Replaying a committed input sequence should produce the same book and fills under the same rule version. Publish market data from accepted sequence positions and give clients a way to detect gaps. A backup cannot safely emit duplicate trades merely because it rebuilt the book; external publication and failover need their own fencing and deduplication boundary.

In a hypothetical in-memory book, keep an ordered structure of price levels and a FIFO linked list of orders at each level. Maintain a hash map from order ID to its list node. Finding a cancel target then uses the map; unlinking a known node changes a bounded number of neighboring pointers. Removing an empty price level still pays the ordered structure’s maintenance cost, so calling the entire cancel operation universally constant-time would hide work. Market orders walk eligible opposing levels until their quantity is filled or liquidity ends. Include partial fills, tick-size validation and self-trade policy in the deterministic transition rules, then replay boundary cases under the same rule version.

Trade-offs and limits

ApproachProvidesRequires
Single-owner book mutationMakes command ordering and replay easier to reason about.One book's throughput is bounded by that owner's processing path.
Partition by independent instrumentAllows unrelated books to progress separately.Cross-instrument risk and publication need their own authority boundaries.

Recovery decision

Hypothetical scenario: A restarted engine replays nondeterministic wall-clock decisions and produces a different book. Persist required inputs and ensure deterministic transition logic.

Only under a protocol that preserves its matching order and invariants. Partitioning by instrument is common conceptually, but splitting one hot book requires a justified ordering design.

Write your design before revealing the review

Can independent matching workers mutate the same instrument concurrently without coordination?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

Only under a protocol that preserves its matching order and invariants. Partitioning by instrument is common conceptually, but splitting one hot book requires a justified ordering design.

A restarted engine replays nondeterministic wall-clock decisions and produces a different book. Persist required inputs and ensure deterministic transition logic.

Check your understanding

Can independent matching workers mutate the same instrument concurrently without coordination?

Only under a protocol that preserves its matching order and invariants. Partitioning by instrument is common conceptually, but splitting one hot book requires a justified ordering design.

How would you recover from this failure: A restarted engine replays nondeterministic wall-clock decisions and produces a different book. Persist required inputs and ensure deterministic transition logic.

Start with the exact boundary that failed. Validate account/risk and assign accepted command sequence. Apply commands deterministically to the instrument book. Persist trade/order consequences before exposing the committed result. Then recover evidence through the observation path: Replay from snapshot plus ordered journal. Publish market-data sequence and recovery snapshots. Keep acknowledgement, execution and settlement meanings distinct. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical buy limit is 100 units at price 105; asks offer 30 at 103 and 50 at 104. Price priority fills 80 units for 30 × 103 + 50 × 104 = 8,290 price units, leaving 20 units unfilled under the chosen rule. Fees and lot/currency rules are separate. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Match accepted orders for one instrument under a deterministic price-time policy. Command order, risk approval, matching and market-data publication are distinct boundaries; exclude actual exchange certification claims.

Which component in this topology could be removed from a smaller first deployment?

Order admission, Instrument sequence, Order book, Trade journal name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Validate account/risk and assign accepted command sequence.

What evidence must a caller have before relying on the observation path?

Replay from snapshot plus ordered journal. Publish market-data sequence and recovery snapshots. Keep acknowledgement, execution and settlement meanings distinct. Only under a protocol that preserves its matching order and invariants. Partitioning by instrument is common conceptually, but splitting one hot book requires a justified ordering design.

45-minute interview rubric

  1. 00–05: scope order and accepted input sequence.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw accepted input sequence, numbered writes and reads.
  4. 28–40: challenge recovery: Sequence accepted commands and make replay deterministic.
  5. 40–45: defend order_id placement, observations and remaining assumptions.

Go deeper

Decision log

Sequence accepted commands and make replay deterministic.

Preserve order identity and accepted input sequence ownership.

Revisit changed workload, observations or recovery objectives.