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) where side is BUY or SELL and type is LIMIT or MARKET
  • cancelOrder(orderId) to pull an open resting order from the book
  • topOfBook() returning the current best bid and best ask as (price, totalQuantity)
  • depth(k) returning the top k aggregated 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 LIMIT quantity rests on the book, whereas MARKET orders 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 roughly 100,000 (10^5) operations per second.
  • Achieve O(log P) insertion and cancellation (where P is the count of active price levels) and O(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 and O(1) top-of-book in bounded memory.
  • Core matching & API implementation: Provide clean, executable code for placeOrder, cancelOrder, topOfBook, and depth(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

  1. 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 (P denotes 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 255 against a resting ask at 250 pays 250).
    • 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:

    1. Uncrossed book: Best bid price is strictly < best ask price (whenever a bid is >= an ask, they match immediately before anything rests).
    2. Exact level totals: Every price level's total_qty equals the exact sum of its live orders' remaining quantities.
    3. No ghost levels or orders: Every resting order appears in live and in one PriceLevel, and empty PriceLevel objects are removed immediately.
    4. Strict FIFO within a level: Orders inside any price level remain in exact arrival order.
    5. Deterministic execution: Feeding the exact same sequence of inputs always emits the exact same sequence of events.
  2. 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 ms
    

    Three conclusions drive our data-structure choices:

    1. The 10-microsecond budget rules out every O(N) or O(P) scan. Scanning 1,000,000 orders to cancel an ID or summing 100,000 orders at the best price takes milliseconds — 100x to 1,000x over budget.
    2. All 1,000,000 orders fit comfortably in RAM (~100–300 MB) on a single server, so the hot path never waits on disk reads.
    3. Logging every input message (6.4 MB/s) is cheap, allowing crash recovery via periodic 40 MB snapshots plus deterministic replay.
  3. Core APIs and the deterministic event stream

    We support the exact prompt signatures (with an optional trader_id to 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 cancelled
    

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

  4. 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, and O(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] <- TAIL
    

    Why each component is chosen carefully:

    • PriceLevel.orders as an OrderedDict (hash map + doubly linked list): Appending a new order at the back is O(1), peeking at the oldest order at the front is O(1), and unlinking a cancelled order in the middle by order_id is O(1). (Beware a subtle Python trap: a plain dict preserves insertion order, but repeatedly deleting from the front leaves tombstones at the start of its internal table, turning next(iter(d)) into a quadratic slowdown! OrderedDict maintains real doubly linked pointers so front pops stay O(1) forever.)
    • PriceLevel.total_qty: Maintained incrementally (+qty on rest, -qty on fill or cancel), making topOfBook() a single integer read instead of summing every order at that price.
    • BookSide price index: In C++ (std::map) or Java (TreeMap), a balanced binary search tree keeps P active price levels sorted in O(log P) insert/delete. Because Python's standard library has no balanced BST, we pair a levels dict (price -> PriceLevel) with a binary heapq using 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 tail
    placeOrder (creates a brand-new price level) O(log P) Pushes 1 new price into the P-level heap
    cancelOrder(orderId) O(1) (or O(log P) amortized if level empties) O(1) lookup in live + O(1) FIFO unlink; heap cleanup only when the last order at that price leaves
    Matching F resting orders across L emptied levels O(F + L log P) amortized Each 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 cached total_qty
    depth(k) O(k log P) amortized Pops k live prices from the heap and pushes them back (O(log P + k) with a C++/Java tree)
    Space O(N + P) Stores N live orders and at most ~2P + 64 heap integers
  5. Code part 1: orders, FIFO price levels, and one side of the book

    Let's write Order, PriceLevel, and BookSide cleanly. Pay special attention to how BookSide makes lazy deletion (leaving a deleted price inside the heap until it reaches the top, because heapq only pops from index 0) completely leak-free and O(1) at the top:

    1. Top is never stale: Whenever remove_level deletes the best level, _discard_stale_top() immediately pops dead prices off heap[0] until heap[0] is live again (or the heap is empty). Thus best_level() is always a pure O(1) peek!
    2. Zero duplicate prices (in_heap): If price 200 empties while sitting deep inside the heap and a new order arrives at 200 a moment later, 200 in self.in_heap is already True — so we reuse that existing heap entry instead of pushing duplicates!
    3. Bounded heap size: If an attacker creates and cancels thousands of unique far-away prices, len(heap) > 2 * len(levels) + 64 triggers an O(P) heapify compaction. Because at least P + 64 distinct level removals must happen since the last compaction, the rebuild cost is O(1) amortized per removal and heap memory never exceeds 2P + 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
    
  6. Code part 2: the matching loop and public engine APIs

    Now MatchingEngine implements price–time matching in ~70 lines. Whenever an order arrives, _match repeatedly inspects opposite.best_level().front() — the single highest-priority resting order on the other side:

    • If trader_id matches on both sides, self-trade prevention cancels either the resting order (cancel_resting) or the incoming remainder (cancel_incoming) in O(1).
    • Otherwise they trade min(order.remaining, resting.remaining) at level.price, decrementing level.total_qty immediately so partial fills keep topOfBook() 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
    
  7. 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_rejected
    
  8. Deep 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:

    1. 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 places 100,000 1-share asks at 250, then sends 100,000 1-share buys — forcing every buy to walk across 100,000 skipped orders (10^10 steps = minutes of freeze!). Fix: Only support cancel-resting, cancel-incoming, or cancel-both. Every order touched is permanently cancelled or filled, guaranteeing O(1) amortized work per order.
    2. Single-message mega-sweep spike: Resting 100,000 tiny orders across the book and firing one MARKET order for 10,000,000 shares is O(1) amortized per resting order, but all 100,000 fills 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 at best_opposite_price +/- collar_ticks so one order cannot wipe out the entire book).
    3. Price-level churn at bogus prices: Placing and cancelling orders at 1,000,000 distinct 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 (bounding P), in_heap blocks duplicate entries at reused prices, and the 2P + 64 rebuild rule caps heap size strictly proportional to live levels.
    4. Hash-collision DoS on orderId: If clients choose raw hash keys (for instance, multiples of 2^61 - 1 all hash to 0 in Python!), live[order_id] degrades from O(1) to O(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.
    5. Expensive depth(k) queries and message floods: Cap k <= 50, serve depth(k) from a downstream market-data replica rather than stalling the matcher thread, and enforce per-session token-bucket rate limits at the gateway.
  9. 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
    
    1. 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++).
    2. Shard horizontally by instrument (symbol_id % M): Books for AAPL and MSFT share zero order state, so M single-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.)
    3. 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!
  10. 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 confirm seq_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 of Order structs at startup so garbage collection / malloc never causes tail-latency spikes. - Intrusive doubly linked lists: Store prev_idx and next_idx directly inside the Order struct (eliminating hash-node indirection). - Tick-indexed flat array + 64-bit hierarchical bitmap: Inside a bounded price band (say 65,536 ticks), store PriceLevel[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 CPU TZCNT/LZCNT bit-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-case O(log P) everywhere; Python's heap gives O(1) top-of-book and O(log P) amortized updates using standard-library tools; a tick bitmap gives O(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.

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):

  1. Mina places SELL 6 @ 250 (LIMIT) (ord_1), then Nate places SELL 4 @ 250 (LIMIT) (ord_2): Ask level 250 holds [ord_1(6) -> ord_2(4)] in arrival order with total_qty = 10, and 250 sits at asks.heap[0]. topOfBook() reads (None, (250, 10)) in O(1).
  2. Quinn places BUY 8 @ 250 (LIMIT) (ord_5): 250 <= 250 crosses! ord_5 matches 6 against front order ord_1 (ord_1 is unlinked from 250 and live in O(1)), then matches 2 against ord_2 (ord_2.remaining drops to 2, level.total_qty drops to 2). ord_5 is completely filled.
  3. Nate places BUY 12 (MARKET) (ord_6): ord_6 meets the front of ask 250, which is ord_2 — also owned by Nate! Self-trade prevention cancels resting ord_2 in O(1), emptying level 250 (asks pops 250 off the heap); if another seller (Owen with 5 @ 252) rests behind it, ord_6 fills 5 at 252 and cancels its remaining 7 shares ("no liquidity") because market orders never rest.
  4. Lookup or cancel any ID (cancelOrder): Looking up order_id in live jumps straight to its Order and unlinks it from its PriceLevel in O(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::map in C++, TreeMap in Java) gives worst-case O(log P) insert and delete, O(1) cached best price, and O(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 reach heap[0], deduplicating via an in_heap set, and compacting when len(heap) > 2P + 64) achieves O(1) topOfBook(), O(log P) amortized updates, and O(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 (TZCNT instruction) for true O(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 in O(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 to O(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 +/- N ticks 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/s cleanly on a modern core, but cyclic garbage collection and dynamic object allocation create tail-latency spikes; production engines pre-allocate fixed Order object 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 separate PriceLevel buckets; 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 dict as a FIFO queue: Repeatedly deleting the oldest key from the front of a dict leaves internal dummy slots at the start of the hash table, making next(iter(d)) degrade toward O(N) over time; use collections.OrderedDict (which links live nodes in a doubly linked list).
  • Forgetting to update level.total_qty on partial fills or leaving 0-quantity levels alive: Causes topOfBook() and depth(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 250 and a buyer bids 255, the trade must print at 250, 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 in live, subtract the delta from order.remaining and level.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 as cancelOrder followed by placeOrder (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 _match up 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, summing level.total_qty across crossing levels takes O(levels crossed); with cancel_resting STP, maintain a trader_qty map (trader_id -> sum_qty, updated in O(1) on rest/fill/cancel) inside each PriceLevel and add level.total_qty - level.trader_qty.get(order.trader_id, 0) at each crossing level so the pre-check still runs in O(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 that MatchingEngine emits the exact same event list, topOfBook(), and depth(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

Similar questions

More Akuna Capital interview questions

All 26 Akuna Capital questions →