System design interview guide
Stock Exchange System Design: The Order Matching Engine
Short answer
A stock exchange is a chain built around one ordered stream. Gateways accept orders and run quick checks, and a sequencer gives every order for an instrument a number and writes it to a journal. A single-threaded matching engine applies the orders in that order to an in-memory limit order book, matching by price-time priority: best price first, and at one price, the earliest order first. Fills go back to traders, book changes go out as market data, and standbys replay the same journal so they can take over.
Asked to design only the order book and matching logic? See the order matching engine design guide
Two courses by the author of this page:
770 lessons · 18 free to read
₹1,111 in India · $35 elsewhere, once
Get System DesignYou own this course
219 lessons · 10 free to read
₹1,333 in India · $35 elsewhere, once
Get Generative AI and Agentic AIYou own this course
Save your progress and get the interview checklist PDF
A modern equities exchange matches orders in single-digit to low tens of microseconds inside the matching core, with wire-to-wire figures in the tens to low hundreds once the NIC, kernel bypass, serialisation and gateway hops are counted, and never blinks during a market open. LMAX published a figure of 6 million orders per second on a single thread, on 2010-era commodity hardware. It is worth quoting precisely: that was their Business Logic Processor, which is a different workload from matching, and LMAX is a retail derivatives venue rather than an equities exchange. It shows what one uncontended thread can do, and it is not a per-instrument bound for this design. Order rates at a large venue run into the millions of messages a second at the open, and tail latency rather than the median is what the design is judged on. The hard part is not the average case. It is holding that latency steady when a Fed announcement triggers a burst of cancels and the book churns thousands of times per millisecond.
A stock exchange is a low-latency deterministic matching system, not a CRUD app. Orders arrive over gateways, get validated and risk-checked, then flow into a single sequenced input stream that assigns each event a monotonic sequence number. A single-threaded matching engine consumes that stream and applies each order to an in-memory limit order book, which keeps resting orders sorted by price and, within a price level, by arrival time. Matching follows price-time priority: the best price trades first, and ties break by who got there earliest. Because every replica consumes the exact same ordered input and the engine is deterministic, all replicas compute byte-identical output, so recovery and hot standby become replay problems rather than distributed-consensus problems on the hot path. Durability comes from journaling the sequenced input to an append-only log before or in parallel with matching, in the style of the LMAX Disruptor. Fills and book changes fan out as a market data feed with periodic snapshots plus incremental deltas. The design goal is microsecond-scale, jitter-free matching with zero data loss and provable determinism.
Where it shows up
Asked at high-frequency trading firms, exchanges, and market-data vendors like Jane Street, Citadel Securities, Nasdaq, Jump Trading, and IMC, and increasingly at crypto exchanges building spot and derivatives order books. It also shows up at any firm that runs a latency-critical event-processing core.
Spec sheetStock Exchange
- 01Peak input rate per matching core
- ~1-6 million events/sec
- 02Per-event latency budget
- ~1-10 microseconds in-engine
- 03Journal write bandwidth
- ~200-600 MB/s sequential per core
- 04Active order book depth per instrument
- ~10^3-10^5 resting orders
worked through below, with the maths
in this guide
Design Stock Exchange, part by part
7 parts open to everyone · 3 with a free account · 3 with the course
You can read 7 of 13 parts. A free account opens the deep dive; the course opens all of it.
- Requirementsopen
- Scale estimatesopen
- High-level architectureopen
- Core componentsopen
- Data modelfree account
- Deep dives (10)free account
- Trade-offs to discussfree account
- What the interviewer asks nextwith the course
- The interview scorecardwith the course
- Mock interview on this questionwith the course
- How Stock Exchange actually does itopen
- Frequently asked questionsopen
- Interview readiness checkopen
The hard parts of this design are taught step by step in the System Design course: Event Sourcing, State Machine and Write-Ahead Logging.
Why this question is asked
This problem separates candidates who reach for a database and a queue from candidates who understand mechanical sympathy. It tests whether you can reason about a hot path where a lock, a cache miss, or a garbage-collection pause is a correctness-visible event, not a micro-optimization. Interviewers want to see you pick the right data structure for the order book, explain price-time priority precisely, and defend a single-threaded design against the instinct to parallelize. Above all it probes determinism: can you explain why one sequenced input stream plus a deterministic state machine gives you replicas, recovery, and audit for free, and why introducing nondeterminism, like reading wall-clock time inside the match loop, quietly breaks all three.
This page is the free part.
The course goes deeper on the Stock Exchange design
₹1,111 in India$35 everywhere elseonce, for the whole course
The System Design course covers the Stock Exchange design across a run of lessons, not one page. These 4 alone are about 92 minutes of step-by-step reading, 2 of them with code you run in the browser, all with a quiz.
- Event Sourcing
Store events instead of state, rebuild any point in time from the log of what happened.
- State Machine
Model system behavior as a finite set of states and transitions, the foundation of distributed protocols.
- Write-Ahead Logging
Write changes to a sequential log before applying them, the foundation of database crash recovery.
- Sequential Consistency
All nodes see operations in the same order, though not necessarily real-time order.
all part of
System Design Masterclass
770 lessons · about 290 hours · 18 free to read
₹1,111in India, by UPI
$35everywhere else, by card or PayPal
You own this course
Continue with Event Sourcingpay once,
yours for life
Live from the course bench
Before you design Stock Exchange, try the questions it rests on.
Real interview questions, live diagrams and measured lab results, pulled at random from the lessons. A new set every time you come back.
Requirements
Always clarify these in the first 5 minutes of the interview. Do not start drawing boxes until both lists are agreed.
Functional requirements
- Accept limit and market orders, plus cancel and modify (cancel-replace) requests, per instrument.
- Maintain a limit order book per instrument with two sides, bids and asks, sorted by price and then by arrival time.
- Match incoming orders against resting orders using strict price-time priority and generate fills (executions).
- Support core order types and time-in-force: day, immediate-or-cancel (IOC), fill-or-kill (FOK), and post-only.
- Assign every accepted order and cancel a unique monotonic sequence number and process events in sequence order.
- Emit an execution report for every order lifecycle event: accepted, partially filled, filled, cancelled, rejected.
- Publish a market data feed: top-of-book and full-depth snapshots plus incremental updates, and a public trade tape.
- Persist the sequenced input stream durably so the exact book state can be reconstructed by replay.
- Enforce pre-trade risk and validation: price bands, lot sizes, self-trade prevention, and credit or position limits.
Non-functional requirements
- Matching-core latency in single-digit to low tens of microseconds at the median, with wire to wire in the tens to low hundreds, with bounded tail latency.
- Deterministic execution: identical input sequence must always produce identical fills and book state on any replica.
- Zero acknowledged-order loss: an order acknowledged to the client must survive process or machine failure.
- High throughput per instrument core, on the order of millions of events per second sustained, with headroom for bursts.
- Fairness: no participant is systematically favored beyond what price-time priority dictates.
- Fast recovery: a failed engine must resume from the log or a hot standby in well under a second.
- Strict auditability: every state transition is reconstructable and timestamped for regulators.
Back-of-envelope scale estimates
Show your math. Pulling numbers from thin air signals you have not thought about the load.
Peak input rate per matching core
~1-6 million events/sec
LMAX published 6 million orders/sec on a single business-logic thread, and Treat venue-level throughput figures as rules of thumb rather than measurements, because the ones that circulate are mostly second-hand. A production instrument core is designed for the low millions per second so a single hot symbol at the open does not saturate it. Sourced upper bound, Derived design target.
Per-event latency budget
~1-10 microseconds in-engine
If wire-to-wire is under ~100 microseconds and most of that is NIC, kernel-bypass, serialization, and gateway hops, the matching step itself must live in the low microseconds. That leaves no room for a lock wait (hundreds of ns to us) or a minor GC pause (ms). Derived from published wire-to-wire figures.
Journal write bandwidth
~200-600 MB/s sequential per core
At 2M events/sec and ~100-300 bytes per sequenced input record, that is 200-600 MB/s of append-only writes. Sequential writes to NVMe or a battery-backed device easily sustain this, which is why LMAX journals to raw sequential files rather than a database. Derived (2M x 100-300B).
Active order book depth per instrument
~10^3-10^5 resting orders
A liquid equity can hold tens of thousands of resting orders across a few thousand price levels. The book must fit comfortably in L2/L3-friendly in-memory structures. At ~64 bytes per order node, 100K orders is ~6 MB, small enough to stay resident and cache-warm. Derived estimate.
Market data fan-out
10^3-10^4 subscribers per feed
Co-located members, data vendors, and internal risk systems all subscribe to the incremental feed. Fan-out is handled by reliable multicast or a broker tier downstream of matching, not by the engine looping over subscribers, so publish cost is O(1) from the engine's view. Derived estimate.
Daily sequenced-event volume
~1-10 billion events/day
A busy US equities day is billions of order, cancel, and trade messages across all symbols. At even 2 billion events at ~200 bytes, the day's journal is ~400 GB, which drives snapshot cadence so restart replay stays under a minute. LMAX reported full restart with a day's replay in under one minute. Derived, with sourced restart figure.
High-level architecture
An order enters over a co-located gateway speaking a binary protocol such as FIX/FAST or a proprietary format, arriving via a kernel-bypass NIC so the packet skips the OS network stack. The gateway does stateless work: authenticate the session, decode the message, run cheap pre-trade validation like price bands and lot size, and stamp a client-level sequence for gap detection. It then hands the order to the sequencer, which is the heart of the design. The sequencer serializes all inputs for a given instrument (or instrument shard) into one totally ordered stream and assigns each a monotonic sequence number. That sequenced record is written to an append-only journal and replicated to standby nodes before the client sees a firm acknowledgment, which is what makes an acknowledged order durable. A single matching thread consumes the sequenced stream in order and applies each event to the in-memory limit order book: it walks the opposite side of the book from the best price inward, generates fills under price-time priority, updates or removes resting orders, and inserts any residual quantity as a new resting order. Every fill and book mutation is written to an output stream. Downstream, execution reports route back to the originating members and a market data publisher turns book mutations into snapshot plus incremental feeds and a public trade tape. Because the engine is a deterministic function of the ordered input, a hot standby that replays the same stream holds an identical book and can take over in microseconds, and any node can be rebuilt by loading the last snapshot and replaying the journal from there.
In a real interview, sketch this on the whiteboard before diving into any single box.
Core components
Walk through each service. The interviewer wants to hear what each one owns, not just the names.
Order Entry Gateway
Terminates member sessions and decodes the wire protocol using kernel-bypass networking so packets avoid the OS stack. It performs stateless, cheap validation (session auth, symbol lookup, price band, lot size, rate limits) and forwards well-formed orders to the sequencer. Keeping it stateless lets you run many gateways in parallel in front of one matching core.
Sequencer
Assigns a single monotonic sequence number to every input event for an instrument, producing the one totally ordered stream that the whole design depends on. It is the single writer to the input log, which removes contention and gives every replica the same replayable order. This is the component that turns a distributed problem into a deterministic replay problem.
Matching Engine
A single-threaded, in-memory state machine that consumes the sequenced stream and applies price-time priority matching against the order book. Single-threaded is a feature: it removes locks, keeps the hot data in CPU cache, and guarantees deterministic output. It reads no wall-clock time or random source inside the match loop so replicas stay byte-identical.
Limit Order Book
The in-memory data structure holding resting orders on both sides, organized as price levels sorted best-first, with a FIFO queue of orders at each level to enforce time priority. Common implementations use a sorted map or array of price levels plus intrusive doubly linked lists per level, and a hash index from order id to node for O(1) cancels. Best bid and best ask are cached for constant-time top-of-book reads.
Journal and Replication Layer
Streams the sequenced input to an append-only log on fast storage and to standby nodes before the order is acknowledged, giving durability and hot failover. Sequential append is the only disk pattern that keeps up at these rates, which is why the log is a raw file, not a relational database. Recovery loads the newest snapshot and replays forward from its sequence number.
Market Data Publisher
Converts book mutations into an outbound feed: full or depth snapshots on a schedule plus incremental deltas for every change, and a separate trade tape. It fans out via reliable multicast or a downstream broker tier so the engine itself does O(1) work per event. Sequence numbers on the feed let subscribers detect gaps and re-request a snapshot.
Snapshot and Recovery Service
Periodically serializes the full book and engine state during quiet windows so that replay on restart is bounded. The snapshot plus the journal tail equals the exact current state, which is the event-sourcing guarantee. Snapshot cadence is tuned so a cold restart, including replaying the remaining log, completes in under a minute.
Data model
orders (in-memory node). The resting-order record. arrival_seq (the sequencer's number) is the time-priority tiebreak within a price level. Nodes are pooled and reused to avoid allocation on the…
Every table for Stock Exchange, its keys, and which store fits it and why.
Deep dives
The limit order book data structure and price-time priority. The book must answer three operations fast: insert a resting order, cancel or modify an existing one, and match an aggressor against the best available prices. The…
10 deep dives on the parts that break at scale, with 21 diagrams: The limit order book data structure and price-time priority; The open and the close are auctions, not continuous trading; Sequencing and determinism: one input stream, identical replicas.
Trade-offs to discuss
Single-threaded matching per book versus a lock-based parallel book. One thread owning the book gives lock-free execution, cache locality, deterministic output, and low tail latency. A parallel book pays lock contention and cache-line…
6 decisions an interviewer expects you to defend, each with the alternative and why it loses here.
What the interviewer asks next
One symbol is so busy at the open that its matching core is saturated. What can you do?
4 follow-up questions with model answers, the interview scorecard for this question, and a mock interview on Design Stock Exchange with the AI tutor.
How Stock Exchange actually does it
The canonical public reference is the LMAX architecture, documented by Martin Fowler and by the LMAX team's own Disruptor paper. LMAX runs all business logic on a single in-memory thread, the Business Logic Processor, surrounded by input and output Disruptors, which are lock-free ring buffers, and reported 6 million orders per second on one thread with event-sourced durability and sub-minute restart via snapshot plus replay. The Disruptor paper reports over 25 million messages per second and latencies under 50 nanoseconds for inter-thread handoff on moderate hardware. Venue throughput and tail-latency figures circulate widely and are mostly second-hand, so this page treats them as design targets rather than quoting them as measurements. Martin Thompson's mechanical sympathy writing and the Aeron messaging project extend the same ideas of single-writer, cache-aware, allocation-free design that underpin low-latency exchanges. These sources describe the general architecture; exact numbers for any specific live venue are proprietary and the LMAX and Disruptor figures cited here come from the published sources listed below; the venue-level rates are industry rules of thumb rather than measurements.
Lessons to study before this interview
If any of these topics are fuzzy, the interviewer will catch it. Each lesson is 15 to 60 minutes with diagrams, code, and a quiz.
Frequently asked questions
interview readiness
Are you ready for Design Stock Exchange?
Three questions from this guide. Answer them without scrolling up, the way you would have to in the room.
Go deeper
This guide is built on these 5 lessons. Each one teaches one piece of the Stock Exchange design above, step by step.
- Event SourcingSystem Design · distributed systems core · 30 min
- State MachineSystem Design · distributed systems core · 25 min
- Write-Ahead LoggingSystem Design · consistency models · 17 min
- Sequential ConsistencySystem Design · consistency models · 20 min
- Garbage CollectionSystem Design · consistency models · 20 min
Practice with 770 system design lessons
Lifetime access for ₹1,111 in India or $35 elsewhere. Interactive diagrams, quizzes, and 20 capstone projects to practise on.
This one question is not enough for the interview.
Get all 200 questions in the System Design and Distributed Systems pack
Each question has why it is asked, a full answer, what the interviewer listens for, the follow-ups, the common mistakes and a diagram (268 diagrams in all). A PDF you keep, junior to staff level.
Pay by UPI, cards or netbanking through Razorpay. Pay by card or PayPal, in US dollars. Download at once from My packs.
NEWSystem Design Hands-On
Included in the System Design course: real systems, built live
Postgres Sharding: Complete Hands-On (PgBouncer + Citus). 2 h 36 min and 20 chapters: one PostgreSQL loaded until it breaks, then four shards behind a router you write, PgBouncer and Citus, with the 139-page slide deck. The first 15 minutes are free to watch.


