Designing an Order Matching Engine
Difficulty: Advanced Patterns: Command, State, Strategy Asked at: Goldman Sachs, Zerodha, Robinhood, Groww
An order book holds every unfilled intention to trade one instrument: buyers at the prices they will pay, sellers at the prices they will accept. A new order arrives and the engine answers one question – does this cross anything already resting here, and if it does, who gets filled first. That is the whole job, and it is the problem where the obvious data structure is wrong for a reason you have to be able to say out loud.
The rule being enforced is price-time priority, and the trap is that it is two orderings at once. Best price first; among orders at the same price, earliest arrival first. A single PriorityQueue ordered by price then arrival sequence looks like exactly that, and for the matching path it is. Then the first cancel arrives. A heap cannot remove an arbitrary element in better than O(n), because remove(Object) scans the backing array to find it before it can sift anything – and in a real market cancels vastly outnumber fills, since most orders leave the book without ever trading. The structure that nails the ordering fails the operation the engine performs most.
The second hard part is arithmetic that holds after every event. One order for a thousand shares can match three resting orders at three prices, produce three trades and still leave a remainder in the book. None of those numbers may drift: for every order, filled plus remaining equals the quantity it was entered with; every trade moves the same quantity on both sides; and all buy fills and all sell fills stay equal forever. Those invariants are the deliverable, not the class diagram.
The third is concurrency, and this is the one design here where the answer is not a lock. A matching engine serialises orders by definition, since “this order arrived first” is a claim about a total order over inbound events. A mutex around the book buys correctness and a latency distribution that falls apart under contention, which is the moment you cared. Real engines go the other way and make the book single-threaded by construction: one thread per instrument consuming a queue of commands, with no lock inside it.
💡 Resting order, also called passive = an order already in the book waiting for someone to trade with it. An order that arrives and trades immediately is the aggressor, or taker.
💡 Price level = all the orders at one exact price on one side, treated as a unit. Most questions the engine asks are about levels rather than individual orders, which is why they get a class.
💡 Crossing the spread = a buy whose limit is at or above the best ask, or a sell at or below the best bid. It is the condition for a trade. Learn more →
Functional Requirements
- Submit an order – a side, a quantity, an order type and, for everything except a market order, a limit price.
- Match on price-time priority – best price first, earliest arrival first within a price, with no exceptions and no randomness.
- Partial fills – one incoming order may produce several trades against several resting orders, and whatever is left follows its type’s resting rule.
- Four order types – limit rests what it cannot fill, market never rests, immediate-or-cancel discards its remainder, fill-or-kill executes in full or not at all.
- Cancel and amend – withdraw a resting order by id, or reduce its quantity, in constant time and without scanning the book.
- Publish market data – emit every trade and every price-level change, so top-of-book is derived from the book rather than stored beside it.
- Self-trade prevention – an account must never match against its own resting order.
Non-Functional Requirements
- Matching is O(log P) in price levels, not orders – P is the number of distinct prices on a side, bounded by the tick grid, so finding the best price is a short tree walk. Taking the next order at that price is O(1), and so is appending a new one.
- Cancel is O(1) – one hash lookup for the order and one decrement of its level’s depth. A cancel never walks a level and never walks the book.
- The book takes no locks – one writer thread per instrument owns it outright. Producers hand over commands and return; sharding by instrument scales by adding threads, not by splitting a lock.
- Deterministic and replayable – the same command log applied to an empty book produces the same trades in the same order, which is what makes the engine testable and auditable at all.
Discussion
Newest first