Limit Order Book Matching Engine
Hard · System Design · Software Engineer · Technical Screen
Prompt
Architect and implement a low-latency, in-memory matching engine for a financial limit order book.
Required API surface:
placeOrder(orderId, side, price, quantity, type)wheresideisBUYorSELLandtypeisLIMITorMARKETcancelOrder(orderId)to pull an open resting order from the booktopOfBook()returning the current best bid and best ask as(price, totalQuantity)depth(k)returning the topkaggregated price levels on both the bid and ask sides
Matching semantics & invariants:
- Price–time priority (FIFO): Superior prices execute first; within the same price tick, earlier arrivals execute ahead of later arrivals.
- Immediate crossing & partial fills: Incoming orders match right away against opposing resting liquidity at the resting maker's price. Unfilled
LIMITquantity rests on the book, whereasMARKETorders walk opposing price levels until filled or liquidity runs out and cancel any leftover quantity rather than resting. - Self-trade prevention: Orders belonging to the same trader/account must never fill against one another.
Scale, complexity, and concurrency targets:
- Handle up to
1,000,000(10^6) live resting orders at roughly100,000(10^5) operations per second. - Achieve
O(log P)insertion and cancellation (wherePis the count of active price levels) andO(1)topOfBook()reads, eliminating all linear scans across orders. - A single-threaded core matcher is fine as the baseline; explain how to scale across multiple CPU threads while keeping execution strictly deterministic.
Illustrative order sequence (prices in integer ticks):
Suppose Mina rests SELL 6 @ 250 (ord_1), Nate rests SELL 4 @ 250 (ord_2), Owen rests SELL 5 @ 252 (ord_3), and Pia rests BUY 8 @ 248 (ord_4), giving topOfBook() -> ((248, 8), (250, 10)). Next, Quinn submits BUY 8 @ 250 (ord_5), completely filling ord_1 (6) and partially filling ord_2 (2), leaving (250, 2) at best ask. If Nate then sends a MARKET buy for 12 (ord_6), self-trade prevention cancels Nate's remaining 2 shares on ord_2, ord_6 fills 5 shares against ord_3 at 252, and the remaining 7 shares cancel due to exhausted ask liquidity.
Scope & Expectations
- Data-structure design & complexity: Specify how price levels, per-price FIFO queues, cached level totals, and order-ID lookups fit together to achieve
O(log P)updates andO(1)top-of-book in bounded memory. - Core matching & API implementation: Provide clean, executable code for
placeOrder,cancelOrder,topOfBook, anddepth(k)handling partial fills, market sweeps, and self-trade prevention. - Adversarial & tail-latency defenses: Identify crafted order patterns that trigger worst-case slowdowns or memory growth and explain concrete exchange and algorithmic safeguards against them.
- Deterministic multi-threading: Show how to parallelize I/O, journaling, risk checks, and multi-symbol execution across cores without introducing lock races or breaking deterministic replay.
Step-by-step walkthrough
Clarify requirements, domain terms, and invariants
First, define the trading concepts in plain English and state our assumptions out loud so every data-structure choice is crystal clear (
Pdenotes the number of active price levels on one side):- Limit order book: A live, two-sided waiting list for one financial instrument (such as shares of
AAPL), holding buy offers (bids, sorted highest price first) and sell offers (asks, sorted lowest price first).
BIDS (Buyers: highest first) ASKS (Sellers: lowest first) ---------------------------- ---------------------------- Best Bid -> $248 : [8 shares] <-- spread --> $250 : [6 shares -> 4 shares] <- Best Ask $247 : [10 shares] $252 : [5 shares]- Limit vs. market orders: A limit order sets a worst acceptable price (for example, "buy up to 8 shares at 250 or cheaper"); any unfilled shares stay (rest) on the book. A market order sets no price limit: it sweeps the opposite side from best price outward until filled or the opposite side runs out, and any unfilled remainder is immediately cancelled so a market order never rests on the book.
- Maker, taker, and trade price: An order waiting on the book is a maker; an incoming order that matches immediately is a taker. Every trade executes at the maker's resting price (so a buyer bidding
255against a resting ask at250pays250). - Integer ticks (never floats): Prices are stored as integer ticks (smallest price increments, such as cents:
$2.50->250). Floating-point math (0.1 + 0.2 != 0.3) would split identical prices into separate buckets. - Price–time priority (FIFO): Better prices always match first; among orders at the exact same price, the order that arrived earliest matches first (First-In, First-Out).
- Self-trade prevention (STP): Two orders from the same account (
trader_id) must never match against each other (regulated exchanges forbid trading with yourself). By default we use cancel-resting (cancel the trader's older resting order and keep matching), with cancel-incoming supported as a configuration switch.
Five invariants that must hold after every single operation:
- Uncrossed book: Best bid price is strictly
<best ask price (whenever a bid is>=an ask, they match immediately before anything rests). - Exact level totals: Every price level's
total_qtyequals the exact sum of its live orders' remaining quantities. - No ghost levels or orders: Every resting order appears in
liveand in onePriceLevel, and emptyPriceLevelobjects are removed immediately. - Strict FIFO within a level: Orders inside any price level remain in exact arrival order.
- Deterministic execution: Feeding the exact same sequence of inputs always emits the exact same sequence of events.
- Limit order book: A live, two-sided waiting list for one financial instrument (such as shares of
Back-of-the-envelope numbers: latency, memory, and durability
Throughput & CPU budget Target rate 100,000 ops/s (1e5 ops/s) on 1 matcher thread -> 10 microseconds (10 us) / op! Typical workload ~55% resting limit orders, ~40% cancels, ~5% aggressive matching orders Price levels (P) 1,000,000 live orders spread across ~1,000 to 10,000 active price levels/side log2(10,000) ~ 13 tree/heap steps (~100-300 ns in C++, ~1-3 us in Python) Average ~100 orders/level, up to 1,000,000 in an adversarial pile-up Memory footprint (for N = 1,000,000 live orders) C++ / Java ~64 B per Order struct + ~32 B hash entry ~ 96 MB total (fits near L3 / RAM) Python (__slots__) ~300 B per live Order + OrderedDict/dict overhead ~ 300 MB total (< 0.5 GB) Durability & recovery math Input journal 100,000 msgs/s x 64 B binary frame = 6.4 MB/s sequential disk write 6.5-hour trading day at peak = ~150 GB Book snapshot 1,000,000 orders x 40 B = 40 MB -> writes to NVMe SSD in ~20-40 msThree conclusions drive our data-structure choices:
- The 10-microsecond budget rules out every
O(N)orO(P)scan. Scanning1,000,000orders to cancel an ID or summing100,000orders at the best price takes milliseconds — 100x to 1,000x over budget. - All
1,000,000orders fit comfortably in RAM (~100–300 MB) on a single server, so the hot path never waits on disk reads. - Logging every input message (
6.4 MB/s) is cheap, allowing crash recovery via periodic 40 MB snapshots plus deterministic replay.
- The 10-microsecond budget rules out every
Core APIs and the deterministic event stream
We support the exact prompt signatures (with an optional
trader_idto enforce self-trade prevention) and emit an ordered list of events from every state-changing call:Operations placeOrder(orderId, side, price, quantity, type, trader_id=None) -> list[Event] cancelOrder(orderId) -> list[Event] topOfBook() -> ((best_bid_price, total_qty) | None, (best_ask_price, total_qty) | None) depth(k) -> ([(bid_price, qty), ...], [(ask_price, qty), ...]) # up to k best levels each Output events (emitted in exact causal order) ("accepted", order_id) ("rejected", order_id) # invalid qty/price/side/type or duplicate live ID ("trade", taker_id, maker_id, price, qty) # executed at maker's resting price ("rested", order_id, price, remaining_qty) # unfilled LIMIT tail added to book ("cancelled", order_id, cancelled_qty, reason) # "client", "self-trade", or "no liquidity" ("cancel_rejected", order_id) # unknown, already filled, or already cancelledWhy emit events on every mutation (including
cancelOrder)? Because trade execution reports, real-time market-data feeds, and audit logs are all pure projections of this single event stream: any subscriber processing every event in order reconstructs the exact same order book.Data structures: achieving O(log P) updates and O(1) top-of-book
To hit
O(1)top-of-book,O(1)order lookup by ID, andO(log P)price-level updates simultaneously, we combine three indexed structures:MatchingEngine |-- live (Hash Map: order_id -> Order) ------------------> O(1) direct lookup for cancelOrder! | |-- bids: BookSide (is_bid = True) / asks: BookSide (is_bid = False) |-- heap (Min-Heap of -price for bids, +price for asks) -> heap[0] is ALWAYS the best live price! |-- in_heap (Hash Set of prices currently in heap) -> prevents duplicate heap entries +-- levels (Hash Map: price -> PriceLevel) -> O(1) lookup for existing price level | v PriceLevel(price=250, total_qty=10) orders (FIFO doubly linked map: OrderedDict / intrusive list): HEAD -> [Order 1: qty 6] <-> [Order 2: qty 4] <- TAILWhy each component is chosen carefully:
PriceLevel.ordersas anOrderedDict(hash map + doubly linked list): Appending a new order at the back isO(1), peeking at the oldest order at the front isO(1), and unlinking a cancelled order in the middle byorder_idisO(1). (Beware a subtle Python trap: a plaindictpreserves insertion order, but repeatedly deleting from the front leaves tombstones at the start of its internal table, turningnext(iter(d))into a quadratic slowdown!OrderedDictmaintains real doubly linked pointers so front pops stayO(1)forever.)PriceLevel.total_qty: Maintained incrementally (+qtyon rest,-qtyon fill or cancel), makingtopOfBook()a single integer read instead of summing every order at that price.BookSideprice index: In C++ (std::map) or Java (TreeMap), a balanced binary search tree keepsPactive price levels sorted inO(log P)insert/delete. Because Python's standard library has no balanced BST, we pair alevelsdict (price -> PriceLevel) with a binaryheapqusing lazy deletion (explained in the next step).
Operation Time complexity Why it holds in plain words placeOrder(existing price level, no match)O(1)Dict lookup in levels+O(1)append to FIFO tailplaceOrder(creates a brand-new price level)O(log P)Pushes 1 new price into the P-level heapcancelOrder(orderId)O(1)(orO(log P)amortized if level empties)O(1)lookup inlive+O(1)FIFO unlink; heap cleanup only when the last order at that price leavesMatching Fresting orders acrossLemptied levelsO(F + L log P)amortizedEach filled resting order is removed permanently once in its life ( O(1)amortized per order placed)topOfBook()O(1)Reads heap[0](guaranteed live!) and its cachedtotal_qtydepth(k)O(k log P)amortizedPops klive prices from the heap and pushes them back (O(log P + k)with a C++/Java tree)Space O(N + P)Stores Nlive orders and at most~2P + 64heap integersCode part 1: orders, FIFO price levels, and one side of the book
Let's write
Order,PriceLevel, andBookSidecleanly. Pay special attention to howBookSidemakes lazy deletion (leaving a deleted price inside the heap until it reaches the top, becauseheapqonly pops from index0) completely leak-free andO(1)at the top:- Top is never stale: Whenever
remove_leveldeletes the best level,_discard_stale_top()immediately pops dead prices offheap[0]untilheap[0]is live again (or the heap is empty). Thusbest_level()is always a pureO(1)peek! - Zero duplicate prices (
in_heap): If price200empties while sitting deep inside the heap and a new order arrives at200a moment later,200 in self.in_heapis alreadyTrue— so we reuse that existing heap entry instead of pushing duplicates! - Bounded heap size: If an attacker creates and cancels thousands of unique far-away prices,
len(heap) > 2 * len(levels) + 64triggers anO(P)heapifycompaction. Because at leastP + 64distinct level removals must happen since the last compaction, the rebuild cost isO(1)amortized per removal and heap memory never exceeds2P + 64.
import heapq from collections import OrderedDict BUY, SELL = "BUY", "SELL" LIMIT, MARKET = "LIMIT", "MARKET" class Order: """Single order record; __slots__ cuts per-order Python memory from ~150B to ~72B.""" __slots__ = ("order_id", "trader_id", "side", "price", "remaining") def __init__(self, order_id, trader_id, side, price, quantity): self.order_id = order_id self.trader_id = trader_id self.side = side self.price = price # integer ticks; None for MARKET orders self.remaining = quantity class PriceLevel: """FIFO queue of resting orders at a single tick price with O(1) middle cancel.""" def __init__(self, price): self.price = price self.orders = OrderedDict() # order_id -> Order in strict arrival order self.total_qty = 0 def append(self, order): self.orders[order.order_id] = order self.total_qty += order.remaining def front(self): # Oldest resting order at this price in O(1) return next(iter(self.orders.values())) def remove(self, order): del self.orders[order.order_id] self.total_qty -= order.remaining def is_empty(self): return not self.orders class BookSide: """One side of the book (bids or asks) mapping prices to PriceLevels.""" def __init__(self, is_bid): self.is_bid = is_bid self.levels = {} # price -> non-empty PriceLevel self.heap = [] # min-heap of (-price for bids, +price for asks) self.in_heap = set() # prices currently inside self.heap (at most 1 copy each) def _to_key(self, price): return -price if self.is_bid else price def _to_price(self, key): return -key if self.is_bid else key def _discard_stale_top(self): # Pop dead prices from heap[0] so the heap top is ALWAYS a live level while self.heap: top_price = self._to_price(self.heap[0]) if top_price in self.levels: break heapq.heappop(self.heap) self.in_heap.remove(top_price) def best_level(self): # Guaranteed O(1) worst-case because heap[0] is kept clean on every removal if not self.heap: return None return self.levels[self._to_price(self.heap[0])] def get_or_create(self, price): level = self.levels.get(price) if level is None: level = PriceLevel(price) self.levels[price] = level if price not in self.in_heap: heapq.heappush(self.heap, self._to_key(price)) self.in_heap.add(price) return level def remove_level(self, level): del self.levels[level.price] self._discard_stale_top() # Compact the heap if dead deep entries outnumber live levels by > 2x + 64 if len(self.heap) > 2 * len(self.levels) + 64: self.heap = [self._to_key(p) for p in self.levels] heapq.heapify(self.heap) self.in_heap = set(self.levels) def depth(self, k): # Extract top k live price levels in O(k log P) amortized, then restore them if k <= 0 or not self.levels: return [] popped_live = [] result = [] while len(result) < k and self.heap: key = heapq.heappop(self.heap) price = self._to_price(key) level = self.levels.get(price) if level is None: self.in_heap.remove(price) continue popped_live.append(key) result.append((price, level.total_qty)) for key in popped_live: heapq.heappush(self.heap, key) return result- Top is never stale: Whenever
Code part 2: the matching loop and public engine APIs
Now
MatchingEngineimplements price–time matching in ~70 lines. Whenever an order arrives,_matchrepeatedly inspectsopposite.best_level().front()— the single highest-priority resting order on the other side:- If
trader_idmatches on both sides, self-trade prevention cancels either the resting order (cancel_resting) or the incoming remainder (cancel_incoming) inO(1). - Otherwise they trade
min(order.remaining, resting.remaining)atlevel.price, decrementinglevel.total_qtyimmediately so partial fills keeptopOfBook()exact!
class MatchingEngine: def __init__(self, stp_policy="cancel_resting"): self.bids = BookSide(is_bid=True) self.asks = BookSide(is_bid=False) self.live = {} # order_id -> resting Order for O(1) cancel self.stp_policy = stp_policy # "cancel_resting" or "cancel_incoming" def place_order(self, order_id, side, price, quantity, order_type, trader_id=None): # 1. Validate inputs up front before mutating any book state if side not in (BUY, SELL) or order_type not in (LIMIT, MARKET): return [("rejected", order_id)] if quantity <= 0 or order_id in self.live: return [("rejected", order_id)] if order_type == LIMIT and (price is None or price <= 0): return [("rejected", order_id)] if order_type == MARKET: price = None # 2. Match immediately against crossing levels on the opposite side order = Order(order_id, trader_id, side, price, quantity) events = [("accepted", order_id)] self._match(order, events) # 3. Rest unfilled LIMIT remainder, or cancel unfilled MARKET remainder if order.remaining > 0: if order_type == LIMIT: self._rest(order) events.append(("rested", order_id, order.price, order.remaining)) else: events.append(("cancelled", order_id, order.remaining, "no liquidity")) return events def _crosses(self, incoming, resting_price): if incoming.price is None: # MARKET orders cross every price return True if incoming.side == BUY: return resting_price <= incoming.price return resting_price >= incoming.price def _match(self, order, events): opposite = self.asks if order.side == BUY else self.bids while order.remaining > 0: level = opposite.best_level() if level is None or not self._crosses(order, level.price): break resting = level.front() # Self-trade prevention check in O(1) if order.trader_id is not None and resting.trader_id == order.trader_id: if self.stp_policy == "cancel_incoming": events.append(("cancelled", order.order_id, order.remaining, "self-trade")) order.remaining = 0 break events.append(("cancelled", resting.order_id, resting.remaining, "self-trade")) self._unrest(resting, opposite, level) continue # Execute fill at the resting maker's price fill_qty = min(order.remaining, resting.remaining) events.append(("trade", order.order_id, resting.order_id, level.price, fill_qty)) order.remaining -= fill_qty resting.remaining -= fill_qty level.total_qty -= fill_qty if resting.remaining == 0: self._unrest(resting, opposite, level) def _rest(self, order): side_book = self.bids if order.side == BUY else self.asks side_book.get_or_create(order.price).append(order) self.live[order.order_id] = order def _unrest(self, order, side_book, level): level.remove(order) del self.live[order.order_id] if level.is_empty(): side_book.remove_level(level) def cancel_order(self, order_id): order = self.live.get(order_id) if order is None: return [("cancel_rejected", order_id)] side_book = self.bids if order.side == BUY else self.asks self._unrest(order, side_book, side_book.levels[order.price]) return [("cancelled", order_id, order.remaining, "client")] def top_of_book(self): best_bid = self.bids.best_level() best_ask = self.asks.best_level() return ( (best_bid.price, best_bid.total_qty) if best_bid else None, (best_ask.price, best_ask.total_qty) if best_ask else None, ) def depth(self, k): return self.bids.depth(k), self.asks.depth(k) # Exact camelCase aliases matching the prompt specification placeOrder = place_order cancelOrder = cancel_order topOfBook = top_of_book- If
End-to-end walkthrough of a live order book
Trace our 6-step order sequence starting from an empty book (prices in integer ticks):
1. placeOrder("ord_1", SELL, 250, 6, LIMIT, trader_id="Mina") -> rested ord_1 @250 x6 2. placeOrder("ord_2", SELL, 250, 4, LIMIT, trader_id="Nate") -> rested ord_2 @250 x4 (queued behind ord_1) 3. placeOrder("ord_3", SELL, 252, 5, LIMIT, trader_id="Owen") -> rested ord_3 @252 x5 4. placeOrder("ord_4", BUY, 248, 8, LIMIT, trader_id="Pia") -> rested ord_4 @248 x8 topOfBook() -> bid=(248, 8), ask=(250, 10) # 250 has 6 + 4 = 10 total depth(2) -> ([(248, 8)], [(250, 10), (252, 5)]) 5. placeOrder("ord_5", BUY, 250, 8, LIMIT, trader_id="Quinn") # crosses best ask 250! - Meets front of 250 (ord_1, Mina): trade("ord_5", "ord_1", price=250, qty=6); ord_1 removed - Meets new front of 250 (ord_2, Nate): trade("ord_5", "ord_2", price=250, qty=2); ord_2 has 2 left! - ord_5 remaining == 0 -> done! topOfBook() -> bid=(248, 8), ask=(250, 2) 6. placeOrder("ord_6", BUY, None, 12, MARKET, trader_id="Nate") # market sweep by Nate! - Meets front of 250 (ord_2, ALSO Nate!) -> STP cancels resting ord_2 (qty=2, "self-trade"); 250 removed! - Next best ask is 252 (ord_3, Owen) -> trade("ord_6", "ord_3", price=252, qty=5); 252 removed! - Asks now empty; ord_6 still wants 7 -> cancelled("ord_6", qty=7, "no liquidity") topOfBook() -> bid=(248, 8), ask=None cancelOrder("ord_4") -> cancelled("ord_4", 8, "client"); second cancelOrder("ord_4") -> cancel_rejectedDeep dive 1: preventing timeouts on adversarial inputs
Amortized complexity alone is not enough when a buggy algorithm or malicious trader crafts worst-case inputs. Walk through the five concrete attacks and how we defeat every one:
- The "skip own orders" self-trade trap (
O(N)per order!): Suppose STP tried to skip past a trader's own resting orders to trade with someone behind them. An attacker places100,0001-share asks at250, then sends100,0001-share buys — forcing every buy to walk across100,000skipped orders (10^10steps = minutes of freeze!). Fix: Only support cancel-resting, cancel-incoming, or cancel-both. Every order touched is permanently cancelled or filled, guaranteeingO(1)amortized work per order. - Single-message mega-sweep spike: Resting
100,000tiny orders across the book and firing oneMARKETorder for10,000,000shares isO(1)amortized per resting order, but all100,000fills execute inside a single call (~50 ms latency spike). Fix: Enforce a maximum order quantity, cap max open orders per trader (e.g.,5,000), and apply market-order price collars (rewriting a market order into a limit order capped atbest_opposite_price +/- collar_ticksso one order cannot wipe out the entire book). - Price-level churn at bogus prices: Placing and cancelling orders at
1,000,000distinct far-away prices ($999,999.01,$999,999.02, ...) tries to bloat the heap. Fix: Exchange price bands reject limit prices outside+/- X%of the last trade/reference price (boundingP),in_heapblocks duplicate entries at reused prices, and the2P + 64rebuild rule caps heap size strictly proportional to live levels. - Hash-collision DoS on
orderId: If clients choose raw hash keys (for instance, multiples of2^61 - 1all hash to0in Python!),live[order_id]degrades fromO(1)toO(N). Fix: Edge gateways map(session_id, client_order_id)to a monotonic internal 64-bit integer ID (1, 2, 3, ...) before messages enter the engine. - Expensive
depth(k)queries and message floods: Capk <= 50, servedepth(k)from a downstream market-data replica rather than stalling the matcher thread, and enforce per-session token-bucket rate limits at the gateway.
- The "skip own orders" self-trade trap (
Deep dive 2: multi-threading without breaking determinism
Determinism means the output event stream is a pure mathematical function of the ordered input log — zero
time.now()calls, zero random numbers, and zero lock races inside the matcher. That property lets a backup server process the exact same log and hold an identical order book in RAM.How do we scale across many CPU cores without breaking determinism?
Trading Clients (TCP / FIX / Binary) | | | v v v +---------+ +---------+ +---------+ |Gateway 1| |Gateway 2| |Gateway G| (Parallel threads: TLS/socket I/O, auth, rate limit, +----+----+ +----+----+ +----+----+ schema check, map client ID -> internal ID) \ | / v v v +--------------------------------+ | Single Sequencer | Assigns global monotonic (seq_no, timestamp) | (Lock-Free Ring Buffer) | -> fixes ONE total order for all messages! +---+-----------+------------+---+ | | | v v v Disk WAL Hot Standby Matcher Shards (1 pinned thread per symbol partition) Journal Replicator |-- Thread 0: owns books [AAPL, AMZN, ...] (zero locks!) +-- Thread 1: owns books [MSFT, NVDA, ...] (zero locks!) | v (releases events ONLY once WAL + Standby >= seq_no) Execution Reports & Market-Data Publisher Threads- Pipeline non-matching work onto separate threads (LMAX Disruptor pattern): Socket parsing, authentication, pre-trade risk limits, disk journaling, replication, and market-data fan-out take ~80% of total CPU cycles. Moving all of them onto parallel producer/consumer threads around a ring buffer (a pre-allocated circular array in shared L3 cache) leaves the matcher thread doing only pure in-memory pointer updates (~100–500 ns/op in C++).
- Shard horizontally by instrument (
symbol_id % M): Books forAAPLandMSFTshare zero order state, soMsingle-threaded matchers run completely in parallel with zero locks while keeping each book 100% deterministic. (Cross-symbol account margin checks run conservatively at the gateway before sequencing or on a dedicated post-sequencer risk stage.) - Never put fine-grained locks inside one order book: Letting two threads lock individual price levels of the same symbol means thread scheduling decides which taker grabs a maker first — destroying price–time priority and making crash replay produce different trades than live trading!
Crash recovery, low-latency optimizations, and trade-offs
Exact crash recovery: - Hold outputs until durable: Downstream gateways release
"accepted"and"trade"packets to clients only after both the local disk journal and the synchronous hot standby confirmseq_no. If the primary server loses power, the standby already has the identical deterministic book and takes over in milliseconds; for a cold restart, loading the latest 40 MB snapshot (taken off the standby so the primary never pauses!) plus replaying a few seconds of journal restores state in < 1 second.Going from Python (
~1e5 ops/s) to C++/Java HFT (~5e6+ ops/s): - Zero hot-path heap allocation: Pre-allocate a flat pool ofOrderstructs at startup so garbage collection /mallocnever causes tail-latency spikes. - Intrusive doubly linked lists: Storeprev_idxandnext_idxdirectly inside theOrderstruct (eliminating hash-node indirection). - Tick-indexed flat array + 64-bit hierarchical bitmap: Inside a bounded price band (say65,536ticks), storePriceLevel[65536]in a flat array (O(1)lookup, zero tree pointers!) with a 2-level hierarchy of 64-bit integers (uint64_t), where a single CPUTZCNT/LZCNTbit-scan instruction finds the next non-empty price level in 1–2 nanoseconds (O(1))!Summary of key trade-offs:
- Balanced BST (
std::map) vs. lazy heap (heapq) vs. tick bitmap array: BST gives worst-caseO(log P)everywhere; Python's heap givesO(1)top-of-book andO(log P)amortized updates using standard-library tools; a tick bitmap givesO(1)everything inside a fixed price band at the cost of pre-allocated tick slots. - Single-threaded matcher per symbol + ring-buffer pipeline vs. per-level locks: Caps a single ultra-hot instrument at one CPU core's speed (~millions of ops/s in C++), in exchange for zero lock contention, exact FIFO fairness, and byte-for-byte deterministic replay.
- Cancel-resting / cancel-incoming STP vs. skipping own orders: Cancels an order instead of trading past it, guaranteeing
O(1)amortized matching time and immunity to linear-scan DoS attacks.
- Balanced BST (
Intuition & how it works
Imagine a busy ticket-exchange counter with two lines of waiting customers: buyers (bids) arranged from highest offered price down to lowest, and sellers (asks) arranged from lowest asking price up to highest — and within each exact price line, whoever stood in line earliest stays at the front (price–time priority). When a new buyer walks up willing to pay 250 ticks for 8 tickets, the clerk only needs to look at the single person standing at the very front of the cheapest seller line: if that seller asks 250 or less, they trade immediately at the seller's posted price; if any tickets remain unfilled and no affordable seller is left, the buyer steps to the back of the 250 buyer line.
A naive implementation stores all 1,000,000 open orders in one list (or scans orders to find the best price, sum quantities, or cancel an ID). At 100,000 operations per second, your entire CPU budget is 10 microseconds per operation — scanning 1,000,000 orders takes several milliseconds, missing the latency target by 100x to 1,000x and freezing the exchange on a single cancel storm.
Instead, we combine three O(1) / O(log P) structures (live hash map order_id -> Order, BookSide price heap + price -> PriceLevel map across P active price levels, and an OrderedDict doubly linked FIFO queue with cached total_qty inside each PriceLevel). Walk through our sample trace (prices in integer ticks):
- Mina places
SELL 6 @ 250 (LIMIT)(ord_1), then Nate placesSELL 4 @ 250 (LIMIT)(ord_2): Ask level250holds[ord_1(6) -> ord_2(4)]in arrival order withtotal_qty = 10, and250sits atasks.heap[0].topOfBook()reads(None, (250, 10))inO(1). - Quinn places
BUY 8 @ 250 (LIMIT)(ord_5):250 <= 250crosses!ord_5matches6against front orderord_1(ord_1is unlinked from250andliveinO(1)), then matches2againstord_2(ord_2.remainingdrops to2,level.total_qtydrops to2).ord_5is completely filled. - Nate places
BUY 12 (MARKET)(ord_6):ord_6meets the front of ask250, which isord_2— also owned by Nate! Self-trade prevention cancels restingord_2inO(1), emptying level250(askspops250off the heap); if another seller (Owenwith5 @ 252) rests behind it,ord_6fills5at252and cancels its remaining7shares ("no liquidity") because market orders never rest. - Lookup or cancel any ID (
cancelOrder): Looking uporder_idinlivejumps straight to itsOrderand unlinks it from itsPriceLevelinO(1)with zero scanning.
Key trade-offs
- Balanced search tree vs. lazy-deletion heap vs. tick-indexed bitmap for price levels. A balanced tree (
std::mapin C++,TreeMapin Java) gives worst-caseO(log P)insert and delete,O(1)cached best price, andO(log P + k)depth(k). Python's standard library lacks a balanced tree, so a binary min-heap with lazy deletion (cleaning dead prices when they reachheap[0], deduplicating via anin_heapset, and compacting whenlen(heap) > 2P + 64) achievesO(1)topOfBook(),O(log P)amortized updates, andO(k log P)depth(k). Ultra-low-latency C++ engines inside a bounded price band use a flat array indexed by tick plus a 64-bit hierarchical bitmap (TZCNTinstruction) for trueO(1)worst-case operations, trading away unbounded price ranges. - Doubly linked FIFO (
OrderedDict/ intrusive pointers) vs. array queue with tombstones. Doubly linked nodes unlink a cancelled middle order immediately inO(1)and reclaim memory right away. Marking cancelled slots inside a flat array is simpler, but a heavy cancel storm leaves thousands of dead tombstones in RAM until fills eventually walk past them. - Self-trade prevention (STP): cancel-resting vs. cancel-incoming vs. cancel-both. Cancel-resting lets an aggressive new order keep sweeping deeper liquidity while pulling the trader's stale quote; cancel-incoming protects passive market-making quotes; cancel-both is conservative. Crucially, all three permanently finish an order every iteration (
O(1)amortized), whereas "skip own orders" degrades toO(N)per incoming order under adversarial self-stacking. - Market orders: sweep-to-empty vs. price-collar protection. Sweeping every level until filled matches the textbook specification, whereas production exchanges often apply price collars (capping sweeps within
+/- Nticks of the best price) to protect traders from fat-finger wipeouts and bound single-message latency spikes. - Single-threaded matcher per instrument + ring buffer vs. multi-threaded locks inside one book. Giving one dedicated thread exclusive ownership of a book (and pipelining network I/O, journaling, and replication around a lock-free ring buffer — a fixed-size circular queue in shared memory — while sharding different symbols across cores) avoids all lock contention and guarantees deterministic replay. Locking individual price levels inside one book introduces OS thread-scheduling races that break FIFO fairness and make crash recovery non-deterministic.
- Python prototype vs. zero-allocation C++/Java. Python with
__slots__handles~1e5 ops/scleanly on a modern core, but cyclic garbage collection and dynamic object allocation create tail-latency spikes; production engines pre-allocate fixedOrderobject pools in C++ or Java so p99.99 latency stays flat in single-digit microseconds.
Common mistakes
- Using floating-point numbers for prices: Binary float rounding (
100.10 + 0.20 = 100.30000000000001) splits orders at the same economic price into separatePriceLevelbuckets; always represent prices in integer ticks. - Linear scans anywhere on the hot path: Scanning orders to cancel an ID, scanning price keys to find the best bid/ask, or summing a level's orders inside
topOfBook()violates the 10-microsecond budget. - Using a plain Python
dictas a FIFO queue: Repeatedly deleting the oldest key from the front of adictleaves internal dummy slots at the start of the hash table, makingnext(iter(d))degrade towardO(N)over time; usecollections.OrderedDict(which links live nodes in a doubly linked list). - Forgetting to update
level.total_qtyon partial fills or leaving0-quantity levels alive: CausestopOfBook()anddepth(k)to report phantom liquidity or stale$0-quantity levels. - Executing trades at the incoming taker's price instead of the resting maker's price: If an ask rests at
250and a buyer bids255, the trade must print at250, giving price improvement to the buyer. - Allowing unfilled market-order remainders to rest on the book: Market orders have no limit price and must cancel any remainder when opposite liquidity runs out.
- Lazy heap deletion without duplicate suppression (
in_heap) or size compaction: Repeatedly placing and cancelling away from top-of-book leaks unbounded stale entries in the heap. - Reading wall-clock time (
time.time()) or using multi-threaded locks inside the matcher: Destroys determinism so replaying the input journal produces a different trade history from live execution.
Follow-up questions
- How would you support modifying an existing order (amend / cancel-replace) while preserving exchange priority rules? Split modifications into two cases based on standard exchange fairness rules: reducing quantity at the same price keeps the order's exact place in the FIFO queue (
O(1)lookup inlive, subtract the delta fromorder.remainingandlevel.total_qty, or remove the order if the new quantity is<= 0). Changing the price or increasing the quantity forfeits time priority because otherwise a trader could cut in line ahead of others with fresh size — implement it atomically ascancelOrderfollowed byplaceOrder(O(log P)if it opens a new level, immediately matching if the new price crosses), emitting a"replaced"event so clients can track the order transition cleanly. - How would you add Immediate-or-Cancel (IOC) and Fill-or-Kill (FOK) orders, especially when self-trade prevention is active? An IOC order is simply a limit order that never rests: run
_matchup to its limit price and immediately emit("cancelled", order_id, order.remaining, "ioc")for any leftover quantity instead of calling_rest. A FOK order must either fill 100% immediately or do nothing at all without mutating the book: pre-scan crossing price levels from best outward before executing any fills. Without self-trade prevention, summinglevel.total_qtyacross crossing levels takesO(levels crossed); withcancel_restingSTP, maintain atrader_qtymap (trader_id -> sum_qty, updated inO(1)on rest/fill/cancel) inside eachPriceLeveland addlevel.total_qty - level.trader_qty.get(order.trader_id, 0)at each crossing level so the pre-check still runs inO(levels crossed)without touching individual orders! - How do you test and verify that the matching engine is both bug-free and 100% deterministic? Build a tiny ~30-line reference oracle that keeps all resting orders in a flat list sorted by
(-price if BUY else price, arrival_seq)on every step, and run randomized property tests (10,000+ generated sequences mixing limit/market orders, partial fills, unknown cancels, and self-trade collisions) asserting thatMatchingEngineemits the exact same event list,topOfBook(), anddepth(k)at every step while checking all five book invariants (best_bid < best_ask,total_qty == sum(remaining),len(heap) == len(in_heap)). To verify determinism in staging and production, replay the recorded input journal through a second process (or the hot standby) and compare a rolling cryptographic/XXH64 hash of the emitted event stream — any divergence of even one tick or order ID flags a non-deterministic bug immediately.
Follow-up questions
- How would you support modifying an existing order (amend / cancel-replace) while preserving exchange priority rules?
- How would you add Immediate-or-Cancel (IOC) and Fill-or-Kill (FOK) orders, especially when self-trade prevention is active?
- How do you test and verify that the matching engine is both bug-free and 100% deterministic?
Similar questions
- In-Memory User Communication Manager
- Thread-Safe C++ Object Pool Refactoring
- Single-Channel Two-Party Call Controller
- SQL Semantics Multiple-Choice Reasoning
- Selecting Python, Java, or C++ Across Trading Services
- Net Portfolio Deltas by Asset Group
More Akuna Capital interview questions
- Multi-Tier Weighted Cache With TTL Expiration Hard
- Single-Channel Two-Party Call Manager With Custom Exceptions Medium
- Hexadecimal String Bitwise AND Medium Pro
- Maximum Node Value in an Unordered Binary Tree Medium Pro
- Single-Channel Two-Party Call Controller Medium Pro
- SQL Semantics Multiple-Choice Reasoning Medium Pro
- Selecting Python, Java, or C++ Across Trading Services Hard Pro
- Net Portfolio Deltas by Asset Group Medium Pro
- Optimal Multi-Symbol Trading Plan Medium Pro
- Fewest Operations to Reach Target Integer Medium Pro