Scrivio Interview library
DesignFoundations7 min read · updated 13 November 2026

A stock exchange matching engine receives buy and sell orders and matches them by strict rules, usually price-time priority. It must be fair, deterministic and very fast, and every order and trade must be recorded exactly.

Describe the order book data structure, the main order types and the API, and walk through how a new limit order is matched under price-time priority.

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.

Java
-> NewOrder { clOrdId: "A-1001", symbol: "ACME", side: BUY, type: LIMIT, price: 100.03, qty: 1200, tif: DAY }
-> Cancel { clOrdId: "A-1002", origClOrdId: "A-1001" }
-> Replace { clOrdId: "A-1003", origClOrdId: "A-1001", price: 100.04, qty: 1000 }
<- Ack { clOrdId: "A-1001", orderId: 77001, status: NEW }
<- Execution { orderId: 77001, lastQty: 300, lastPx: 100.02, leavesQty: 900, status: PARTIALLY_FILLED }
// market data (public, no participant names)
<- Trade { symbol: "ACME", px: 100.02, qty: 300, seq: 5501882 }
<- BookUpdate { symbol: "ACME", side: ASK, px: 100.02, qty: 200, seq: 5501883 }
Common order types
TypeBehaviour
Limittrade at this price or better; the rest rests in the book
Markettrade 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
Stopinactive until the trigger price trades, then becomes market or limit
Time-in-force options such as IOC and FOK change how long an order may live.

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.

Java
final class Book {
final TreeMap<Long, Level> bids = new TreeMap<>(Comparator.reverseOrder()); // best = firstEntry()
final TreeMap<Long, Level> asks = new TreeMap<>(); // best = firstEntry()
final Map<Long, Order> byId = new HashMap<>(); // cancel in O(1)
}
final class Level { long price; long totalQty; final ArrayDeque<Order> queue = new ArrayDeque<>(); }
// (a real engine uses an intrusive doubly linked list so a cancel can unlink from the middle)

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.

Java
void matchBuy(Order buy) {
while (buy.remaining > 0 && !asks.isEmpty()) {
Level best = asks.firstEntry().getValue();
if (best.price > buy.price) break; // 100.05 > 100.03: stop
Order sell = best.queue.peekFirst(); // oldest at the best price
long qty = Math.min(buy.remaining, sell.remaining);
emitTrade(buy, sell, best.price, qty); // trade at the resting price
buy.remaining -= qty; sell.remaining -= qty; best.totalQty -= qty;
if (sell.remaining == 0) { best.queue.pollFirst(); byId.remove(sell.id); }
if (best.queue.isEmpty()) asks.pollFirstEntry();
}
if (buy.remaining > 0) rest(bids, buy); // 200 rest at 100.03
}
// trades: S1 300@100.02, S2 200@100.02, S3 500@100.03; 200 rests as the best bid
Step throughMatching a buy limit order
  1. Quantity left and asks exist?
    YesLook at the best askNoRest or finish
  2. Best ask <= limit price?
    YesTrade with the oldest order thereNoStop matching
  3. Trade at the resting pricequantity = smaller of the two
  4. Remove filled orders and empty levelsthen loop
  5. 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.

What to say in the interviewAbout 80 seconds aloud

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/