Design a Low-Latency Stock Exchange Matching Engine
Design a low-latency electronic stock exchange order book and matching engine that matches trade orders in microseconds.
Think of a stock exchange as a very fast auction house. Thousands of buyers and sellers call out prices at once. When the best price to buy meets the best price to sell, the auctioneer makes a trade, in millionths of a second.
- Clients
- Trader
- Entry
- Order gateway
- Services
- Sequencer
- Matching engine
- Standby engine
- Data, outside
- Journal
- Market data feed
1. Requirements and scope
- Place limit orders, market orders, and cancel orders.
- Match buy and sell orders based on Price-Time Priority (FIFO).
- Send every price change and every completed trade to all traders as it happens.
- Deterministic execution order.
- Low latency: an example target is a p99 matching time under 50 microseconds.
- High durability: Zero trade order loss; complete audit log.
2. Back-of-the-envelope numbers
- Writes: 100,000 orders a second (17%)
- Reads: 500,000 price queries a second (83%)
Read-heavy: about 5 reads for each write. A cache and extra read copies help most here.
3. API
4. Data model and storage
Order: (order_id, symbol, side, price, quantity, timestamp, status)
5. The design, in three versions
Version 1: Database-Backed Matching
Orders stored in SQL database; matching performed via database transactions.
Low-Latency Stock Exchange Matching Engine: Version 1: Database-Backed Matching Version 1 of 3
The picture follows one request through the parts of this version, in order. Under it, switch a part off to see what the request does without it.
One request, step by step
Each numbered arrow is one step. Press "Simulate Request Flow" to follow them one at a time.
- The order of the steps
- A request or its reply
The parts: switch one off
1. Clients
2. Entry
3. Services
4. Data, outside
The steps in words0 of 4 steps shown
Trader to Order gateway
A trader sends "buy 100 shares at $10".
Order gateway to Matching engine
The gateway checks the order and passes it on.
Matching engine to Orders database
It locks rows of the order book and matches in SQL. This is slow.
Matching engine to Trader
The trader gets the result.
Write path, read path and failures
Each path follows one request through the final design (version 3), one hop at a time.
Write pathPlace an order
- Trader
- Order gateway
- Sequencer
- Journal
- Matching engine
- Standby engine
Trader to Order gateway
A trader sends an order: buy 100 shares at 50.00 or less.
Order gateway to Sequencer
The gateway checks the order and passes it on. The sequencer gives every order the next number: 1, 2, 3.
Sequencer to Journal
The numbered order is appended to a log on disk before anything else happens.
Sequencer to Matching engine
The engine handles orders one at a time, in number order. It matches the buy against the cheapest sell orders in its book in memory.
Sequencer to Standby engine
The standby engine receives the same numbered orders and does the same work.
Matching engine to Trader
The engine reports what was filled, such as 100 shares at 49.98.
Read pathRead market data
- Matching engine
- Market data feed
- Traders
- Recovery service
Matching engine to Market data feed
After each match or change to the book, the engine publishes an update.
Market data feed to Traders
The feed sends the update to all subscribers at the same moment, over UDP multicast.
Traders to Recovery service
Each update is numbered. A trader who sees a gap asks a recovery service to send the missing ones again.
What breaks, and what happens then
The primary matching engine crashes
- What users see
- Matching stops for that stock for a moment.
- What the design does
- The standby has handled the same numbered orders, so its book is identical. It takes over at the next number.
The journal disk is slow
- What users see
- Every order waits, because nothing is matched before it is logged.
- What the design does
- Write to the log in small batches on fast disks, and keep a second copy on another machine.
A trader's connection drops after sending an order
- What users see
- The trader does not know if the order was placed.
- What the design does
- Each order carries the trader's own id. On reconnect, the trader asks for the status of that id and does not send it again.
6. Deep dives
7. Follow-up questions
- How do you make price updates fair? (Answer: send one copy by UDP multicast, so the network hands it to every trader at nearly the same moment.)
What it costs
Hardware and network are the cost, not storage. Low delay needs dedicated machines, fast network cards and a standby that mirrors every order. The journal is about 10 TB a year, which is small.
Another way to design it
An exchange that can accept a few milliseconds of delay can run on ordinary servers with a replicated log. It is much cheaper to build and run. It suits a small market, not a venue where traders compete on speed.
8. How answers are judged
A passing answer at Mid level. A complete design with numbers: about 100,000 orders a second for one symbol. It explains price-time priority matching and goes deep on one part, such as the order book or the journal.
| What is judged | Junior | Mid | Senior | Staff |
|---|---|---|---|---|
| BreadthHow much of the system does the answer cover? | Names the core parts: clients, servers, a database and a cache. | Covers the whole main flow, from the request to the stored data and back. | Builds a complete design without being led through it. | Covers the system, the systems around it and who owns each part. |
| DepthHow far does it go into the hard parts? | Explains what each part does and why it is there. | Goes deep on one part, such as the database or the cache. | Goes deep on the two or three riskiest parts. | Goes deepest where the risk is largest, and explains why the risk is there. |
| DrivingWho leads the conversation? | Follows the interviewer, step by step. | Moves forward alone, with an occasional nudge. | Leads the conversation from start to finish. | Changes the problem when the question asked is not the right one. |
| Trade-offsAre choices compared and justified? | Names more than one option. | Says why one option was picked over another. | Compares options in detail, with what each one costs. | Ties each choice to cost, speed and risk for the business. |
| Unclear questionsWhat happens when the question is vague? | Answers the questions that are asked. | Asks questions to make the problem clear. | Sets the scope and says what is left out. | Questions the assumptions behind the problem itself. |
| ScopeWhat does it consider beyond the normal path? | Covers the normal path, when everything works. | Adds what happens when a part fails. | Adds growth: what breaks at ten times the load, and the fix. | Adds abuse, cost and the daily work of running the system. |
Requirements and scope
Before I design, I want to check the scope. This is order matching and market data, not clearing or settlement, which happen after a trade. Does every symbol need the same microsecond target, or only the most liquid ones? I will assume price-time priority, and that market data fairness matters as much as speed.
I will assume every symbol trades about as much as any other. So I would place symbols on matching machines by hash, then start designing the API and the order book.
Shows: Unclear questionsThe difference: Trading is lopsided: a few symbols carry most orders. Assuming even load without asking lets hashing put two hot symbols on one machine, slowing both.
Estimates
At up to 100,000 orders a second for one hot symbol, at 150 bytes each, that is 15 megabytes a second, within NVMe's write speed. Only a few symbols hit that peak, briefly at the open, so the exchange's audit log still totals about 10 terabytes a year. Market data reads run far higher, near 500,000 ticks a second.
100,000 orders a second is the peak for one hot symbol, and the exchange lists about 8,000 symbols. So I would size the whole system for 800 million orders a second, spread across all of them.
Shows: DepthThe difference: Only a handful of symbols ever get near that peak at once; most trade far less. Sizing every symbol for the hot-symbol rate wastes capacity many times over.
Core design
Each order for a symbol goes to that symbol's own single-threaded matching engine. A symbol's book runs on one thread, one machine, so a hot symbol cannot be split across machines. Only busy symbols need a dedicated, pinned machine and core, while quiet ones share one, so cost scales with the number of hot symbols.
I would run the matching engine with a thread pool, so several orders for the same symbol get matched at once for higher throughput. A lock around the order book keeps updates safe.
Shows: DepthThe difference: Locking around concurrent threads for the same symbol's book breaks the strict price-time order the exchange must guarantee. One thread per symbol keeps that order without a lock.
Deep dive
The hard part is matching fast without scanning the book. Price levels sit in a balanced tree, each pointing to a linked list of orders in arrival order. That gives price-time priority for free. A cancel is O(1) through a hash map pointer to its list node, and a match at the top is also O(1).
I would keep all orders for a symbol in one array sorted by price and time, and insert a new order in its sorted position. Cancelling an order removes it from the array the same way.
Shows: DepthThe difference: Inserting into or removing from a sorted array shifts many elements as the book grows. A price-level tree with linked lists keeps insert, cancel and match near constant time.
Failures and trade-offs
If the primary matching engine crashes, a hot standby takes over. Every order passes through a sequencer that logs it to a write-ahead log before matching. The standby replays that log in order and reaches the identical book state. Trading pauses only for the replay.
If the primary crashes, the hot standby starts accepting new orders where trading left off. It does not need to replay anything, since it already holds a live copy of the current book in memory.
Shows: ScopeThe difference: A live in-memory copy can be missing whatever crashed with the primary. Replaying the sequencer's log deterministically is what gives the standby the identical, gap-free book state.
We wrote this guide in our own words, informed by public interview guides such as AlgoMaster and Hello Interview. We are not connected to either site. Interviewers differ. The guide and the example answers show the direction each level takes, not a checklist.
10. Check your design with your own AI
Write your design first. Then copy this prompt into the AI chat you already use, and add your design at the end. It asks for a score in each area, one fix for each, and two follow-up questions.
The site sends nothing anywhere. An AI review can be wrong, so check what it says against sections 8 and 9.
See the prompt
You are a system design interviewer. Review my design for the interview problem below. Problem: Design a Low-Latency Stock Exchange Matching Engine Design a low-latency electronic stock exchange order book and matching engine that matches trade orders in microseconds. What users must be able to do: - Place limit orders, market orders, and cancel orders. - Match buy and sell orders based on Price-Time Priority (FIFO). - Send every price change and every completed trade to all traders as it happens. How well it must work: - Deterministic execution order. - Low latency: an example target is a p99 matching time under 50 microseconds. - High durability: Zero trade order loss; complete audit log. Numbers to assume: - 100,000 orders/second per hot ticker symbol during market open. Judge my design at the Mid level. A passing answer at this level: A complete design with numbers: about 100,000 orders a second for one symbol. It explains price-time priority matching and goes deep on one part, such as the order book or the journal. For each area below, say whether my design is strong, fine or weak. Give one reason and one fix for each: 1. Requirements and scope 2. Estimates 3. Core design 4. Deep dive 5. Failures and trade-offs Then ask me the two follow-up questions an interviewer would ask next. Do not write a full model answer for me. My design: [Describe your parts, how one request moves through them, and why you chose each one.]