Quick revision
The short answer
Each symbol has an order book with bids sorted by price from highest to lowest and asks from lowest to highest, a FIFO queue of orders at each price level, and a map from order id to its queue entry so a cancel takes constant time. A new buy limit order matches while the best ask is at or below its price and quantity remains, filling against the oldest order at the best ask at that resting order's price, and any remainder rests on the bid side. The API accepts new, cancel and replace requests and returns acknowledgements and execution reports, market data publishes book changes and trades, and every input and output is recorded in sequence so the book can be rebuilt and audited exactly.
What to remember
In this answer, we saw that price-time priority means better prices trade first, earlier orders trade first at the same price, and trades happen at the resting order's price. The order book keeps bids and asks in sorted maps of price levels, each a FIFO queue, with an id map for constant-time cancels. A buy limit order fills against the best asks while they are at or below its price, and the remainder rests on the bid side. The API covers new, cancel and replace with acknowledgements and execution reports, and recording every input and output in sequence makes the engine recoverable and auditable.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each symbol has an order book with bids sorted by price from highest to lowest and asks from lowest to highest, a FIFO queue of orders at each price level, and a map from order id to its queue entry so a cancel takes constant time. A new buy limit order matches while the best ask is at or below its price and quantity remains, filling against the oldest order at the best ask at that resting order's price, and any remainder rests on the bid side. The API accepts new, cancel and replace requests and returns acknowledgements and execution reports, market data publishes book changes and trades, and every input and output is recorded in sequence so the book can be rebuilt and audited exactly.
Why this question is asked
A matching engine is the heart of an exchange, and its rules are unusually strict: the same orders must always produce the same trades, and no participant may be treated differently from another. Interviewers ask about it because it combines a precise data structure, a clear algorithm and a design that must be both fast and auditable. In this answer, we will recap what price-time priority means, define the API and the order types, build the order book, walk through matching a new limit order on a concrete book, and see why every message is recorded in sequence.
1A Quick Recap of Price-Time Priority
An order is an instruction to buy or sell a quantity of a symbol. A limit order sets the worst price the trader accepts: a buy limit at 100.03 will pay 100.03 or less, a sell limit at 100.02 will accept 100.02 or more. Orders that cannot trade immediately rest in the book. The highest resting buy price is the best bid and the lowest resting sell price is the best ask; the gap between them is the spread.
Price-time priority decides who trades first. A better price always wins: a seller asking 100.02 trades before one asking 100.03. Among orders at the same price, the one that arrived first wins. And a trade happens at the price of the order that was already resting, so an aggressive buyer willing to pay 100.03 who meets a resting ask at 100.02 pays 100.02. These rules make the market fair and predictable.
2The API and the Order Types
Participants connect through gateways, usually with the FIX protocol or a faster binary protocol. They send three kinds of requests and receive two kinds of responses, and separately everyone can subscribe to market data.
| Type | Behaviour |
|---|---|
| Limit | trade at this price or better; the rest rests in the book |
| Market | trade now at the best available prices; never rests |
| Immediate-or-cancel (IOC) | fill what is possible now, cancel the rest |
| Fill-or-kill (FOK) | fill the whole quantity now or nothing |
| Stop | inactive until the trigger price trades, then becomes market or limit |
The client order id lets the participant match responses to its own requests, and the exchange's order id identifies the order inside the engine. A replace that raises the price or the quantity normally loses its time priority, because otherwise a trader could hold a place in the queue while changing the order.
3Building the Order Book
Each symbol has its own book with two sides. Each side is a sorted map from price to a price level: bids sorted from highest to lowest, asks from lowest to highest, so the best price is always the first entry. A price level holds a FIFO queue of orders, which gives us time priority, plus the total quantity at that price for market data. In Java, a TreeMap gives O(log n) access to the best price, and production engines often use arrays indexed by price tick for O(1) access, because prices move in fixed ticks within a known range.
The third piece is a hash map from order id to the order's node in its queue. A cancel looks the order up, unlinks it from a doubly linked list in constant time, and removes the level if it became empty. Prices are stored as integers in ticks, never as doubles, because floating-point rounding would make 100.03 compare unpredictably.
4Walking Through a Match
Take ACME's ask side: at 100.02, seller S1 with 300 shares (arrived first) and S2 with 200; at 100.03, S3 with 500; at 100.05, S4 with 1,000. The best bid is 100.00. A new buy limit order arrives for 1,200 shares at 100.03.
The engine compares the best ask, 100.02, with the order's limit of 100.03. The ask is at or below the limit, so it trades with the oldest order at that level, S1, for 300 shares at 100.02, leaving 900. It continues with S2, 200 at 100.02, leaving 700, and the 100.02 level is now empty. The next best ask, 100.03, is still within the limit, so it fills S3's 500 at 100.03, leaving 200. The next ask, 100.05, is above the limit, so matching stops, and the remaining 200 shares rest on the bid side at 100.03, which becomes the new best bid.
- Quantity left and asks exist?YesLook at the best askNoRest or finish
- Best ask <= limit price?YesTrade with the oldest order thereNoStop matching
- Trade at the resting pricequantity = smaller of the two
- Remove filled orders and empty levelsthen loop
- Rest the remainder on the bid sideunless IOC, FOK or market
5 steps in order. Play them, or step through them one at a time.
Price first, then time, and the resting order sets the trade price.
5Recording Everything in Sequence
Every input the engine accepts, new orders, cancels, replaces, gets a sequence number and is written to a journal before it is processed, and every output, acknowledgements, executions and market data, is also numbered. Because the matching rules are deterministic, replaying the input journal from the start rebuilds exactly the same book and the same trades. That gives us recovery after a crash, a backup engine that can follow the same stream, and an audit trail regulators can check down to the individual message.
6Follow-up questions
How would you handle a market order when the book is thin?
A market order walks the book until it is filled, which on a thin book can mean very poor prices. Exchanges protect against this with price bands or collars, converting the market order into a limit at a protected price, and cancelling what cannot fill within the band.
Why is a separate book per symbol important?
Symbols are independent: a trade in ACME never affects the BETA book. That makes each book a natural unit of ownership, so one thread can own a group of symbols without locks, and symbols can be spread across threads and machines to scale.
7Conclusion
In this answer, we saw that price-time priority means better prices trade first, earlier orders trade first at the same price, and trades happen at the resting order's price. The order book keeps bids and asks in sorted maps of price levels, each a FIFO queue, with an id map for constant-time cancels. A buy limit order fills against the best asks while they are at or below its price, and the remainder rests on the bid side. The API covers new, cancel and replace with acknowledgements and execution reports, and recording every input and output in sequence makes the engine recoverable and auditable.
Open with
Each symbol has an order book with two sides. Bids are sorted by price from highest to lowest and asks from lowest to highest, each price level is a FIFO queue of orders, and there is a map from order id to its node so cancels are constant time.
Then, if they want more
Prices are integer ticks, never doubles. The API is new order with symbol, side, type, price, quantity and a client order id, plus cancel and replace; responses are acknowledgements and execution reports, and market data publishes book updates and trades. Order types are limit, market, time-in-force options like immediate-or-cancel and fill-or-kill, and stop orders that activate at a trigger price.
For matching a buy limit: while there is quantity left and the best ask is at or below my limit, I trade with the oldest order at the best ask, at the resting order's price, remove filled orders and empty levels, and loop. Whatever is left rests on the bid side.
For example, a buy of 1,200 at 100.03 against asks of 500 at 100.02 and 500 at 100.03 fills 1,000 and rests 200 as the new best bid. Every input and output gets a sequence number and is journaled, so I can replay to rebuild the book exactly and audit every trade.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Describe the order book data structure, the main order types and the API, and walk...": https://scrivio-interview-library.netlify.app/architecture/system-design-problems/64902d37f9/