Asked at
URL Shortener (TinyURL)
Asked from Junior level upFoundations & Storage
Distributed Rate Limiter
Asked from Mid level upAPI Gateway & Security
Distributed Key-Value Store
Asked from Senior level upFoundations & Storage
Distributed Notification Service
Asked from Mid level upMessaging & Queues
Distributed Web Crawler
Asked from Mid level upDistributed Systems
Metrics & Monitoring Platform
Asked from Senior level upObservability & Time-Series
Real-Time Chat App (like WhatsApp or Slack)
Asked from Mid level upReal-Time & WebSockets
Social News Feed (like X/Twitter)
Asked from Mid level upSocial & Feed Systems
Ride-Hailing App (like Uber)
Asked from Senior level upGeospatial & Real-Time
Low-Latency Stock Exchange Matching Engine
Asked from Staff level upFintech & Low Latency
Global Video Streaming Platform (like YouTube or Netflix)
Asked from Senior level upMedia & Streaming
Distributed Hotel & Ticket Reservation System
Asked from Mid level upE-Commerce & Transactions
Shared Document Editor (like Google Docs)
Asked from Staff level upReal-Time & Distributed State
Game Leaderboard
Asked from Junior level upCaching & Data Structures
File Sync Service (Dropbox / Google Drive)
Asked from Mid level upStorage
Payment System
Asked from Senior level upPayments & Transactions
Ad Click Aggregation
Asked from Senior level upStream Processing
AI Support Assistant (RAG)
Asked from Senior level upAI Systems
LLM Inference Platform
Asked from Senior level upAI Systems
Enterprise Semantic Search
Asked from Mid level upAI Systems
AI Code Completion
Asked from Senior level upAI Systems
LLM Gateway
Asked from Senior level upAI Systems
AI Agent That Takes Actions
Asked from Senior level upAI Systems
LLM Evaluation Platform
Asked from Senior level upAI Systems
AI Document Processing Pipeline
Asked from Mid level upAI Systems

Design a Low-Latency Stock Exchange Matching Engine

Asked from Staff level upDomain: Fintech & Low Latency
Concepts to know first:

Design a low-latency electronic stock exchange order book and matching engine that matches trade orders in microseconds.

An analogy

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.

Where this design ends up. This is version 3 of 3. Part 5 builds it up from version 1 and says why each part was added.
  1. Clients
    • Trader
  2. Entry
    • Order gateway
  3. Services
    • Sequencer
    • Matching engine
    • Standby engine
  4. Data, outside
    • Journal
    • Market data feed

1. Requirements and scope

Functional Requirements
  • 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.
Non-Functional Requirements & SLAs
  • 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.
Key Traffic Assumptions: 100,000 orders/second per hot ticker symbol during market open.

2. Back-of-the-envelope numbers

Writes and reads each second
  • 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.

Write Throughput
100,000 orders/sec per symbol
Read Throughput
500,000 market tick queries/sec
Storage Growth
Every order and trade saved to append-only NVMe journaling log: ~10 TB/year
RAM Cache Footprint
The whole active order book stays in RAM, and the busiest price levels stay in the CPU cache

3. API

FIX/TCPOrderSingle(D)Financial Information eXchange (FIX) binary protocol message
UDPMarketData(W)Multicast UDP market depth feed (Level 2)

4. Data model and storage

Storage Strategy: In-Memory Doubly-Linked Lists + Binary Search Tree (AVL/Red-Black) backed by NVMe Sequential Journal Log.
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.

TraderOrder gatewayMatching engineOrders database1234
  • The order of the steps
  • A request or its reply

The parts: switch one off

1. Clients

Tradersends an order

2. Entry

Order gatewaylimit and risk checks

3. Services

Matching engineorder book in memory

4. Data, outside

Orders databasethe order book in SQL

The steps in words0 of 4 steps shown

  1. Trader to Order gatewayHTTPS · 2 ms

    A trader sends "buy 100 shares at $10".

  2. Order gateway to Matching enginecall · 3 ms

    The gateway checks the order and passes it on.

  3. Matching engine to Orders databasequery · 8 ms

    It locks rows of the order book and matches in SQL. This is slow.

  4. Matching engine to Traderreply · 20 ms

    The trader gets the result.

Why this version
ACID transactional safety.
Next bottleneck
Orders at the best price all wait for the same row locks, so throughput falls far short of 100,000 orders a second.

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

  1. Trader
  2. Order gateway
  3. Sequencer
  4. Journal
  5. Matching engine
  6. Standby engine
  1. Trader to Order gateway

    A trader sends an order: buy 100 shares at 50.00 or less.

  2. Order gateway to Sequencer

    The gateway checks the order and passes it on. The sequencer gives every order the next number: 1, 2, 3.

  3. Sequencer to Journal

    The numbered order is appended to a log on disk before anything else happens.

  4. 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.

  5. Sequencer to Standby engine

    The standby engine receives the same numbered orders and does the same work.

  6. Matching engine to Trader

    The engine reports what was filled, such as 100 shares at 49.98.

Read pathRead market data

  1. Matching engine
  2. Market data feed
  3. Traders
  4. Recovery service
  1. Matching engine to Market data feed

    After each match or change to the book, the engine publishes an update.

  2. Market data feed to Traders

    The feed sends the update to all subscribers at the same moment, over UDP multicast.

  3. 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

Price-Time Priority Matching Data Structure
The order book uses a balanced tree (B-Tree or TreeMap) keyed by Price. Each price level node points to a Doubly-Linked List of Orders sorted by arrival timestamp. Limit order insertion is O(log P), order cancellation is O(1) via hash map pointer, and order matching is O(1) at top of book.

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.

How each level is judged
What is judgedJuniorMidSeniorStaff
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

Strong answer
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.
Weak answer
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

Strong answer
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.
Weak answer
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

Strong answer
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.
Weak answer
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

Strong answer
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).
Weak answer
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

Strong answer
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.
Weak answer
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.]