Low-Latency C++ Order Matching Engine
Hard · System Design · Software Engineer · Online Assessment
Prompt
Design an in-memory limit order book and matching engine in C++ for a single electronic trading exchange. The entire book resides in RAM on a single host without distributed consensus on the matching path, and the engine must sustain tens of thousands to hundreds of thousands of order operations per second at microsecond-scale per-order latency with minimal tail jitter (strictly bounded below a few milliseconds).
Incoming messages represent new orders and cancellations:
- Each incoming order provides at least
order_id(unique identifier),side(BUYorSELL),price,quantity, arrivaltimestamp(or monotonic sequence number), andtype. - The book maintains two sides governed by strict price-time priority: bids (buy orders) ranked from highest to lowest price, and asks (sell orders) ranked from lowest to highest price, with ties at an identical price broken in FIFO arrival order.
- When a new order arrives, the engine crosses it against eligible resting orders on the opposite side in price-time order, supports both partial and complete fills, emits trade execution events (carrying
trade_id, executionprice, matchedquantity, maker/takerorder_ids, andtimestamp), and rests any remaining quantity on the book if permitted by the order's lifecycle rules. - At minimum, the engine must support
LIMITorders and cancellation byorder_id, with a clean extension path forMARKET,IOC(Immediate-or-Cancel),FOK(Fill-or-Kill),GTC(Good-Till-Cancel), andPostOnlyinstructions.
State any scoping assumptions explicitly up front—such as whether one process serves a single instrument or shards thousands of symbols, whether prices sit on a bounded integer tick grid or arbitrary levels, whether trades execute at the resting maker's price or aggressor's price, whether crash recovery must reconstruct exact book state, and how self-trade prevention (CancelResting, CancelIncoming, CancelBoth) behaves.
Scope & Expectations
- Matching rules & order-type extensions: Define exact price-time execution semantics, partial-fill queue priority, trade pricing, self-match prevention, and how the core loop extends from
LIMITandorder_idcancellation toMARKET,IOC,FOK,GTC, andPostOnly. - C++ data structures & memory layout: Propose concrete, low-jitter C++ structures for sorted bid/ask price levels, per-level FIFO queues,
O(1)cancellation byorder_id, and preallocated memory management that avoids heap allocation stalls on the hot path. - Concurrency, durability & crash recovery: Explain how multiple network threads feed the matching core safely without lock contention, and how snapshotting or journaling restores exact book state on restart while guaranteeing orders are applied once and trades are never duplicated.
- C++ APIs & complexity trade-offs: Sketch clean C++ interfaces for submitting orders, cancelling by ID, querying best bid/ask and depth, and consuming output events, accompanied by average, worst-case, and amortized time/space complexity analysis.
Step-by-step walkthrough
Clarify rules, vocabulary, and scope
An order book is a live ledger of open buy and sell offers for one tradable instrument (called a symbol, such as
AAPL). Offers to buy are called bids (highest price goes first), offers to sell are called asks (lowest price goes first), and the gap between the highest bid and lowest ask is the spread. An order already waiting in the book is a resting (maker) order because it adds liquidity; an incoming order that immediately trades against a resting order is an aggressor (taker) order because it removes liquidity.A matching engine is small in code size, yet unforgiving: one ambiguous rule (which price a trade prints at, whether a partial fill loses its place in line, or how an all-or-nothing order behaves) creates a financial bug, and one stray heap allocation on the hot path ruins microsecond tail latency. Start by locking down the exact rules.
Scoping assumptions locked down up front
Design dimension Chosen assumption Instrument scope Multi-instrument (~2,000 symbols) inside one process. Each symbol's book belongs to one dedicated shard thread, with symbols partitioned across engine shards. Tick representation Fixed tick grid, where one tick equals the minimum price increment (such as 0.01 = 1integer tick). Prices useint64_tinteger ticks inside a venue-enforced price collar (band) of 16,384 ticks (±8,192ticks around a reference price); out-of-band orders are rejected.Supported instructions LIMIT(trade at a worst acceptable price or better) and Cancel byorder_idas baseline, extending cleanly toMARKET(fill immediately at best available levels),IOC(Immediate-or-Cancel: fill available liquidity now and drop the rest),FOK(Fill-or-Kill: fill 100% immediately or cancel 100%),GTC / DAY(Good-Till-Cancel / Day), andPostOnly(maker-only: reject if crossing).Execution price rule Every fill executes at the resting (maker) order's price. If an ask rests at 250.10and a buyer submits a limit at250.15, the trade prints at250.10.Crash persistence Exact state recovery: zero acknowledged orders and zero published trades may be lost or duplicated across restarts. Self-trade handling Self-match prevention (STP) keyed by account_idblocks same-account orders from trading against one another under a configurable policy:CancelResting(default),CancelIncoming, orCancelBoth.Functional requirements
- Validate incoming orders, cross eligible opposite-side liquidity in strict price-time priority (best price wins first; equal-price orders execute in earliest-arrival sequence), emit trade records, and rest or cancel any leftover shares.
- Cancel an existing resting order by
order_idin O(1) time. - Serve queries for top-of-book (best bid and best ask) and top-N price depth.
Non-functional requirements
- Throughput: 500,000 messages/second across the venue; 150,000 messages/second sustained peak on the single busiest symbol (with 1 ms microbursts up to 1,000,000 messages/second).
- Latency: inside the engine (ring pop to ring push), target p50 < 1 us and p99 < 10 us, staying well under the low-millisecond end-to-end bound.
- Low jitter: zero locks, zero system calls, and zero heap allocations (
new/malloc) on the steady-state matching path. - Determinism: feeding the exact same sequence of stamped input messages always produces the exact same book state and trade IDs.
Back-of-the-envelope numbers
Before picking data structures, translate throughput and memory into concrete nanoseconds and megabytes so we see what can fit in CPU cache and RAM.
Workload & per-message latency budget Symbols 2,000 total across 8 engine threads (shards) Venue peak throughput 500,000 msgs/s (~50% NewOrder, ~45% CancelOrder, ~5% other) Note: most resting orders end in Cancel, so Cancel is just as hot as Add! Busiest single symbol 150,000 msgs/s -> 1 s / 150,000 = 6.7 us average budget per message 1 ms microburst (1,000,000 msgs/s) 1.0 us budget per message before input queue grows Input SPSC ring buffer 65,536 slots x 64 B = 4 MB (a 2,000-msg 1 ms burst uses ~3% of the ring) RAM & CPU cache footprint Order struct 64 B (aligned to 1 CPU cache line) Max live resting orders 2M venue-wide -> preallocate 4M pool slots x 64 B = 256 MB total OrderId -> Order* hash table 8M slots (load factor <= 0.5) x 16 B = 128 MB total PriceLevel array (bounded band) 16,384 ticks/side x 32 B = 512 KB/side = 1 MB/symbol x 2,000 symbols = 2 GB total (hot inner levels stay warm in L1/L2 cache) 3-layer non-empty bitmap 16,384 bits = 2 KB + 32 B + 8 B per side (fits in L1 cache!) Durability journal bandwidth Sequenced input log 500,000 msgs/s x 64 B = 32 MB/s peak sequential disk/network write One 6.5-hour trading day 50,000 msgs/s average x 64 B x 23,400 s = ~75 GB/dayTwo physical facts jump out from this math:
- At 1 us (1,000 ns) per message during a burst, algorithm constants dominate. One L3/DRAM cache miss costs ~70-100 ns, a contended mutex lock costs hundreds of nanoseconds, and a slow
mallocor OS page fault costs microseconds. Every routine operation must touch a tiny, fixed number of preallocated cache lines. - All book state fits comfortably in RAM (< 3 GB), and journal bandwidth (32 MB/s) is trivial for an NVMe SSD. What breaks durability is per-message latency (a disk
fsynctakes tens of microseconds to milliseconds), so disk flushing must be decoupled from the matching loop.
- At 1 us (1,000 ns) per message during a burst, algorithm constants dominate. One L3/DRAM cache miss costs ~70-100 ns, a contended mutex lock costs hundreds of nanoseconds, and a slow
API, data model, and a concrete matching trace
Network gateway threads decode wire bytes into fixed-size, plain-data C++ structs with zero
std::stringor heap pointers so messages copy cleanly across ring buffers.using Price = int64_t; // integer ticks (e.g., 100.02 at 0.01 tick = 10002); NEVER float/double using Qty = int64_t; using OrderId = uint64_t; using AccountId = uint32_t; enum class Side : uint8_t { Buy, Sell }; enum class OrdType : uint8_t { Limit, Market }; enum class Tif : uint8_t { GTC, Day, IOC, FOK }; enum class Stp : uint8_t { CancelResting, CancelIncoming, CancelBoth }; enum class Reason : uint8_t { UserCancel, IocRemainder, FokNotFillable, SelfMatch, PostOnlyWouldCross, BadPrice, BadQty, DuplicateId, UnknownOrder, PoolFull }; struct NewOrder { // 64 bytes: copied by value through SPSC ring uint64_t seq; // monotonic sequence stamped by the owning shard thread uint64_t timestamp_ns; // gateway/shard arrival timestamp in nanoseconds OrderId order_id; Price price; // ignored for OrdType::Market Qty qty; uint32_t symbol; AccountId account; Side side; OrdType type; Tif tif; bool post_only; }; struct CancelOrder { uint64_t seq; uint64_t timestamp_ns; OrderId order_id; uint32_t symbol; AccountId account; }; struct Trade { uint64_t trade_id; // deterministic per-book counter uint64_t in_seq; // sequence number of the triggering aggressor message uint64_t timestamp_ns; // inherited from the triggering message (never wall-clock inside matcher!) Price price; // ALWAYS the resting (maker) order's price Qty qty; OrderId maker_order_id; OrderId taker_order_id; AccountId maker_account; AccountId taker_account; Qty maker_leaves; // remaining quantity on the maker after this fill Qty taker_leaves; // remaining quantity on the taker after this fill Side aggressor_side; }; struct LevelView { Price price; Qty qty; uint32_t orders; }; class EventSink { // zero-overhead template in production; interface shown for clarity public: virtual ~EventSink() = default; virtual void accepted(uint64_t in_seq, OrderId id) = 0; virtual void trade(const Trade& t) = 0; virtual void cancelled(uint64_t in_seq, OrderId id, Qty cancelled_qty, Reason why) = 0; virtual void rejected(uint64_t in_seq, OrderId id, Reason why) = 0; }; class OrderBook { // single-symbol book, touched by its owning shard thread only public: void on_new(const NewOrder& m); void on_cancel(const CancelOrder& m); std::optional<Price> best_bid() const; std::optional<Price> best_ask() const; int depth(Side s, LevelView* out, int max_levels) const; };Inside
OrderBook, each restingOrderis aligned to a single 64-byte cache line and embeds its own doubly linked list pointers (an intrusive linked list, meaning the list links live directly inside theOrderobject instead of in a separately allocated wrapper node):struct PriceLevel; struct alignas(64) Order { // 1 order = 1 exact 64-byte cache line OrderId id = 0; // 8 B uint64_t seq = 0; // 8 B: arrival order -> strict time priority AccountId account = 0; // 4 B Side side = Side::Buy; // 1 B (+ 3 B compiler padding) Price price = 0; // 8 B Qty remaining = 0; // 8 B Order* prev = nullptr; // 8 B: previous order at same price level Order* next = nullptr; // 8 B: next order at same price level (or next free slot in pool) PriceLevel* level = nullptr;// 8 B: owning price level for O(1) counter updates }; static_assert(sizeof(Order) == 64, "Order must fit in one 64-byte cache line"); struct PriceLevel { // 32 bytes: 2 price levels per cache line Order* head = nullptr; // oldest resting order (matched first) Order* tail = nullptr; // newest resting order (appended here) Qty total = 0; // total resting quantity at this price (O(1) depth queries) uint32_t count = 0; // number of resting orders at this price };Note why
alignas(64)is essential: without it, a 64-byte struct only has 8-byte alignment, sostd::vector<Order>can start at a 16-byte-aligned address and cause every singleOrderto straddle two cache lines.Concrete walkthrough of a multi-level fill
Suppose the tick size is 0.01 (
25010ticks = 250.10). Two sell orders are resting on the ask side: Order#41sells400 @ 25010, and Order#42sells500 @ 25012. Now Order#55arrives:BUY LIMIT 700 @ 25012, GTC.Before Order #55 arrives: ASK 25012: [ #42: qty=500 ] (total=500) ASK 25010: [ #41: qty=400 ] <-- best_ask = 25010 Incoming: in_seq=2040, NEW #55 BUY LIMIT 700 @ 25012 GTC (acct=7, ts=171500000800) Step 1: Best ask is 25010 <= limit 25012 -> crosses! Match min(700, 400) = 400 shares against maker #41 at maker's price 25010. #41 remaining becomes 0 -> unlinked; ASK 25010 empties -> LevelBitmap jumps best_ask to 25012. Step 2: Next best ask is 25012 <= limit 25012 -> crosses! Match min(300, 500) = 300 shares against maker #42 at maker's price 25012. #42 remaining becomes 200 (stays at head of ASK 25012, keeping its original time priority!). #55 remaining becomes 0 -> done. Emitted output events: out_seq=8101 ACCEPTED id=55 out_seq=8102 TRADE trade_id=601 px=25010 qty=400 maker=41 taker=55 maker_leaves=0 taker_leaves=300 out_seq=8103 TRADE trade_id=602 px=25012 qty=300 maker=42 taker=55 maker_leaves=200 taker_leaves=0 out_seq=8104 BOOK_DELTA ASK 25010 -> 0, ASK 25012 -> 200High-level architecture and threading model
Where parallelism belongs. If multiple network threads locked and mutated the same order book concurrently, mutex contention would sit right on the hot path, and arrival order would depend on unpredictable OS lock scheduling. Instead, we separate the unit of matching (one book = one thread, zero locks) from the unit of parallelism (2,000 symbols sharded across 8 pinned engine threads).
Clients (binary TCP order-entry sessions) | | | +------v------+ +------v------+ +------v------+ | Gateway 1 | | Gateway 2 | | Gateway 3 | Decode wire bytes, session seq | (net thread)| | (net thread)| | (net thread)| dedup, basic risk, route by symbol +--+-------+--+ +--+-------+--+ +--+-------+--+ | | | | | | Dedicated SPSC ring per v v v v v v (gateway, engine shard) pair +-----------------------+ +-----------------------+ | Engine Shard A | ... | Engine Shard H | Pinned core, busy-polling: | - Stamps in_seq & ts | | - Stamps in_seq & ts | 1) Pop input msg | - Owns ~250 books, | | - Owns ~250 books, | 2) Push to journal ring | order pool & index | | order pool & index | 3) Match in RAM (no locks!) +-----+-----------+-----+ +-----+-----------+-----+ 4) Push events to output ring | inputs | outputs | | v v v v +-----------+ +-----------------------------------+ | Journal | | Output Publisher Thread | -> Sends execution reports & market | Thread | | Releases event ONLY once | data once input is durable +-----+-----+ | event.in_seq <= durable_seq | | +-----------------------------------+ | Group fsync (every ~200 us) + replicate v NVMe Journal ----------> Hot Standby Host (replays identical input stream in RAM)Lock-free SPSC rings and avoiding false sharing. Rather than using a multi-producer queue (which requires expensive atomic
compare_exchangeinstructions), every(Gateway, Engine Shard)pair gets its own SPSC (Single-Producer Single-Consumer) ring buffer, a fixed-size circular array where only one thread writestail_and only one thread writeshead_.A classic hardware trap here is false sharing: CPU caches move memory in 64-byte blocks called cache lines, so if
head_andtail_sit in the same 64-byte block, every producer push invalidates the consumer core's L1 cache line even though they touch different variables. Putting each cursor on its ownalignas(64)cache line and caching the remote cursor locally eliminates cache-line ping-pong:template <typename T, size_t N> class SpscRing { static_assert((N & (N - 1)) == 0, "N must be a power of two for bitmask wrap"); public: bool try_push(const T& item) { // called ONLY by the single producer const uint64_t t = tail_.load(std::memory_order_relaxed); if (t - head_cache_ == N) { // looks full -> refresh cached head_ head_cache_ = head_.load(std::memory_order_acquire); if (t - head_cache_ == N) return false; // genuinely full -> apply backpressure } buf_[t & (N - 1)] = item; tail_.store(t + 1, std::memory_order_release); return true; } bool try_pop(T& out) { // called ONLY by the single consumer const uint64_t h = head_.load(std::memory_order_relaxed); if (h == tail_cache_) { // looks empty -> refresh cached tail_ tail_cache_ = tail_.load(std::memory_order_acquire); if (h == tail_cache_) return false; } out = buf_[h & (N - 1)]; head_.store(h + 1, std::memory_order_release); return true; } private: alignas(64) std::atomic<uint64_t> head_{0}; // owned by consumer cache line uint64_t tail_cache_ = 0; // consumer-private shadow copy alignas(64) std::atomic<uint64_t> tail_{0}; // owned by producer cache line uint64_t head_cache_ = 0; // producer-private shadow copy alignas(64) T buf_[N]; };Consistent read queries without locking the book. Off-thread readers must never inspect a book mid-match. For
best_bid()/best_ask(), the engine publishes a tiny snapshot after each message using a seqlock (a version counter incremented to an odd number before writing fields and to an even number afterward; readers check that the version was even and unchanged, or read from double-buffered slots). Full depth comes either from the market-data delta stream or by sending a query message through the shard's input ring.Deep dive 1: one matching loop for all order types, FOK, and STP
Instead of writing five separate matching functions, notice that
LIMIT,MARKET,IOC,FOK,DAY, andPostOnlyall share the same price-time matching loop and differ only in: 1. A pre-check before mutating the book (may it cross? can it fill completely?), and 2. Leftover disposition after matching stops (rest in book vs. cancel remainder).Order type Pre-check before matching Matching limit price Unfilled leftover LIMIT(GTC/DAY)Price in band; reserve pool slot Order's priceRests at tail of its price level ( DAYswept at close)LIMIT(IOC)Price in band Order's priceCancelled ( IocRemainder)MARKETNone Far edge of opposite band (collar protection) Cancelled ( IocRemainder; never rests without a price)LIMIT(FOK)Price in band + reachable qty >= m.qtyOrder's priceNone (feasibility check guaranteed 100% fill) PostOnlyPrice in band + does not cross best opposite None (rejected if crossing) Full quantity rests as maker void OrderBook::on_new(const NewOrder& m) { if (m.qty <= 0) { out_.rejected(m.seq, m.order_id, Reason::BadQty); return; } if (m.type == OrdType::Limit && !in_band(m.price)) { out_.rejected(m.seq, m.order_id, Reason::BadPrice); return; } if (index_.find(m.order_id) != nullptr) { out_.rejected(m.seq, m.order_id, Reason::DuplicateId); return; } const bool may_rest = (m.type == OrdType::Limit) && (m.tif == Tif::GTC || m.tif == Tif::Day); if (may_rest && !pool_.has_free()) { // check capacity BEFORE mutating the book! out_.rejected(m.seq, m.order_id, Reason::PoolFull); return; } BookSide& opp = (m.side == Side::Buy) ? asks_ : bids_; Price limit = m.price; if (m.type == OrdType::Market) { // treat Market as Limit at the collar boundary limit = (m.side == Side::Buy) ? (opp.base + band_ - 1) : opp.base; } // Phase 1: Type-specific pre-checks (book is still completely untouched). if (m.post_only && opp.best >= 0 && crosses(m.side, limit, opp.base + opp.best)) { out_.rejected(m.seq, m.order_id, Reason::PostOnlyWouldCross); return; } if (m.tif == Tif::FOK && fillable_qty(opp, m, limit) < m.qty) { out_.cancelled(m.seq, m.order_id, m.qty, Reason::FokNotFillable); return; } // Phase 2: Common price-time matching loop. out_.accepted(m.seq, m.order_id); MatchResult r = match(opp, m, limit); if (r.left == 0) return; // Phase 3: Dispose of any unfilled remainder. if (r.self_match_stop) { out_.cancelled(m.seq, m.order_id, r.left, Reason::SelfMatch); } else if (may_rest) { rest(m, r.left); } else { out_.cancelled(m.seq, m.order_id, r.left, Reason::IocRemainder); } } void OrderBook::on_cancel(const CancelOrder& m) { Order* o = index_.find(m.order_id); if (o == nullptr || o->account != m.account) { out_.rejected(m.seq, m.order_id, Reason::UnknownOrder); return; } Qty cancelled_qty = o->remaining; remove(o); // O(1) intrusive unlink + pool release out_.cancelled(m.seq, m.order_id, cancelled_qty, Reason::UserCancel); }Inside
match, the loop always inspectsopp.levels[opp.best].head, guaranteeing best price first and earliest arrival first:OrderBook::MatchResult OrderBook::match(BookSide& opp, const NewOrder& m, Price limit) { Qty left = m.qty; while (left > 0 && opp.best >= 0) { Price level_price = opp.base + opp.best; if (!crosses(m.side, limit, level_price)) break; Order* maker = opp.levels[opp.best].head; if (maker->account == m.account) { // Self-Match Prevention (STP) if (stp_ == Stp::CancelIncoming) { return {left, true}; } out_.cancelled(m.seq, maker->id, maker->remaining, Reason::SelfMatch); remove(maker); // shrinks resting book by 1 order if (stp_ == Stp::CancelBoth) { return {left, true}; } continue; } Qty fill_qty = std::min(left, maker->remaining); left -= fill_qty; maker->remaining -= fill_qty; maker->level->total -= fill_qty; out_.trade(Trade{ next_trade_id_++, m.seq, m.timestamp_ns, level_price, fill_qty, maker->id, m.order_id, maker->account, m.account, maker->remaining, left, m.side }); if (maker->remaining == 0) { remove(maker); } // Note: if maker->remaining > 0, `maker` stays at `head` and keeps its time priority! } return {left, false}; }Why FOK must check before mutating (and respect STP). You cannot partially match a FOK and "roll back" once trades have entered the output stream. And you cannot naively sum
PriceLevel::totalif the incoming account already has resting orders on the opposite side, because STP will cancel or stop on those self-orders rather than trading against them! Instead,fillable_qtydry-runs reachability without modifying anything. Because one thread owns the book, nothing can change betweenfillable_qtyandmatch:Qty OrderBook::fillable_qty(const BookSide& opp, const NewOrder& m, Price limit) const { const bool has_self_orders = account_resting_count(opp, m.account) > 0; Qty sum = 0; int64_t slot = opp.best; while (slot >= 0 && sum < m.qty && crosses(m.side, limit, opp.base + slot)) { if (!has_self_orders) { // fast path: O(crossable levels), no order walk sum += opp.levels[slot].total; } else { // slow path: respect STP order-by-order for (Order* o = opp.levels[slot].head; o != nullptr; o = o->next) { if (o->account == m.account) { if (stp_ != Stp::CancelResting) return sum; // matching stops right here continue; // CancelResting skips self qty } sum += o->remaining; if (sum >= m.qty) return sum; } } slot = next_level(opp, slot); } return sum; }Proof that STP always terminates. Every iteration of
while (left > 0 && opp.best >= 0)either exits immediately (!crosses,CancelIncoming,CancelBoth), removes theheadresting order viaCancelResting, or executes a trade offill_qty >= 1(sinceqty <= 0is rejected up front) that either removesmakeror drivesleftto0. Thus every non-exiting iteration strictly decreases the finite count of resting orders onopp, guaranteeing termination in at mostN_opp + 1steps.Deep dive 2: O(1) cancel and constant-time price level jumps
Nearly half of all real-world exchange messages are cancellations. To make
on_cancel,rest, and finding the next best price level all strict O(1) with zero heap allocations, each book combines four structures:1) Preallocated Open-Addressing Hash Index (load <= 0.5, backward-shift delete): order_id 1042 ------> Order* (points directly into OrderPool) 2) OrderPool (contiguous preallocated array of 64 B cache-aligned Order slots + free list): [ slot 0 ] [ slot 1: Order #1042 ] [ slot 2 ] ... 3) PriceLevel Array (direct tick indexing: slot = price - base) + Intrusive FIFO Queue: levels[102]: head ---> [ #1040 ] <---> [ #1042 ] <---> [ #1049 ] <--- tail ^ Unlinking #1042 is just two pointer writes: #1040->next = #1049 and #1049->prev = #1040 (no scan, no delete!) 4) Hierarchical 64-ary LevelBitmap (1 bit per price slot -> O(1) jump to next non-empty tick): Toy 4-bit-per-word illustration when Ask slot 1 empties and next Ask is at slot 10: Layer 1 (summary, 1 bit per 4-slot group): [ 0 | 0 | 1 | 0 ] -> group 2 is non-empty! Layer 0 (1 bit per tick slot 0..15): [0000|0000|0010|0000] -> bit 10 is set! Instead of scanning 9 empty PriceLevels, 2 CPU bit-scan instructions jump straight to 10!In 64-bit C++, three 64-bit bitmap layers (
64 * 64 * 64 = 262,144slots, easily covering our 16,384-tick band) find the next non-empty bid or ask in at most threestd::countr_zero/std::countl_zeroinstructions (single-cycletzcnt/lzcntinstructions on x86-64):inline uint64_t bit(unsigned b) { return uint64_t{1} << b; } inline uint64_t bits_above(unsigned b) { return ~((uint64_t{2} << b) - 1); } // bits b+1..63 (0 when b==63) inline uint64_t bits_below(unsigned b) { return bit(b) - 1; } // bits 0..b-1 (0 when b==0) class LevelBitmap { public: explicit LevelBitmap(size_t n) : l0_((n + 63) / 64, 0), l1_((n + 4095) / 4096, 0) {} void set(size_t i) { l0_[i >> 6] |= bit(i & 63); l1_[i >> 12] |= bit((i >> 6) & 63); l2_ |= bit(i >> 12); } void clear(size_t i) { l0_[i >> 6] &= ~bit(i & 63); if (l0_[i >> 6] != 0) return; l1_[i >> 12] &= ~bit((i >> 6) & 63); if (l1_[i >> 12] != 0) return; l2_ &= ~bit(i >> 12); } int64_t first_at_or_above(size_t i) const { // used by Asks (lowest price >= i) size_t w0 = i >> 6, w1 = i >> 12; uint64_t m = l0_[w0] & ~bits_below(i & 63); if (m != 0) return static_cast<int64_t>((w0 << 6) + std::countr_zero(m)); m = l1_[w1] & bits_above(w0 & 63); if (m != 0) return lowest_in_l0((w1 << 6) + std::countr_zero(m)); m = l2_ & bits_above(static_cast<unsigned>(w1)); if (m == 0) return -1; size_t w1b = std::countr_zero(m); return lowest_in_l0((w1b << 6) + std::countr_zero(l1_[w1b])); } // last_at_or_below(i) mirrors this for Bids using std::countl_zero (63 - countl_zero(m)). private: int64_t lowest_in_l0(size_t w0) const { return static_cast<int64_t>((w0 << 6) + std::countr_zero(l0_[w0])); } std::vector<uint64_t> l0_; // 1 bit per price tick std::vector<uint64_t> l1_; // 1 bit per 64-tick l0 word uint64_t l2_ = 0; // 1 bit per 4,096-tick l1 word };With
OrderPool,LevelBitmap, and the intrusive pointers inOrder, bothrestandunlinkexecute in pure constant-time pointer arithmetic:void OrderBook::rest(const NewOrder& m, Qty qty) { Order* o = pool_.alloc(); // pops free list head in O(1); capacity checked in on_new BookSide& own = (m.side == Side::Buy) ? bids_ : asks_; int64_t slot = m.price - own.base; PriceLevel& lvl = own.levels[slot]; *o = Order{m.order_id, m.seq, m.account, m.side, m.price, qty, lvl.tail, nullptr, &lvl}; if (lvl.tail != nullptr) lvl.tail->next = o; else lvl.head = o; lvl.tail = o; lvl.total += qty; lvl.count += 1; own.nonempty.set(static_cast<size_t>(slot)); if (own.best < 0 || (own.side == Side::Buy ? slot > own.best : slot < own.best)) { own.best = slot; } index_.insert(o->id, o); inc_account_resting(own, o->account); } void OrderBook::unlink(Order* o) { PriceLevel& lvl = *o->level; if (o->prev != nullptr) o->prev->next = o->next; else lvl.head = o->next; if (o->next != nullptr) o->next->prev = o->prev; else lvl.tail = o->prev; lvl.total -= o->remaining; lvl.count -= 1; dec_account_resting((o->side == Side::Buy) ? bids_ : asks_, o->account); if (lvl.count > 0) return; BookSide& own = (o->side == Side::Buy) ? bids_ : asks_; int64_t slot = o->price - own.base; own.nonempty.clear(static_cast<size_t>(slot)); if (slot == own.best) { own.best = (own.side == Side::Buy) ? own.nonempty.last_at_or_below(static_cast<size_t>(slot)) : own.nonempty.first_at_or_above(static_cast<size_t>(slot)); } }Explicit comparison:
std::mapvs. Array + Hierarchical BitmapDimension std::map<Price, PriceLevel>(Red-Black Tree)Bounded Array + 3-Layer LevelBitmapInsert into existing / new level O(log L) tree walk + heap node alloc on new level O(1) array index + 3 bitwise ORs; zero alloc Best level empties -> find next best Amortized O(1) tree rebalance + node deleteO(1) ( <= 364-bittzcnt/lzcntops); zero freeBest bid / ask lookup O(1) ( map.begin())O(1) (cached bestinteger slot)Cache behavior ~ log2(L)dependent pointer chases (cache misses)Flat contiguous memory; bitmap fits inside L1 cache Memory & price range O(active levels); handles arbitrary sparse prices Fixed 1 MB/symbol; requires venue price collar + rare recentering Selection: For microsecond-scale HFT/exchange targets with a venue price collar, Array + LevelBitmap wins decisively by eliminating O(log L) pointer chasing and heap jitter. (When building incrementally under time pressure, start with a clean
BookSideabstraction backed byOrderPooland intrusive lists, usingstd::mapfirst if needed and swapping inLevelBitmaponce correctness tests pass.)Deep dive 3: tail-latency jitter, durability, and exactly-once recovery
Eliminating non-algorithmic jitter on the hot path
- Zero steady-state heap allocation:
OrderPool,PriceLevelvectors, open-addressing hash tables, and SPSC rings are sized once at startup. - Zero page faults and fewer TLB misses: call
mlockall(MCL_CURRENT | MCL_FUTURE)and write zero to every page at startup so the OS maps physical RAM up front, backed by 2 MB huge pages for the 256 MBOrderPool. - Zero OS scheduler preemption: pin each engine shard thread to an isolated CPU core (
isolcpus/pthread_setaffinity_np) and busy-poll its input rings; steer NIC interrupts onto gateway cores. - Zero syscalls or text formatting: engine threads never write sockets, files, or
printf; binary events go straight into rings.
Durability without
fsyncon the matching pathBecause each shard is a deterministic state machine (it never reads the system clock, never branches on pointer addresses or randomized hash iteration order, and derives
trade_idandout_seqfrom in-book counters), we never need to write full order-book mutations to disk on every trade. Instead, we persist sequenced 64-byte inputs plus periodic snapshots taken off-primary by the hot standby:Engine Thread (us scale): [Pop in_seq=101] -> [Match in RAM] -> [Push out_seq=508 to Output Ring] | | Journal Thread (batch ~200 us): +-> [Append 101..180, NVMe fsync + Standby ACK] -> durable_seq = 180 | Output Publisher Thread: Waits until 101 <= durable_seq, then sends!Matching stays speculative in RAM at sub-microsecond speed, so subsequent orders see the updated book immediately. Meanwhile, the Output Publisher holds acknowledgments and trade prints until
in_seq <= durable_seq(both locallyfsynced and acknowledged by the hot standby). Clients add ~200 us of group-commit wait on external confirmation, while no client ever sees a trade that a crash could erase.Crash recovery and exactly-once guarantees
- Fast failover: promote the hot standby, which has already applied every input up to
durable_seqin RAM. - Cold restart from disk: load the latest standby snapshot (book state at
in_seq = S,next_trade_id,next_out_seq) and replay journaled inputs within_seq > Sthroughon_new/on_cancel. At 150k msgs/s over a 5-minute snapshot interval (45M messages) and ~2M msgs/s in-memory replay speed, cold recovery finishes in ~23 seconds. - Two sequence markers prevent duplicates end-to-end:
- Input deduplication: each client session carries a strictly increasing client sequence number checked at the gateway (catching network retries even after an order filled and left the live
index_), andin_seq <= Sprevents re-applying pre-snapshot journal entries. - Output deduplication: deterministic replay regenerates the exact same
out_seqandtrade_idvalues; the publisher and downstream clearing/market-data consumers drop anyout_seq <= last_seen_out_seq.
- Input deduplication: each client session carries a strictly increasing client sequence number checked at the gateway (catching network retries even after an order filled and left the live
- Zero steady-state heap allocation:
Complexity analysis, scaling, and failure modes
Let
Lbe active price levels,Bbe ticks in the collar band (16,384), andkbe resting orders removed (filled or STP-cancelled) during one incoming order.Operation Array + LevelBitmap(chosen)std::mapalternativeWhy Add resting order (no cross) O(1) expected, O(1) level update O(log L) + O(1) expected hash Direct price - baseindex + 3 bitmap bits + O(1) hash insert (load <= 0.5).Match sweeping kordersO(k + 1) per call; O(1) amortized O(k + 1) per call; O(log L) amortized Each step unlinks head in O(1) and jumps empty levels via <= 364-bit word ops.Cancel by order_idO(1) expected O(1) expected + amortized O(1) rebalance Open-addressing lookup + 2-pointer intrusive unlink + O(1) bitmap clear if empty. Query best_bid/best_askO(1) worst-case O(1) worst-case Reads cached bestslot (or seqlock snapshot off-thread).Query top- NdepthO(N) worst-case O(N) worst-case Jumps across Nnon-empty levels viaLevelBitmap::first_at_or_above.FOK feasibility check O(crossable levels) without self-orders; O(walked orders) with self-orders Same Uses PriceLevel::totalfast path wheneveraccount_resting_count == 0.Space per symbol O(live orders + B) (~1 MB + orders) O(live orders + L) Fixed tick array trades 1 MB/symbol for zero allocations and O(1) indexing. Why matching is O(1) amortized. One large aggressive order sweeping
k = 10,000resting orders takes O(10,000) work (~100-300 us) and emits 10,000 trades. However, each passive order enters the book a single time and leaves the book at most a single time (via full execution or cancellation), while at most one partially filled maker remains per incoming order. Across any sequence ofMmessages, total loop iterations are at most2M, giving O(1) amortized work per message. (Unfillable FOK scans are bounded separately by thePriceLevel::totalfast path and gateway rate limits.)Scaling bottlenecks and failure handling
- 10-100x surge on a single hot symbol: one core's per-message budget drops to ~670 ns (10x) or ~67 ns (100x). Give that symbol its own dedicated shard thread, batch ring pops, replace 64-bit pointers in
Orderwith 32-bit pool indices (shrinkingOrderto 32-48 bytes so twice as many fit in L1/L2 cache), and offload all risk/serialization to gateways. One symbol's continuous order book cannot be split across cores without sacrificing strict price-time priority. - 10,000+ symbols: 1 MB x 10,000 = 10 GB of level arrays. Keep wide arrays for liquid symbols and use narrower collars or a
std::mapfallback for illiquid long-tail symbols. - Graceful failure handling: full input rings trigger gateway backpressure (never blocking the matcher);
PoolFullcleanly rejects new resting orders while cancels continue draining the book; slow journal disks stalldurable_seqand halt trading cleanly if persistence exceeds a safety timeout rather than publishing unpersisted fills.
- 10-100x surge on a single hot symbol: one core's per-message budget drops to ~670 ns (10x) or ~67 ns (100x). Give that symbol its own dedicated shard thread, batch ring pops, replace 64-bit pointers in
Intuition & how it works
Picture an order book as two orderly lines at a busy wholesale fruit market: one line of buyers holding signs with the highest price they will pay (bids, sorted highest price first, earliest arrival first at ties) and one line of sellers holding signs with the lowest price they will accept (asks, sorted lowest price first, earliest arrival first at ties). Whenever a new buyer walks up willing to pay at least what the front seller is asking, an immediate trade happens at that waiting seller's posted price (the maker price), and any leftover shares either trade with the next seller in line or join the buyer line.
A textbook implementation wraps std::map<double, std::list<Order>> in a shared mutex lock, allocates list and hash nodes with new on every order, and flushes to disk with fsync before acknowledging each message. At 150,000 messages per second on a single symbol (6.7 microseconds per message on average, shrinking to 1 microsecond during bursts), mutex contention across network threads, red-black tree pointer chasing, heap-allocator stalls, and millisecond disk flushes miss the latency budget by two to three orders of magnitude. Instead, we assign each symbol to one pinned, lock-free thread, store prices as integer ticks (fixed smallest price increments, such as 1 cent = 1) in a preallocated array with a hierarchical bitmap (a compact multi-layer bitset that finds the next non-empty price tick in three CPU bit-scan instructions), link orders inside preallocated 64-byte object pool slots via an intrusive doubly linked list (where prev and next pointers live inside Order itself), and batch disk writes off the matching thread.
Walk through four tiny events with a 0.01 tick size (25010 ticks = 250.10):
1. Event 1 (SELL 400 @ 25010, Order #41): Ask side is empty, so #41 takes a preallocated 64-byte slot from the pool, sits at the head of asks[25010], sets bit 25010 in the ask bitmap, and updates best_ask = 25010.
2. Event 2 (SELL 500 @ 25012, Order #42): #42 rests at asks[25012] and sets bit 25012; best_ask stays 25010.
3. Event 3 (BUY 700 @ 25012, Order #55): #55 checks best_ask (25010 <= 25012), fills 400 shares against #41 at maker price 25010, unlinks #41, clears bit 25010, and uses the bitmap to jump best_ask over empty tick 25011 straight to 25012. Still needing 300 shares, #55 fills 300 against #42 at 25012, leaving #42 at the front of asks[25012] with 200 remaining and its original time priority intact.
4. Event 4 (CANCEL #42): A preallocated open-addressing hash table (a flat array hash map with no pointer-chained buckets) maps 42 directly to #42's Order*, unlinks its prev/next pointers in O(1), clears bit 25012 (best_ask = -1), and returns the slot to the pool's free list with zero heap calls.
Key trade-offs
- Bounded tick array + hierarchical bitmap vs.
std::map<Price, PriceLevel>. Indexing a flat array byprice - basemakes level lookup and insertion strict O(1) with zero heap allocations, and a 3-layer 64-bit bitmap finds the next non-empty price in at most three bit-scan instructions. The trade-off is fixed memory (~1 MB per symbol) and enforcing a venue price collar (a bounded window of allowed ticks around a reference price) that must occasionally be recentered, whereasstd::maphandles unbounded sparse prices automatically at the cost of O(log L) pointer-chasing cache misses and node allocations. - Intrusive doubly linked list + object pool vs.
std::list+std::unordered_map. Storingprev,next, andlevelinside preallocatedalignas(64) Orderobjects lets cancel-by-ID unlink any middle order in two pointer writes with zeronew/deletejitter. The cost is writing custom pool and open-addressing hash-table code and enforcing a hard maximum capacity (PoolFull) instead of growing dynamically. - Single-threaded book sharded by symbol vs. multi-threaded locks on one book. Routing all messages for a symbol through lock-free SPSC (Single-Producer Single-Consumer) ring buffers (fixed circular queues with one writer and one reader on separate cache lines) to a single owning core gives deterministic price-time ordering and zero lock contention. The trade-off is that one ultra-hot symbol cannot scale beyond a single CPU core's instruction budget.
- Speculative RAM matching + input journaling vs. synchronous
fsyncper order. Because the matcher is deterministic, logging compact 64-byte sequenced inputs (in_seq) in ~200-microsecond group commits and taking periodic snapshots on a hot standby reconstructs exact state without stalling the matcher on disk I/O. External acknowledgments and trade prints wait in the output publisher untilin_seq <= durable_seq, adding ~200 microseconds to client ack latency while keeping matching itself under a microsecond. - Lock-free seqlock top-of-book reads vs. reader-writer locks. Publishing best bid/ask via a seqlock (an atomic version number bumped odd before writing and even after writing so readers retry if torn) keeps readers completely off the engine's critical path, at the minor cost that off-thread queries may see state a few microseconds behind the latest match.
Common mistakes
- Using
floatordoublefor prices. Binary floating point cannot represent0.01or0.10exactly (0.1 + 0.2 != 0.3), causing two orders at the same decimal price to land in different price buckets and breaking deterministic replay across compilers or CPU architectures. - Printing trades at the aggressor's limit price instead of the resting maker's price, or stripping time priority from a partially filled resting order by pushing it to the back of its price queue.
- Forgetting
alignas(64)on a 64-byteOrderstruct. A 64-byte struct without explicit 64-byte alignment is only 8-byte aligned, so heap arrays often start at a 16-byte offset and force every singleOrderto split across two CPU cache lines. - Implementing FOK (Fill-or-Kill) as "match first, roll back if short" or summing
PriceLevel::totalblindly when self-match prevention (STP) is active, which either leaks false trade events or lets self-orders trick FOK into half-filling. - Claiming O(1) cancel while mapping
order_idonly to aPrice, which still requires an O(N) linear scan through thousands of orders queued at a busy price level, or scanning empty array ticks linearly when the best price level drains. - Placing
headandtailcursors of an SPSC queue on the same cache line, causing false sharing where producer and consumer cores invalidate each other's L1 cache on every push and pop. - Calling
malloc,free,fsync,gettimeofday, or string-formatting loggers inside the engine thread, any one of which introduces multi-microsecond to millisecond tail-latency spikes.
Follow-up questions
- Which core invariants must hold under every stress scenario, and how does your architecture enforce them? Six invariants protect both correctness and latency: (1)
in_seqstamped by the owning shard thread defines deterministic time priority, (2) every trade prints at the resting maker's price while partial fills retain their queue head position, (3) every non-exiting matching iteration removes one resting order so loops always terminate, (4)FOKandPostOnlyvalidate reachability before mutating book state, (5) steady-state operations never allocate heap memory or acquire locks, and (6) external publishers hold acknowledgments and fills untilin_seq <= durable_seq. Naming which invariant a failure or surge scenario threatens keeps every trade-off concrete. - If message volume on a single hot instrument jumps by 10x to 100x—or the engine scales to 10,000+ instruments—what bottlenecks hit first and how do you adapt? On one ultra-hot symbol at 10x–100x (
1.5Mto15Mmsgs/s), per-message CPU budget shrinks to~670 nsand~67 ns, making cache-miss latency the primary bottleneck: pin that symbol exclusively to its own dedicated core, pop SPSC ring entries in batches, and replace 64-bit pointers inOrderwith 32-bit pool indices so twice as many orders stay warm in L1/L2 cache (since splitting one continuous order book across cores would break strict price-time priority). Across10,000+instruments, static memory (10,000 x 1 MB = 10 GBof price arrays) hits first, so reserve wide flat tick arrays for liquid symbols while using narrower tick collars or a sparsestd::maplayout for illiquid long-tail books, partitioning journals per shard. - How do you enforce self-trade prevention when an incoming aggressor meets a resting order from the same account, and why is your matching loop guaranteed to terminate? Each iteration inspects
maker = opp.levels[opp.best].headfirst. Whenmaker->account == m.account,CancelIncomingexits immediately,CancelBothunlinksmakerand exits, andCancelRestingunlinksmaker(shrinking the finite opposite-side book by one order) before continuing; when accounts differ, positive quantity validation (qty > 0) guarantees a fill ofmin(left, maker->remaining) >= 1that either unlinksmakeror reducesleftto0and exits. Because every continuing step strictly decreases the finite count of resting opposite-side orders and never inserts mid-loop, termination is guaranteed withinN_resting + 1steps—unlike a buggy "skip in place" approach that would spin forever on the head order. - When an incoming FOK order comes from an account that already has resting liquidity at crossable prices, why does summing per-level volume fail and how do you compute true fillable quantity? Suppose Ask
25010holds60shares from Account7ahead of40shares from Account9(level.total = 100), and Account7sendsFOK BUY 100 @ 25010underCancelResting: summinglevel.totalsees100 >= 100and approves the order, yet actual matching cancels Account7's60shares and fills only40from Account9, violating FOK's all-or-nothing rule after emitting irreversible trades! To prevent this,fillable_qtychecks per-account resting counts: whenaccount_resting_count > 0on the opposite side, it walks orders in priority sequence—skipping same-account shares underCancelRestingand halting immediately at any same-account order underCancelIncomingorCancelBoth—while retaining the fastO(crossable levels)level.totalsum whenever the incoming account has zero resting opposite-side orders. - Why are IEEE-754 floating-point types unsafe for order-book prices, and what exact numeric representation should replace them? Binary
floatanddoublecannot represent base-10 fractions such as0.01or0.10exactly (0.1 + 0.2 != 0.3), so parsing or rounding drift can map identical decimal prices into different buckets or alter deterministic replay across compilers and CPU instruction sets. Instead, gateways parse wire decimals directly into signed 64-bit integer ticks (int64_t, where1 tick = tick_size, rejecting off-grid prices), store quantities asint64_t, and compute trade notional (price * qty) using exact 64-bit or__int128integer arithmetic, formatting decimals only at external edges. - Tracing a single order along the critical path, why can your C++ implementation sustain microsecond-scale latency with minimal tail jitter? Following one message from ingress to egress: the pinned shard core busy-polls an L1-cached SPSC ring with zero locks or syscalls, computes the price slot via
price - baseinO(1), updates at most three 64-bitLevelBitmapwords using single-cycletzcnt/lzcntinstructions, splices two intrusive pointers inside a preallocatedalignas(64) OrderPoolslot, probes a flat open-addressing hash map kept at<= 0.5load factor, and writes fixed-size binary events to an output ring. Steady-state adds and cancels touch a tiny constant number ofmlocked, huge-page-backed cache lines with zeronew/deletecalls, multi-level sweeps performO(1)amortized work per order, and diskfsynchappens asynchronously in ~200-microsecond group-committed batches off the matching core.
Follow-up questions
- Which core invariants must hold under every stress scenario, and how does your architecture enforce them?
- If message volume on a single hot instrument jumps by 10x to 100x—or the engine scales to 10,000+ instruments—what bottlenecks hit first and how do you adapt?
- How do you enforce self-trade prevention when an incoming aggressor meets a resting order from the same account, and why is your matching loop guaranteed to terminate?
- When an incoming FOK order comes from an account that already has resting liquidity at crossable prices, why does summing per-level volume fail and how do you compute true fillable quantity?
- Why are IEEE-754 floating-point types unsafe for order-book prices, and what exact numeric representation should replace them?
- Tracing a single order along the critical path, why can your C++ implementation sustain microsecond-scale latency with minimal tail jitter?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System