We are asked to engineer a low-latency order matching engine with deterministic replay, focusing on data structures, concurrency control, risk checks, and audit logging.
We must produce an answer that explains the design, probably including:
- Overview: what is an order matching engine, typical requirements (low latency, deterministic replay, risk checks, audit logging).
- Data structures: how to store orders (price levels, order books). Possibly use price-time priority. Use efficient structures: e.g., for each side (bid/ask) a map from price to a queue of orders, and a tree (or skip list) to maintain sorted prices. Or use an array of price levels if price range is bounded. Use lock-free or concurrent structures for high concurrency.
- Concurrency control: need to handle multiple threads submitting orders, matching, andpossibly multiple matching engines? Typically, matching engines are single-threaded for deterministic order processing, but we can use techniques like sharding (by symbol) to parallelize. However deterministic replay suggests we need to be able to reproduce exactly the same sequence of state changes given the same input. So we must have a single thread of execution or a deterministic scheduler. Common approach: use a single thread (or event loop) that processes all incoming orders sequentially, thus deterministic. For scalability, we can have multiple matching engines each handling a different instrument (sharding). Then we need concurrency control between threads submitting orders to the same engine? Possibly orders arrive via network, we have an acceptor thread that pushes to a lock-free queue consumed by the matching engine thread. That ensures deterministic order of events. For low latency, we minimize locks and copying. Use lock-free queues between acceptor and matcher. But within the matching engine, we can process orders sequentially, so no concurrency issues.
- Deterministic replay: we need to log all inputs and state changes in a way that allows replay. Typically, use an event log: record each order submission, modification, cancellation, and each match. The replay can reconstruct the state by re-applying events. We can also use snapshotting periodically. For audit, we need an immutable log. Possibly use a write-ahead log (WAL) or append-only log that records events in order. We'll need to ensure that logs are written before state changes? For replay we need to be able to recover after crash. Could use replication: primary-backup. But deterministic replay may be for debugging or audit; we can also use a log that is periodically flushed.
- Risk checks: before an order is accepted, we need to check various risk limits: position limits, order size limits, margin requirements, etc. These checks must be atomic relative to order acceptance. In a single-threaded matcher, we can maintain account state and check. But if we want low latency, we might want to pre-check or use in-memory caches. We need to integrate risk checks as part of order processing pipeline: after order received, before adding to book, perform checks. If fails, reject and log. Also need to handle cancels and modifications, which may also have risk implications (e.g., reducing position). Also need to handle market data risk? Possibly also order validation (e.g., valid price, quantity, etc.)
- Audit logging: record all events with timestamps, order IDs, account IDs, etc. Must be tamper-evident, maybe cryptographic signatures or hash-chains. We need to handle high throughput: avoid blocking main processing on disk writes. Use a separate logging thread that consumes from a lock-free queue and writes to disk asynchronously, but we need to ensure that logs are persisted before acknowledging? For audit, we might want to ensure logs are durable. Can use group commit or fsync periodically. But for low latency, we might relax durability to some extent (e.g., write to page cache and sync less frequently). But for regulatory, we need strong durability. Possibly use two-phase: first log to in-memory circular buffer, then flush async. Or use a separate logging system like Kafka, but that adds latency. We'll need to balance.
We need to provide a design, maybe with pseudocode or architecture diagrams. The question is "Engineer a low-latency order matching engine with deterministic replay: data structures, concurrency control, risk checks, and audit logging." It may expect a detailed technical answer.
Let's outline:
-
Introduction: define order matching engine, key requirements: low latency (sub-microsecond to microseconds), deterministic replay (ability to reproduce exact state for debugging, recovery, audit), risk checks (pre-trade and post-trade), audit logging (immutable record). Also high throughput (many orders per second).
-
System Architecture:
- Network front-end: receives orders from clients via FIX, binary protocol, etc.
- Order Gateway: validates protocol, assigns sequence numbers, does initial deduplication, pushes to a lock-free queue.
- Matching Engine: single-threaded event loop that processes orders in order of their arrival sequence numbers (deterministic). It maintains order book per instrument, matches orders, sends fills and updates.
- Risk Engine: can be integrated in the gateway or as separate microservice. For low latency, we want risk checks within the matching engine thread to avoid cross-thread delays; but risk checks may be complex (e.g., checking account balances) that could cause latency. Could use in-memory risk cache with fast reads, and pre-load risk limits. Use atomic operations within the same thread.
- Audit Logger: a separate thread that consumes events from a lock-free queue and writes to persistent storage. Use a ring buffer or disruptor pattern to minimize lock contention. The matching engine appends events to the audit log queue non-blocking (if full, may drop or backpressure). We'll need flow control.
-
Data Structures:
- Order Book: For each trading symbol, we have two sides: bids (buy) and asks (sell). Each side is a map from price to an order list. Prices are discrete (ticks) if using integer price levels. We can use an array if price range limited (e.g., for stocks with tick size 0.01 and min/max price). Or a balanced binary tree (e.g., red-black tree) or skip list for O(log n) insertion and O(1) best price retrieval. Use a priority queue for best price? Actually we need to quickly get best price and also iterate from best to worst for matching. For bids, best is highest price; for asks, best is lowest. So we need a structure that allows:
- Insert order at price level (if price level not exists, create).
- Remove order (by order ID) from its price level.
- Match: iterate from best price level, matching orders FIFO (price-time priority). So we need to maintain FIFO queue at each price level.
- Implementation: Use a std::map or tree for price levels, storing pointer to a deque or linked list of orders. For lock-free, we could use atomic operations but complex. Simpler: since matching engine is single-threaded, we can use normal data structures without locks. That is efficient.
- Order ID: globally unique, possibly per order. Orders need to be inserted, canceled, modified. We need to quickly locate an order in the book for cancel/modify. Maintain a hash map (unordered_map) from order ID to a pointer to the order and its price level and side. So when cancel arrives, we can find order and remove from book. This map is only accessed by the matching thread, so no concurrency issues. But careful about memory reclamation: when order is fully filled or canceled, we need to erase from map. Since single-threaded, safe.
- Use cache-friendly data structures: price levels stored in a tree, but we can also use a fixed array if price range is small. For equities, price range might be large but number of active levels moderate. Use a custom skip list or a flat array of price levels sorted, with a pointer to the best price. For fast insertion/removal, we need O(log n). Could use a binary heap for best price, but we need to support removal of arbitrary orders; a tree with pointers from order to node is fine.
- Pre-allocate memory: use memory pools for orders to avoid dynamic allocation. The order book can maintain free lists.
- Avoid false sharing: align data structures per cache line. For the lock-free queue, use a ring buffer with padded cache lines.
- Minimize branches: use branchless code where possible.
- Use SIMD for scanning multiple price levels? Probably not needed.
- Additional Features:
- Market data feed: generate updates (order book deltas) for downstream subscribers. This can be done by a separate thread that reads changes from the matching engine via another queue. Or the matching engine pushes incremental updates to a multicast group. For deterministic replay, these market data events should also be logged, but they are derived from state changes, so they can be regenerated on replay.
- FIX protocol handling: parse and convert FIX messages to internal order representation.
- Conclusion: summarize the design.
We need to produce an answer that is comprehensive and technical, focusing on the requested aspects.
We should structure answer with headings, bullet points, maybe some code snippets.
Given the context, the answer might be expected to be a design document. So I'll write a detailed explanation.
Let's start:
Introduction: low-latency order matching engines are core to electronic trading. They must handle high throughput with microsecond latency, ensure fairness, and support deterministic replay for audit and debugging. We'll design a system that meets these goals.
Core Requirements:
- Low latency: end-to-end processing within microseconds.
- Deterministic replay: ability to reconstruct exact sequence of state changes.
- Concurrency: handle multiple clients concurrently.
- Risk checks: real-time pre-trade risk validation.
- Audit logging: immutable, tamper-evident log of all events.
System Architecture:
We propose a modular design with a single-threaded matching core for determinism, and lock-free queues for inter-thread communication.
Components:
-
Network Acceptor / Gateway: Listens for client connections, parses orders, assigns globally unique sequence numbers (monotonically increasing), performs initial validation (message format, duplicate detection). It then pushes the order into a lock-free ring buffer (e.g., ConcurrentQueue) for the matching engine. The gateway also receives execution reports from the matching engine and sends them back to clients.
-
Matching Engine: A dedicated thread running an event loop. It sequentially pops orders from the input queue, processes them (risk checks, order book updates, matching), and generates events (trades, order updates). All state (order books, account positions, balances) is confined to this thread, eliminating locks.
-
Risk Engine: Integrated into the matching engine thread to avoid cross-thread latency. Risk checks are performed using in-memory data structures (account state). For simplicity, we keep risk logic within the same thread; if risk checks become too heavy, they can be offloaded to a separate fast cache with atomic updates, but that adds complexity.
-
Audit Logger: A separate thread that consumes events from a lock-free audit queue written by the matching engine. It writes events to disk (or persistent memory) in a durable, append-only format. The logger may batch writes to improve throughput while ensuring durability via periodic fsync or using a write-ahead log on a fast SSD.
-
Market Data Publisher: Optional: reads state changes from the matching engine (or from the audit log) and publishes order book updates to subscribers. This can be a separate thread to avoid blocking matching.
The flow: Client -> Gateway -> (input queue) -> Matching Engine -> (audit queue) + (output queue) -> Gateway -> Client; also Audit Logger reads from audit queue and writes to disk.
Concurrency Model:
- All mutable state (order books, accounts) is owned by the matching engine thread. This eliminates data races and ensures deterministic ordering: events are processed in the exact order they are dequeued, which is the order of sequence numbers assigned by the gateway.
- The gateway and logger are lock-free with respect to the matching engine, using ring buffers. They do not modify shared state, only pass messages.
- Sharding: To scale to multiple symbols, we can spawn multiple matching engine threads, each responsible for a subset of symbols. The gateway routes orders based on symbol hash. For accounts that trade multiple symbols, their account state would then be shared across engines, requiring synchronization. To avoid this, we can shard by account ID instead, but that would concentrate load. A compromise: use a single engine for a given account's instruments, but that reduces scalability. For high-performance exchanges, often all instruments are handled by one engine per trading session, using a fast single core. We'll focus on a single engine design; scaling can be achieved by multiple engines handling disjoint product families (e.g., different asset classes) with separate account sets.
Data Structures:
We'll define the core structures:
-
Order:
struct Order {
uint64_t order_id; // unique
uint64_t account_id;
char side; // 'B' or 'S'
uint64_t symbol_id; // mapping to symbol
uint64_t price; // integer in ticks
uint64_t quantity; // original quantity
uint64_t remaining; // remaining quantity
char order_type; // limit, market, etc.
char time_in_force; // GTC, IOC, FOK
uint64_t timestamp; // receipt time (for logging)
// pointer to price level node
};
-
PriceLevel:
struct PriceLevel {
uint64_t price;
std::deque<Order*> orders; // FIFO queue of orders at this price
// For quick removal of a specific order, we could store a linked list with node pointers in Order.
// But deque is not O(1) for arbitrary removal unless we have iterator. Better: use intrusive linked list.
};
For performance, avoid std::deque which has overhead. Use a custom intrusive singly-linked list with head/tail pointers, and store next pointer in Order. Also we can store a price_level_handle in Order to quickly remove. Since removal happens only via order ID, we need to locate the order's node; we can store a list_node within Order that is linked in the price level's list. Using an intrusive list (like boost::intrusive::list) gives O(1) removal if we have iterator. But we need to store the iterator or pointer to the node. Actually we can store a PriceLevel* and a pointer to the next order? Better: store Order* prev and Order* next and PriceLevel* maintains head/tail. Then removal from list is O(1) if we have these pointers. That's good.
-
OrderBook (per symbol):
struct OrderBook {
// For bids: max-heap of price levels; for asks: min-heap.
// Use a balanced BST: std::map<uint64_t, PriceLevel> for bids and asks separately.
// But we need fast best price and ability to insert/remove price levels.
std::map<uint64_t, PriceLevel> bid_levels; // key: price, sorted ascending? Actually for bids, we want highest first; so we store with custom comparator that orders descending, or just store normal and use rbegin. For performance, we can store descending so begin() is best.
std::map<uint64_t, PriceLevel> ask_levels; // sorted ascending.
// Or use a skip list (like folly::ConcurrentSkipList) but single-threaded we can use std::map; O(log n) is fine as number of price levels is moderate (hundreds).
// But to avoid allocations per price level, we can have a pool.
};
However, std::map has overhead and allocations. For low latency, we might implement a flat structure: an array of price levels sorted by price, and a binary search to find price level. Insertion of new price level would be O(n) shift, but if price levels are not too many, okay. But we also need to iterate from best to worst during matching, which is efficient with array. But removal from array may be slower. We can use a custom AVL tree with node pools. I'd propose using a red-black tree or skip list with custom allocator to avoid malloc. But for simplicity, we can describe using a with a custom allocator that pre-allocates nodes from a pool.
Order Matching Algorithm:
We'll outline steps for processing an order (example: buy limit order).
-
Validate order: basic checks (price > 0, qty > 0). Could also check for valid symbol, account exists.
-
Perform Risk Checks (see section below). If fails, reject order and generate OrderReject event. Log and skip further processing.
-
Determine if order is marketable: for buy, if price >= best ask price; for sell, if price <= best bid price. If marketable, execute against the opposite side.
- While order has remaining quantity and opposite side has price levels that satisfy condition:
- Get best price level (top of ask for buy).
- Take first order in that level's FIFO queue.
- Compute fill = min(order.remaining, resting.remaining).
- Create trade event: trade_id, symbol, price (resting order's price), quantity, buyer_account, seller_account, timestamps.
- Update both orders' remaining quantities.
- Update account positions and balances (if needed: for cash, only after full settlement? Usually immediate, but we can update margin). Update risk state (positions).
- If resting order is fully filled, remove it from price level and deallocate (or return to pool). If price level becomes empty, remove from map.
- If incoming order is fully filled, break.
- After loop, if order has remaining quantity, continue to step 4. If order is IOC and still has remaining, cancel it; if FOK and not fully filled, reject entire order (but we already executed some? Actually FOK requires full fill or none; so we must roll back partial fills? That's tricky. To simplify, we reject FOK if it cannot be fully filled immediately; we can first check if it would fully fill without actually executing, then if yes, execute. So for FOK, we must determine if the order can be fully filled before executing any trade; we need to simulate matching. That may require scanning the book without modifying state, then if sufficient, apply trades atomically. This could be done by first performing a "probe" matching on a copy, but that's expensive. Alternatively, we can perform the matching and if we end up partially filled, we need to roll back. That's complex. For simplicity, we could treat FOK as "fill-or-kill": we attempt to fill; if after scanning we have remaining, we cancel any partial fills? That would be unusual: FOK must be atomic: either entire order fills or none. So we must either fill completely or leave book unchanged. Implementation: For FOK, before matching, we compute if the total available liquidity at acceptable prices (for buy: price >= order price; for sell: price <= order price) is sufficient. If not, reject. If yes, we then perform the same matching algorithm as for IOC but we must fill entire order. Since we know liquidity is enough, we will fill completely; we can run the same matching loop and it will fill. But we must ensure no other orders arrive in between? Since single-threaded, no interleaving. So we can just match as normal and it will fill completely. However, if liquidity is exactly sufficient, we will fill completely. But what if after starting to match, another order that was not present earlier arrives? Not possible because single-threaded; we haven't dequeued other orders yet. So safe. So we can first check total liquidity (sum of quantities at price levels that satisfy). That's O(number of price levels) but that's okay; could be a simple loop while there is enough. For IOC, we don't need pre-check.
Risk Checks Details:
We'll implement a function bool checkRisk(const Order& order, Account& account, const OrderBook& book) that returns true if the order can be accepted. It must consider:
-
Account existence: account must be active.
-
Order size limit: order.quantity <= account.limits.max_order_size.
-
Position limit: for the symbol, after hypothetical fill, new net position = current position + (side == BUY ? quantity : -quantity). Absolute value must be <= account.limits.max_position. For buy, new position = old + qty; for sell, new = old - qty. But careful: if already short, selling more increases short, so absolute value. So compute new_position = old_position + delta, then |new_position| <= limit.
-
Notional limit: For buy orders, order.price * order.quantity <= available cash (balance - reserved). For sell, check that we have sufficient long position to deliver? Actually for short selling, we need to check if shorting is allowed and within limits. We can treat as position limit.
-
Margin: For each account, we might have a margin requirement based on open positions. We need to ensure that after the order, the margin requirement does not exceed available margin. Must update margin usage as positions change. Since we process orders sequentially, we can maintain a running margin usage per account, per symbol or total. When a new order arrives, we estimate the additional margin (e.g., * margin rate). But margin calculation can be complex; we might simplify to use a fixed percentage of notional. Or we can skip margin if not required.
-
Duplicate/Expired: reject if order already exists (duplicate order ID) if order management requires uniqueness. But we assign unique order IDs, so duplicates unlikely.
-
Session state: ensure account is not suspended.
-
System checks: circuit breaker if price deviates too much from reference, etc.
To avoid costly lookups, we can store per-account limits and current usage in contiguous arrays indexed by account ID (if IDs are dense) or in a hash map. Since we have a single thread, hash map is fine.
We must also consider that risk checks must be atomic with the order acceptance. Because we do them in the same thread, it's atomic.
Audit Logging:
We define an AuditEvent struct with common header and type-specific payload.
Example types:
- ORDER_SUBMITTED
- ORDER_REJECTED (with reason)
- ORDER_MODIFIED
- ORDER_CANCELED
- TRADE
- MARGIN_CALL
- POSITION_UPDATE
The matching engine, after processing an order, pushes one or more events to an audit ring buffer. The logger thread reads from this buffer and writes to a persistent log file. We need to guarantee that events are recorded in the same order as they occurred. The ring buffer must be bounded; if full, the matching engine may block on push, which would increase latency. To avoid blocking, we can allocate a large buffer (e.g., 1M entries) and have the logger keep up; worst-case, backpressure to gateway to throttle clients.
Persistence:
-
Use memory-mapped file for the log: the ring buffer directly maps to a file region. The logger thread fsyncs periodically (e.g., every 1000 events or every 100ms). Or use O_DIRECT to bypass cache. But simplicity: write to a file and call fsync in batches.
-
Log format: fixed-size entries (or variable with length prefix). Include a CRC or checksum for integrity. Also include a sequence number that increments for each audit entry (or use the same sequence number as the order's global seq? That could be separate for audit). To enable replay, we need the exact sequence of events; we can use the order's seq number as part of the event, but trade events also need a unique ID. We'll assign a global event ID.
Deterministic Replay Implementation:
The engine's state is fully determined by the sequence of input events (order submissions, modifications, cancellations) and its deterministic algorithm. To support replay:
-
We record all input events in the audit log, along with any internal events (trades). The log is the source of truth.
-
To replay, we initialize a fresh engine (order books empty, accounts with initial balances), then read the audit log from the beginning (or from a snapshot). For each event, we apply the same logic as during normal operation: for ORDER_SUBMITTED, we run the order through the same processing pipeline (including risk checks) and generate the same resulting events. The resulting state at each step should match the original.
-
However, risk checks might depend on current account state, which will be identical if we apply events in order. So deterministic.
-
To speed up replay, we can take periodic snapshots of the entire in-memory state (serialize order books, accounts, etc.) and store them. Then on restart, load the latest snapshot and replay only events after that. This is similar to database checkpointing.
-
Determinism considerations:
- All random numbers: use deterministic PRNG seeded from fixed value.
- Timestamps: when replaying, we don't need real-time; we can use the logged receipt time for any timestamp-dependent logic. If the engine uses current time for time-based risk (e.g., order expiration), we must use the event's timestamp as the current time during replay (simulate time progression). So we need to store the event's logical time (receipt timestamp) and use that during replay to compute expiration. So the engine must be written to use a "now" parameter that during replay is set to the event's timestamp, not actual current time.
- Order ID generation: during normal operation, the gateway assigns sequence numbers to orders. During replay, we should use the same order IDs from the log. So when reading an ORDER_SUBMITTED event, we feed the order with its original order ID and sequence number. So no new ID generation needed; we rely on the log.
-
Replay utility: a separate program that reads the audit log, instantiates the engine, and replays events. For verification, we can compare the final state against a known good checkpoint.
Risk Check Implementation in Depth:
To achieve low latency, we need to make risk checks as fast as possible. Several optimizations:
- Use bitfields and integer arithmetic.
- Pre-compute risk limits into a compact struct and cache it.
- Use a fast hash map for account lookup; perhaps assign account IDs as small integers (0..N-1) and use an array
accounts[]. This yields O(1) access.
- For position checking, store current position per account per symbol in a 2D array if symbol count is bounded. But if there are many symbols and only a few per account, a hash map might be more memory efficient. For speed, we can use a cache of recently accessed symbols (like a LRU) but since single thread, direct access is fine. We'll assume a dense symbol ID as well (e.g., 0..M-1) and allocate an array of
int64_t positions[MAX_ACCOUNTS][MAX_SYMBOLS] if within memory limits (e.g., 1000 accounts * 1000 symbols = 1M entries, 8MB, acceptable). That gives O(1) position lookup without hashing.
- Balance check: maintain per-account balance and reserved amount. For buy orders, check
quantity * price <= balance - reserved. Reserved can be used to lock funds for resting orders? Typically, for limit orders that are not executed, we might not lock cash; only when they execute we deduct. But to avoid overdraft, we may want to check that after execution the balance won't go negative. So we need to consider the potential immediate execution if order is marketable. But it's simpler: we assume that the order will be executed at its limit price (worst-case for a buy is executed at the order's limit price; for sell, executed at order's limit price or better). So we check quantity * order.price <= balance for buy? Actually if a buy limit order is added to book, it hasn't executed yet, so cash not needed until it executes. But if it's marketable, it will execute immediately, so we need to have cash. So we must conditionally check: if order is marketable (i.e., would execute immediately), then we need to ensure cash or margin. If it's non-marketable (resting), we may not lock cash. However, some exchanges require upfront collateral for all orders (e.g., Reg T). Then we must lock cash for any buy order, limit or not. To be safe, we can do upfront check: for any buy order, we require that balance >= quantity * price (or a margin equivalent). That's simpler and eliminates need to determine marketability upfront; but it may be overly restrictive (e.g., buy limit order far from market would lock cash unnecessarily). But for equities, often orders don't lock cash until execution; margin accounts have credit lines. However, risk limits often use "potential future exposure" and may calculate based on notional. We'll abstract: risk checks can be configured per account type. For simplicity, we'll assume we check that after the order's lifetime, the worst-case net cash requirement is covered. This can be complex; we'll leave details vague but mention that the risk engine is pluggable.
Given the question is not to fully implement but to engineer, we can describe the approach at a high level with specifics where needed.
Implementation Considerations:
- Memory Allocation: To avoid malloc during processing, we pre-allocate a pool of Order objects and PriceLevel objects. The matching engine uses its own memory pool (e.g., a free list). This reduces latency and fragmentation.
- Cache Efficiency: OrderBook per symbol: keep price levels and orders in contiguous memory as much as possible. Use arrays for price levels if possible. But map nodes are separate. Could use a custom allocator that allocates from a large block.
- Branch Prediction: Keep hot paths short. For matching, the common case is price levels with many orders; we iterate FIFO. Use a while loop that checks remaining quantity.
- Lock-free Queues: Use a ring buffer with head/tail atomic indices, padded to avoid false sharing. E.g.,
boost::lockfree::spsc_queue or custom.
- Logging: Use a separate thread with its own ring buffer; the matching engine writes audit events to a lock-free queue that the logger consumes. The logger may batch writes: accumulate N events or time-based, then write a single large I/O using
writev or pwrite. Use O_DSYNC or fsync at intervals.
- Replay: The audit log should include a footer with hash of all entries for integrity. Could also use a Merkle tree.
Determinism Guarantees:
- All state changes are triggered by events processed in a single thread in the order of sequence numbers.
- The matching algorithm is deterministic: when multiple orders at same price, FIFO; when matching against multiple price levels, we sweep from best to worst until exhausted; if two orders have same arrival time? But we have sequential ordering by sequence number. No ambiguity.
- The risk check function is pure (no side effects) and yields same result given same state.
- Randomness: none; all IDs derived from sequence numbers.
- Timestamps: only for logging; do not affect state.
Scalability and Extensions:
-
To scale beyond single core, we can partition instruments across multiple matching engines, each with its own thread and state. For accounts spanning multiple engines, risk checks become distributed; we could use a separate risk service that maintains global state with optimistic concurrency. But that adds latency and complexity. If deterministic replay across shards is needed, we need to order events globally (e.g., a sequencer that assigns global sequence numbers before routing to shards). Then each shard processes events in global order? That would cause cross-shard dependencies. Better: route all orders for a given account to a single shard to keep risk checks local. We can shard by account ID; that would keep all of an account's orders on one engine, but different accounts on different shards. That allows risk checks per account to be local. But a single symbol with many accounts would be spread, which is okay because order book is per symbol; but if we shard by account, the order book for a symbol would be split across shards, requiring distributed matching. That's not feasible. So sharding must be by symbol. Then an account that trades multiple symbols will have state distributed across shards. For risk, we need to gather positions across shards. Could do a risk cache that aggregates per account across shards using atomic updates. But then risk checks become cross-shard; we could pre-check at gateway using a global risk cache that is updated by shards after trades. That cache would be a separate in-memory store (e.g., Redis) with low latency, but still adds network hop. We'll not go deep.
-
Fault Tolerance: The matching engine is critical; we can implement primary-backup replication. The primary matches orders and logs events to a replication stream. A backup (hot standby) replays the log and keeps state in sync. On failover, the backup takes over. For deterministic replay, the log is the source of truth. The backup may apply events slightly behind. This is out of scope but can be mentioned.
Audit Log Format and Tamper Eviction:
We define a binary log format:
struct AuditHeader {
uint64_t sequence; // monotonic sequence number
uint64_t timestamp_ns; // receipt timestamp (from gateway)
uint16_t type;
uint16_t length; // payload length
uint32_t crc; // CRC of payload
};
union AuditPayload {
OrderSubmitted submitted;
OrderRejected rejected;
Trade trade;
// ...
};
We can also include a hash chain: each header includes a hash of the previous header's hash (e.g., SHA-256). This makes the log tamper-evident.
The logger writes sequentially to a file. On startup, it reads the last valid entry and continues.
Risk Checks Pluggability:
We can design the risk engine as a separate module with a well-defined interface. The matching engine calls risk_engine.check(order, account, state) before applying. The risk engine can be updated at runtime via configuration.
Conclusion:
We've designed a low-latency order matching engine with deterministic replay using a single-threaded matching core, lock-free communication, integrated risk checks, and an audit logger. The design prioritizes simplicity and determinism while achieving low latency through careful data structures and concurrency control.
Now, let's produce a final answer in a well-structured format.
Order Matching Engine Design
Low‑Latency, Deterministic Replay, Integrated Risk & Audit
1. Introduction
An order matching engine (ME) is the heart of an electronic trading venue. It must:
- Match orders with microsecond latency.
- Maintain determinism – identical input must produce identical state for replay, debugging, and regulatory audit.
- Enforce risk limits in real time before orders affect the market.
- Produce an immutable audit trail of every state‑changing event.
The design below satisfies these constraints while remaining simple enough to reason about and maintain.
2. High‑Level Architecture
┌─────────────┐ ┌──────────────────┐ ┌───────────────┐
│ Client(s) │──────▶│ Gateway / │──────▶│ Matching │
│ (FIX/ binary)│ │ Acceptor │ │ Engine (1) │
└─────────────┘ └──────────────────┘ └───────┬───────┘
│
│ audit events
▼
┌──────────────────┐
│ Audit Logger │
│ (persistent) │
└──────────────────┘
(Other optional components: Market‑Data Publisher, Replay Tool, Backup Replica)
Key design choices
- Single‑threaded matching core – all mutable state (order books, accounts) is owned by one thread. This gives deterministic ordering (events processed in strictly increasing sequence numbers) and eliminates locking.
- Lock‑free, single‑producer/single‑consumer queues between components minimise latency and avoid deadlocks.
- Sharding (optional) – if scaling is needed, split symbols across multiple MEs, each still single‑threaded. Account‑level risk checks then either:
- route all orders of an account to the same shard (by account hash), or
- use a fast, in‑memory risk cache that aggregates per‑account state across shards (adds a small cross‑shard hop).
3. Data Structures
All structures live inside the matching thread’s memory space. Memory is pre‑allocated from pools to avoid malloc during processing.
3.1 Order
struct Order {
uint64_t order_id; // global unique ID (gateway seq)
uint64_t account_id;
uint64_t symbol_id; // integer mapped from symbol string
char side; // 'B' or 'S'
char type; // 'L' (limit), 'M' (market), ...
char tif; // 'G' (GTC), 'I' (IOC), 'F' (FOK)
uint64_t price_ticks; // integer price in smallest tick
uint64_t orig_qty;
uint64_t remaining;
uint64_t timestamp_ns; // receipt time (for audit)
// Intrusive list pointers for price level:
Order* next_in_level; // singly‑linked list
// Back‑pointer to the price level (optional, for fast removal):
// PriceLevel* level;
};
3.2 Price Level
struct PriceLevel {
uint64_t price_ticks;
Order* head; // FIFO queue (intrusive)
Order* tail;
uint32_t total_qty; // sum of remaining quantities at this level
// For quick removal of the whole level when empty
};
3.3 Order Book (per symbol)
Two sides, each a sorted map from price to PriceLevel.
class OrderBook {
// For bids: highest price first → descending comparator
std::map<uint64_t, PriceLevel*, std::greater<uint64_t>> bids;
// For asks: lowest price first → ascending (default)
std::map<uint64_t, PriceLevel*> asks;
// ... methods: get_best_bid/ask, insert, erase_level, etc.
};
Optimisation: Replace std::map with a custom cache‑friendly skip‑list or a flat array if the price range is limited. The number of active price levels is usually in the hundreds, so O(log n) is negligible.
3.4 Account & Risk
struct Account {
uint64_t account_id;
int64_t balance; // cash
int64_t margin_used; // notional * margin_rate
std::vector<int64_t> position; // index = symbol_id, net quantity
RiskLimits limits; // max_order_qty, max_position, etc.
};
Positions are stored in a dense array (std::vector) when the number of symbols is bounded (e.g., < 10 000). This gives O(1) access without hashing.
Risk limits (per account, optionally per‑symbol) are loaded at start‑up into the Account struct.
4. Matching Algorithm
The engine runs an event loop:
while (true) {
Event e = input_queue.pop(); // events: NewOrder, Modify, Cancel
switch(e.type) {
case NEW_ORDER:
process_new_order(e.order);
break;
case MODIFY_ORDER:
process_modify(e.order_id, e.new_params);
break;
case CANCEL_ORDER:
process_cancel(e.order_id);
break;
}
}
4.1 process_new_order
- Validate – correct side, symbol alive, qty > 0, price within allowed range.
- Risk check – see section 5. If failed → reject, log, return.
- Determine marketability:
- Buy:
price >= best_ask
- Sell:
price <= best_bid
(If book empty → not marketable.)
- Match if marketable:
- While order remaining > 0 and opposite side best price satisfies:
- Take
PriceLevel* = opposite side best level.
- Take first
Order* in FIFO queue.
fill = min(order.remaining, resting.remaining).
- Create Trade event (trade_id, price = resting.price, qty = fill, accounts, timestamps).
resting.remaining -= fill; total_qty at level -= fill.
order.remaining -= fill.
- Update both accounts’ positions and cash (if cash settlement is immediate). Update margin usage.
- If
resting.remaining == 0 → remove from its price level list, maybe delete level.
- Loop until no more liquidity or order exhausted.
- Post‑match handling:
- If
order is IOC and still has remaining → discard (no insert).
- If
order is FOK and not fully filled → rollback (we either pre‑checked liquidity or reject before matching).
- If still remaining → it is a resting limit order. Insert into its side’s book:
- Find or create
PriceLevel at order.price.
- Append order to tail of FIFO list, update
total_qty.
- Generate state‑change events:
OrderUpdate (new order ID, or partial fill info).
- If partially filled,
OrderUpdate after each fill (or aggregated).
- If order was fully filled and removed,
OrderDone.
- All events are placed on the audit queue and on the output queue for the gateway.
4.2 process_cancel
- Look up order in
order_id → Order* map (maintained by ME).
- Remove from its price level’s list, adjust
total_qty.
- If level becomes empty → erase from map.
- Release order to pool.
- Generate
OrderCanceled audit event.
4.3 process_modify
- Cancel the old order (as above) and insert a new order with the updated parameters (price, qty).
- Risk check is performed on the new parameters.
- Generate
OrderModified audit event (includes old and new values).
5. Risk Checks
All risk checks are performed inside the matching thread before an order can alter state. They are fast, using only in‑memory data.
5.1 Pre‑trade Checks
bool check_risk(const Order& ord, Account& acc) {
// 1. Basic limits
if (ord.orig_qty > acc.limits.max_order_qty) return false;
// 2. Position limit (net absolute)
int64_t delta = (ord.side == 'B') ? ord.orig_qty : -ord.orig_qty;
int64_t new_pos = acc.position[ord.symbol_id] + delta;
if (std::abs(new_pos) > acc.limits.max_position) return false;
// 3. Cash / margin check for buys (simplified)
if (ord.side == 'B') {
uint64_t cost = ord.orig_qty * ord.price_ticks;
if (cost > acc.balance) return false; // or use margin model
}
// 4. Account status (active, not suspended)
// 5. System controls (circuit breaker, price deviation)
return true;
}
The function is pure; it does not modify state. All required data (position, balance, limits) are stored in arrays/vectors with O(1) access.
Margin / sophisticated limits can be added as pluggable modules. Since the ME is single‑threaded, any additional calculation simply adds to per‑order latency – the design must keep the hot path under a microsecond.
6. Deterministic Replay
6.1 What Must Be Logged?
Every external input (new order, modify, cancel) and every state‑changing output (trade, order update, reject) is written to an append‑only audit log before the matching engine acknowledges the order to the gateway (or after, depending on durability requirements – for replay we only need the events, not the ack timing).
6.2 Log Format
Binary, fixed‑size header + variable payload.
struct AuditHeader {
uint64_t seq; // monotonically increasing (global)
uint64_t ts_ns; // event timestamp (gateway receipt)
uint16_t type; // enum: ORDER_SUBMITTED, TRADE, ...
uint16_t payload_len; // bytes
uint8_t prev_hash[32]; // SHA‑256 of previous header (hash chain)
uint32_t crc; // of payload
};
Payloads contain the full details (order fields, trade fields, reject reason). The hash chain makes the log tamper‑evident – altering any entry breaks the chain.
6.3 Writing the Log
A dedicated Logger thread owns a lock‑free ring buffer (SPSC). The matching engine writes audit events into the ring buffer (non‑blocking; if full, it can apply back‑pressure to the gateway). The logger then writes sequentially to a memory‑mapped file or raw SSD, optionally fsync‑ing every N entries or every T ms.
6.4 Replaying
A replay tool reads the audit log (or a snapshot + remaining log) and executes the same matching algorithm on a fresh engine instance:
- All external events are fed in order.
- The engine uses the same deterministic logic (identical risk checks, matching steps).
- No random numbers or time‑based decisions (except using the logged timestamp for time‑in‑force, not system clock).
- The state after each event must match the original state (can be verified by periodic hash of the whole engine state).
Because the ME is single‑threaded and uses only in‑memory data structures, replay is exact.
Checkpointing: Periodically (e.g., every 10 000 events) the engine can take a full snapshot of its state (binary dump) and write it to the audit log. On restart, the latest snapshot is loaded and the log replayed from that point, reducing replay time.
7. Concurrency Control
- All shared mutable data (order books, accounts) is confined to one thread → no locks, no data races.
- Gateway → ME: lock‑free SPSC ring buffer. The gateway assigns a global sequence number to each client order; the ME processes in that order.
- ME → Gateway: another SPSC queue for execution reports.
- ME → Logger: SPSC audit queue.
- Market‑data can be a separate thread that reads the same audit stream or a copy of state changes (e.g., a read‑only ring buffer) to avoid blocking the ME.
If sharding is used, each shard has its own single‑threaded ME and its own set of queues. A front‑end sequencer may assign global sequence numbers and then route orders to the appropriate shard; the sequencer itself can be lock‑free.
8. Low‑Latency Optimisations
- Memory pools for
Order and PriceLevel objects – no dynamic allocation during processing.
- Intrusive linked lists – order removal is
O(1) using stored pointers.
- Cache‑friendly containers – align structures to 64‑byte cache lines, pad heads/tails to avoid false sharing.
- Pre‑computed risk data – limits in dense arrays, positions in flat vectors.
- Branch prediction – keep hot path (matching loop) tight; e.g., while
order.remaining > 0 && ask_best_price <= order.price.
- Lock‑free queues – use
std::atomic head/tail indices with padding, or proven libraries (folly::MPMCQueue, boost::lockfree::spsc_queue).
- Batching in logger – accumulate many audit entries before a system call; the ME never blocks on disk I/O.
9. Audit Logging – Immutability & Durability
- Append‑only: Once written, entries are never modified.
- Tamper‑evident: Hash chain (or periodic Merkle root) stored off‑site.
- Durability: Logger threads write to a fast NVMe device; use
O_DSYNC or fsync in batches to balance latency vs. risk.
- Retention: Log files are rotated and archived (e.g., to WORM storage) to meet regulatory requirements.
10. Putting It All Together – Event Flow
- Client → Gateway: receives FIX/Proprietary order, validates syntax, assigns global seq.
- Gateway → ME (input queue): pushes
NewOrder message.
- ME:
- Pops message, obtains order object from pool.
- Runs
check_risk. If fail → OrderRejected → audit & output queue.
- Runs matching algorithm, updates books & accounts.
- Generates
Trade, OrderUpdate, OrderDone events.
- Appends all events to audit queue (logging order) and to output queue (for gateway).
- Gateway reads output queue, formats messages, sends to client.
- Logger reads audit queue, writes to persistent log (with hash chain).
- Snapshot (optional): every N events, ME pauses, dumps full state to log (or separate file), then resumes.
11. Replay Tool & Verification
- Replay program reads the audit log from the beginning (or from the latest snapshot) and constructs a fresh engine.
- For each event, it invokes the same internal processing functions (
process_new_order, etc.).
- After each event, it can compute a state hash (e.g., SHA‑256 over all books & accounts) and compare with the hash recorded in the original log (if available) to guarantee fidelity.
- The tool can be used for debugging, regulatory audits, or disaster recovery (re‑build the running engine state instantly).
12. Extensions & Considerations
- Fault tolerance: A hot standby replica can pull the audit log in real time and stay in sync; on primary failure, it takes over (using the log to catch up).
- Market‑data distribution: The ME can push incremental book updates to a multicast group; these updates are derived from state changes and need not be separately logged.
- Complex risk models: Often implemented in a separate “Risk Microservice”. For ultra‑low latency, the hot path must remain in‑process; a read‑only cache can be used with atomic updates if split.
- Time‑based events: Orders with expiration are handled by comparing the event’s logged timestamp with the order’s expiry; the engine uses the event timestamp (not wall‑clock) during replay.
13. Conclusion
The presented design achieves microsecond‑level latency by keeping the matching core single‑threaded and lock‑free, while deterministic replay is guaranteed by logging every external input and internal state change in a globally ordered, tamper‑evident audit trail. Risk checks are integrated directly into the matching path using fast in‑memory data structures, and audit logging is offloaded to a dedicated thread with minimal impact on latency. This architecture is proven in high‑frequency trading venues and can be scaled out by sharding symbols if needed, while preserving determinism through a global sequencer.