DEV Community

Cover image for Design a stock exchange: the system design interview walkthrough
Gowtham Potureddi
Gowtham Potureddi

Posted on

Design a stock exchange: the system design interview walkthrough

Design a stock exchange: the system design interview walkthrough

The request to design a stock exchange sounds like a matching problem — take buy orders, take sell orders, pair the ones whose prices cross, done. For a toy book with ten orders that is exactly what it is. But the interview asks you to do it for millions of orders a second on a hot symbol, where two fills of the same share is a real-money bug, where a crash mid-session cannot lose or invent a single order, and where a million people are watching the price tick in real time — and that is a correctness, latency and fan-out problem, not a lookup. This is one of the sharpest system design interview prompts because the one-line brief hides a matching engine system design whose every fill has to be exact, deterministic and auditable.

The round turns on two decisions. First, the heart of the system — the matching engine and the order book it holds — which must order fills fairly by price then time, run fast enough to clear orders in microseconds, and never double-fill a resting order. Second, how you stay correct when things move or break: every accepted order needs one agreed position in time, the book has to survive a crash exactly as it was, and the price feed has to reach a flood of subscribers without the engine ever waiting on them. This walkthrough follows the path a strong candidate draws on the whiteboard — requirements, estimate, API and data model, high-level design, then the deep dives — and at each step it names the follow-up the interviewer uses to tell a memorised answer from an engineer who understands the tradeoff.

Title card for a system design interview walkthrough on designing a stock exchange, showing buy and sell orders flowing through an order gateway and sequencer into a single-threaded matching engine that holds a bids-and-asks order book, on a dark citrus-and-lavender background.

How the stock exchange round is actually run

A stock exchange round runs about 45 minutes on a shared canvas — you draw the boxes and arrows while you talk, and the interviewer interrupts. It is a favourite because the one-line problem opens onto deep water fast: the moment you write "match buyers to sellers," the question becomes in what order, how fast, and what happens when it breaks — and every answer after that (price-time priority, sequencing, durability, fan-out) compounds. Get the matching engine and the event log clean and you have shown the whole system in one problem.

The interviewer rarely lets "take orders and pair the ones that cross" stand. "Two buy orders arrive in the same microsecond for the one share left at the best price — who gets it, and how do you make sure only one of them actually gets it?" That question — correctness under a design that is otherwise just a fast matcher — is the one a copied answer can never rehearse, and the one this round is really testing.

The rounds here are modelled on how the loop runs, not scraped from any candidate's recall. What matters for prep is the shape: a blank canvas, a clock, and a follow-up after every decision you make.

The five-step framework for any HLD round

Every high-level design answer fits the same spine. Say it out loud at the start so the interviewer knows you have a plan, then walk it:

  1. Clarify requirements — functional and non-functional, and what you are explicitly not building.
  2. Estimate — orders per second, latency budget and fan-out, to justify every later choice.
  3. High-level design — the boxes and arrows: gateway, sequencer, matching engine, market-data feed, ledger.
  4. Deep dive — the two or three decisions that actually decide this system.
  5. Follow-ups — bottlenecks, failure modes, and what you would change at ten times the scale.

What the debrief measures

The score is not "right or wrong design." A good HLD debrief reads on four dimensions, and every move below maps to one: problem solving (did you make the engine single-threaded per symbol so price-time priority and no-double-fill both fall out of the design), communication (did you say why a sequencer gives you one agreed order of events in a sentence), technical execution (rebuild the book by replaying an append-only event log, snapshot to bound recovery, fan out market data off the hot path), and time management (did you spend your 45 minutes on the engine, durability and fan-out, not on the order-entry form). Reading a walkthrough teaches the design; it does not teach you to deliver it on the clock while someone pushes back.

Step 1 — Requirements: what a stock exchange must do

Spend the first few minutes here. Jumping to boxes before you have scoped the problem is the fastest way to design the wrong system.

Type Requirement
Functional Place and cancel limit and market orders; match crossing orders by price-time priority; maintain an order book per symbol; execute trades and record them; publish a market-data feed (quotes and ticks); report order status.
Functional (optional) More order types (stop, immediate-or-cancel, fill-or-kill); positions and portfolio; settlement and clearing — call these out, then scope most of them for later.
Non-functional Very low latency (microseconds inside the engine); correctness and consistency (never double-fill, never lose an order); high throughput; durability and auditability (every order and trade recorded and replayable).

The sentence that earns points: "The hard part isn't pairing prices — it's doing it with microsecond latency, perfect consistency so no share is filled twice, and a record clean enough to replay the exact book after a crash." Say that and you have framed the entire design before drawing a box.

Step 2 — Capacity estimation (back of the envelope)

Estimation here is about proving one thing: the hard axes are engine latency, correctness and market-data fan-out, not storage.

Quantity Assumption Result
Orders per symbol ~100K orders/sec at peak on a hot symbol the book must live in memory; no disk or network on the matching hot path
Engine latency one match operation microseconds — it is an in-memory state machine, so the budget is tiny
Market-data fan-out 1 trade → millions of subscribers fan-out, not matching, is the subscriber-side scaling axis
Durability append the sequenced event stream sequential disk writes, replayable — cheap to write, exact to recover

Two conclusions fall out, and you should say both out loud. First, the engine is a tiny in-memory state machine on the hot path — throughput and correctness come from keeping each symbol's book in memory and processing one sequenced event at a time, not from a bigger database. Second, the durability and fan-out problems live off the hot path — an append-only event log for recovery, and a separate publisher tier for the price feed — so the engine never waits on disk or on a slow subscriber. You have now pointed the interview at the real deep dives before anyone asked.

Step 3 — API and data model

The public interface is thin — place and cancel orders, read status, subscribe to prices — and most of the state is the order book and the trade log.

API call Operation
placeOrder(symbol, side, type, price, qty) → order_id validate, authenticate, risk-check, assign a sequence number, hand to the symbol's engine
cancelOrder(order_id) remove a resting order from the book if it is still open
getOrderStatus(order_id) → status open / partially filled / filled / cancelled
subscribe(symbol) → stream a market-data stream of quotes and ticks for the symbol

The data model is dominated by the book and the trade log:

Entity Notes
order order_id, user_id, symbol, side (buy/sell), type (limit/market), price, qty, filled_qty, status, seq.
order_book per symbol, in memory: bids (price level → FIFO queue of orders) and asks (price level → FIFO queue), best prices at the front.
trade trade_id, symbol, price, qty, buy_order_id, sell_order_id, ts, seq — append-only.
event_log the append-only, sequenced stream of accepted orders, cancels and trades — the source of truth for replay and audit.
position user_id, symbol, qty, avg_price — updated async from the trade log, off the hot path.

Step 4 — High-level design: the trading pipeline

Now the boxes. The whole system is one ordered pipeline: an order is validated, stamped with a position in time, matched, and the results fan out. Around that sit the pieces that make it correct, durable and observable:

  • Client → Order gateway: authenticate the user, validate the order, run risk checks (buying power, position limits), then forward only clean orders.
  • Sequencer: assigns one monotonic sequence number to every accepted order and cancel — the single agreed answer to "what happened first," before anything touches the book.
  • Matching engine (per symbol): single-threaded, holding the in-memory order book, applying each sequenced event by price-time priority and emitting trade events.
  • Market-data publisher: takes the trade and quote stream and fans it out to subscribers as quotes and ticks.
  • Settlement / ledger (async) + event log: positions, balances and clearing are driven off the trade log, and every sequenced event is appended to a durable log for replay, recovery and audit.

Say explicitly that the engine is a deterministic state machine, not just a service — feed the same sequenced event log in and you get the exact same order book out, every time. That single property is what later makes crash recovery, auditing and no-double-fill all fall out of one design, which is why the sequencer sits in front of the engine. Naming that determinism unprompted is a signal the interviewer is listening for.

A stock exchange architecture diagram showing clients sending orders to an order gateway that validates and risk-checks, a sequencer assigning a total order, a single-threaded matching engine holding an in-memory order book and emitting trade events, a market-data publisher fanning out quotes and ticks, and an append-only event log feeding an async settlement ledger.

Deep dive: the matching engine and the order book

This is the first decision that actually decides the round. The engine holds an order book per symbol — all the resting buy orders (bids) and sell orders (asks), grouped into price levels — and its whole job is to decide, when a new order arrives, which resting orders it trades against and in what order. The naive answer is "scan the book for a crossing price," but that leaves out the two things an interviewer is listening for: the matching rule and the concurrency model.

Property What it does Why it matters
Price-time priority match at the best price first; within one price level, the earliest resting order fills first (FIFO at the level). Gives a fair, unambiguous order of fills — the rule the whole market agrees on, not first-come chaos.
Single-threaded per symbol one thread owns one symbol's book and processes its sequenced events one at a time; no locks, no shared state. Makes matching deterministic and atomic — a resting order's remaining quantity is decremented in one uninterrupted step, so it cannot be filled twice.

The book itself is in-memory and built for the two hot operations: add (a resting limit order drops into the FIFO queue at its price level) and cancel (pull an order out of its level). The price levels are a sorted structure — a sorted map or an array of price buckets — so the engine can read the best bid and best ask in O(1) and walk outward only as far as a marketable order needs. A market order simply walks the opposite side from the best price, filling FIFO until its quantity is exhausted; a limit order does the same but stops at its limit price, resting whatever is left. Because one thread processes one sequenced event at a time, matching, decrementing and emitting the trade all happen as a single atomic step — there is no window for a second thread to touch the same resting order.

"Two orders could match the same resting order — how do you guarantee one fill, not two?" The engine is single-threaded per symbol and processes one sequenced event at a time, so the resting order's remaining quantity is decremented atomically in memory before the next event is ever looked at — there is no concurrency to race. Say both halves: the sequencer makes the order total, and the single thread makes each match atomic.

System Design
HLD · Payments & marketplaces · 45 min
Design the matching engine out loud, with follow-ups

Practise on Zynter →

Deep dive: consistency, durability and sequencing

This is the decision most candidates under-think. The matching is easy to describe; the follow-ups are always "how do you make sure every fill is exactly right?" and "what happens when the engine dies?"

Sequencing for a total order. Before anything touches the book, the sequencer stamps every accepted order and cancel with one monotonically increasing sequence number. That gives the system a single agreed timeline — there is no ambiguity about which of two orders arrived first, because "first" is defined by the sequence, not by wall-clock races between machines. The matching engine consumes that sequenced stream in order, which is exactly what makes it deterministic.

Durability via an append-only event log. Each sequenced event is appended to a durable log before it is applied — sequential writes, which are cheap. The order book is never the source of truth; the log is. Because the engine is a deterministic function of the log, you can throw the in-memory book away and rebuild the exact same book by replaying the log from the start. This also gives you a perfect audit trail: every trade can be traced back to the precise sequence of orders that produced it.

Exactly-once matching and recovery. Each event carries its sequence number, so a replay or a retry applies each event once and only once — duplicate delivery is harmless because the engine ignores anything it has already applied. To keep recovery fast, the engine periodically writes a snapshot of the book plus the last-applied sequence number; on restart it loads the latest snapshot and replays only the events after it, rebuilding the exact book in seconds rather than from the beginning of the session.

"The matching engine crashes mid-session — how do you recover the exact order book?" The book is a pure function of the sequenced event log, so you load the latest snapshot and replay the events after it — deterministic replay reproduces the book to the exact resting order and quantity. Name both pieces: the append-only log makes the state recoverable, and periodic snapshots bound how much you replay.

A stock exchange consistency and durability diagram showing a sequencer stamping each order and cancel with a monotonic sequence number, an append-only event log written before events are applied to the matching engine, periodic book snapshots with a last-applied sequence, and recovery by loading the snapshot and replaying later events to rebuild the exact order book.

System Design
HLD · Consistency & durability · 45 min
Defend no-double-fill and crash recovery out loud

Practise on Zynter →

Deep dive: market-data distribution at scale

A flood of subscribers changes the shape of the problem. The engine clears orders in microseconds, but millions of clients want to see every price change — and if pushing those updates ever slows the engine down, the whole design fails. The rule is simple: the engine never fans out directly.

The flow, end to end: the matching engine emits a single ordered stream of trades and quote changes to a tier of market-data publishers, which do the fan-out. A new subscriber is first sent a snapshot — the current state of the book or the top of book — and then a stream of incremental updates (deltas) keyed by sequence number, so it can detect a gap and re-sync. For the fan-out itself you use pub/sub (or multicast on an internal network), so one update is written once and delivered to many subscribers rather than the engine looping over a subscriber list. The publisher tier scales horizontally; the engine does not.

Concern Naive Scaled
Fan-out engine loops over every subscriber engine emits one stream; a publisher tier fans out via pub/sub or multicast, scaling horizontally.
New subscriber replay the whole day send a snapshot, then sequence-numbered incremental deltas so clients can detect gaps and re-sync.
Slow consumer backpressure reaches the engine conflate or drop updates for the slow client; never let a slow subscriber stall the engine or other clients.

Repeat the real scaling axis: the engine stays a tiny, fast, single-threaded state machine, and everything that has to reach millions of clients lives behind the publisher tier — so the fan-out and slow-consumer handling, not the matcher's speed, are where the subscriber side lives or dies.

"A million clients subscribe to the price feed — how do you push updates without falling behind?" The engine emits one ordered stream to a horizontally scaled publisher tier that fans out via pub/sub; new clients get a snapshot then sequence-numbered deltas, and slow consumers are conflated or dropped so they never backpressure the engine. The engine never touches the subscriber list.

A stock exchange market-data distribution diagram showing the matching engine emitting a single ordered trade and quote stream to a horizontally scaled tier of market-data publishers that fan out via pub/sub or multicast, new subscribers receiving a snapshot then sequence-numbered incremental deltas, and slow consumers being conflated or dropped so they never backpressure the engine.

The follow-ups that decide the stock exchange round

Scan the probes from each deep dive and they rhyme. Master these five and you are ready for a version of the question that is not drawn exactly like this one.

  • "Who matches first when two orders cross at the same price?" → Price-time priority: best price first, then FIFO by arrival within the level, ordered by the sequencer. (problem solving)
  • "Two orders could match the same resting order — how do you guarantee one fill, not two?" → Single-threaded per symbol processing one sequenced event at a time; the resting quantity is decremented atomically in memory. (technical execution)
  • "The matching engine crashes mid-session — how do you recover the exact book?" → The book is a deterministic function of the append-only event log; load the latest snapshot and replay later events. (technical execution)
  • "A million clients subscribe to the price feed — how do you not fall behind?" → The engine emits one stream to a horizontally scaled publisher tier; snapshot plus sequenced deltas; conflate or drop slow consumers. (communication)
  • "What's the real bottleneck at scale?" → Not the matcher — it's keeping the hot path in memory and off disk, and fanning market data out without backpressuring the engine. (problem solving)

Each maps to a debrief dimension. Reading this list teaches you the answers; it does not teach you to deliver them while someone interrupts — that only comes from saying them out loud.

How to prepare: a one-week plan

You do not need fifty systems. You need this one cold and the framework automatic, so the next "design X" is just new nouns in the same five steps.

  • Days 1–2: Learn the five-step framework until it is reflex. Do the exchange end to end on paper — requirements, estimate, data model, the gateway → sequencer → matching engine → trade events → market data loop.
  • Days 3–4: Drill the matching-engine deep dive: price-time priority, the in-memory order book's add/cancel/match, and why single-threaded per symbol gives you determinism and no double-fill. Say each tradeoff in one sentence.
  • Days 5–6: Own consistency and fan-out — the sequencer's total order, the append-only event log and snapshots for recovery, and the publisher tier with snapshots, deltas and slow-consumer handling. Answer each of the five follow-ups out loud.
  • Day 7: A full timed 45-minute round, narrating the whole way, with someone (or something) interrupting. This is the rep that counts.

This post is the deep walkthrough behind one row of the broader system design interview question set — once the exchange is automatic, the same spine carries the rest of the list.

Frequently asked questions

How do I design a stock exchange step by step?

Follow the five-step HLD framework. Clarify requirements (place and cancel limit and market orders, match by price-time priority, maintain an order book per symbol, execute trades, publish market data, report status — with microsecond latency and no double-fill); estimate to show the hard axes are engine latency, correctness and fan-out, not storage; define the placeOrder/cancelOrder/subscribe API plus the order, order book, trade and event-log model; draw the trading pipeline (client → gateway → sequencer → matching engine → trade events → market-data publisher, with an append-only event log and async ledger); then deep-dive the decisions that matter — the matching engine and order book, consistency and durability, and market-data distribution. Finish on the follow-ups about double-fill and recovery.

What is a matching engine and how does it work?

The matching engine is the core of an exchange: it holds the order book for a symbol and decides, when a new order arrives, which resting orders it trades against. It matches by price-time priority — the best price fills first, and within one price level the earliest-arriving order fills first (FIFO). It runs single-threaded per symbol over a sequenced stream of events, so each match is deterministic and atomic. A market order walks the opposite side from the best price until its quantity is filled; a limit order does the same but stops at its limit price and rests whatever remains.

How does a stock exchange guarantee no double-fill?

Two mechanisms together. A sequencer stamps every accepted order and cancel with a monotonic sequence number, so there is one agreed order of events and no wall-clock race decides who is first. The matching engine then processes that sequenced stream single-threaded per symbol, applying one event at a time, so a resting order's remaining quantity is decremented in a single uninterrupted step. There is no concurrency touching the same order, so the same unit of a resting order cannot be filled twice.

How does a stock exchange recover its order book after a crash?

The order book is never the source of truth — the append-only event log is. Every sequenced order, cancel and trade is written to a durable log before it is applied, and because the matching engine is a deterministic function of that log, replaying it reproduces the exact book. To keep recovery fast the engine periodically snapshots the book along with the last-applied sequence number; on restart it loads the latest snapshot and replays only the events after it, rebuilding the book to the exact resting order and quantity in seconds.

How does a trading platform send market data to millions of users?

The matching engine never fans out to subscribers directly — that would let slow clients stall it. Instead it emits one ordered stream of trades and quote changes to a horizontally scaled tier of market-data publishers that do the fan-out via pub/sub or multicast, so each update is written once and delivered to many. A new subscriber receives a snapshot of the current book, then sequence-numbered incremental deltas so it can detect a gap and re-sync. Slow consumers are conflated or dropped, never allowed to backpressure the engine or the other subscribers.

How do I practise a system design interview out loud?

Reading a walkthrough is not the same as defending a design while someone interrupts. On Zynter, the HLD track runs live voice rounds modelled on how real system design loops run — you talk through a shared design on the canvas, and a voice interviewer pushes with the follow-ups above one at a time, then gives you a debrief on problem solving, communication, technical execution, and time management. The score is a practice signal, not a hiring decision.

Practise it on Zynter

You can read every hop. The round is won on the matching engine and the no-double-fill case.

Pick the Stock Trading round, draw the trading pipeline on the canvas, and defend it out loud to a voice interviewer that keeps asking "how do you guarantee one fill, not two?" and "how do you recover the exact book after a crash?" — then read the debrief. Zynter.ai is on-demand mock interviews modelled on real company loops, with 150+ rounds across 20 companies including the HLD system design track (Sep 2026).

Practise the Stock Trading round →
Browse all interview tracks

Top comments (0)