Low-Latency Matching Engine Architecture: Engineering Practices for Small Teams

    This article examines how a small engineering team can build and operate a low-latency trading matching and clearing platform. It breaks the system into five layers, details the in-memory order book data structures, covers kernel-bypass networking and CPU isolation, and explains how event sourcing with an ordered log keeps the system correct as well as fast. It also shows how to replace self-built infrastructure with managed cloud capabilities, which observability metrics matter most, and a pragmatic path for scaling out.

    1. The Engineering Problem Behind the Phenomenon

    There are cases in the industry of an engineering team of roughly a dozen people building and operating a high-frequency matching and clearing system that generates hundreds of millions of dollars in annual gross revenue. Such outcomes are often attributed to timing or luck, but from an engineering standpoint the real enablers are three things: choosing a scenario that is extremely sensitive to latency and throughput, and therefore has a naturally high technical barrier; compressing system complexity into a very small number of core modules, avoiding the operational tax of microservice sprawl; and pushing all non-core capabilities (storage, messaging, monitoring, release) out to general-purpose cloud services, so limited headcount stays focused on the two main lines: matching and risk control.

    This article discusses no specific company, product, or individual. It abstracts the phenomenon into a general engineering question: how to build a low-latency trading matching platform with the smallest possible team that can run stably over the long term. The same question applies to traditional finance, cross-border e-commerce pricing, compute scheduling, and ad auctions.

    2. Layered Architecture: Containing the Complexity

    A deployable high-performance matching system is usually split into five layers, communicating through clearly defined protocols, with any layer independently replaceable.

    1. Access layer: protocol parsing, authentication, rate limiting, session management. This layer is stateless and scales horizontally.
    2. Risk control layer: pre-trade checks before an order reaches matching, including self-trade prevention, price deviation bands, per-account exposure, and rate limits.
    3. Matching core: maintains the order book in memory, executes price-time priority or an improved variant, and emits a stream of fill events.
    4. Clearing and ledger layer: converts fill events into deterministic balance changes, guaranteeing replayability and reconcilability.
    5. Peripheral services: market data distribution, historical queries, reporting, monitoring and alerting.

    The key design principle: only the matching core needs to be single-threaded and serialized; everything else can run in parallel. The most common mistake a small team makes is stuffing risk control, market data, and queries into the matching process, letting slow logic drag down the core.

    1. Access (parallel) -> Risk control (parallel, stateful sharding) -> Matching core (single writer) -> Ledger (sequential persistence)
    2. \-> Market data fan-out (side path, lossy and reconnectable)

    3. In-Memory Data Structures for the Matching Core

    Matching core performance is determined almost entirely by data structures. The layered structure widely used in the industry is:

    • Price level: an ordered skip list or balanced tree maintains price pointers, supporting O(log n) insertion and deletion plus bidirectional traversal.
    • Order level: each price holds a FIFO doubly linked list, implementing time priority.
    • Order index: a hash table keyed by order ID, giving O(1) cancel and amend.

    Pseudocode sketch:

    1. class OrderBook:
    2. def __init__(self):
    3. self.bids = SkipList() # price -> order queue
    4. self.asks = SkipList()
    5. self.index = {} # order_id -> (side, price, node)
    6. def on_new(self, order):
    7. book = self.bids if order.side == 'B' else self.asks
    8. queue = book.get_or_create(order.price)
    9. node = queue.append(order)
    10. self.index[order.id] = (order.side, order.price, node)
    11. def on_cancel(self, order_id):
    12. side, price, node = self.index.pop(order_id)
    13. book = self.bids if side == 'B' else self.asks
    14. book[price].remove(node)
    15. if book[price].is_empty():
    16. book.delete(price)

    Three disciplines are mandatory in practice:

    • Zero dynamic memory allocation: all objects on the hot path are preallocated, using object pools and an arena allocator to avoid GC or malloc jitter.
    • Lock-free single writer: the matching thread owns the core data structures exclusively; other threads submit instructions only through a lock-free ring buffer, eliminating lock contention.
    • Deterministic execution: the same input sequence must produce exactly the same output sequence, which is the prerequisite for replay-based reconciliation.

    4. The Low-Latency Path: From NIC to Matching Thread

    Optimization at the network and operating system level often yields more obvious gains than algorithm tuning:

    • Kernel bypass: use a user-space network stack or poll-mode driver to bypass the kernel protocol stack and interrupts, pushing tail latency from milliseconds down to microseconds.
    • CPU affinity and isolation: pin the matching thread to a dedicated physical core, isolate interrupts and scheduling from it, and disable frequency scaling and hyperthread sharing on that core.
    • Batching and coalescing: downstream market data uses batched encoding and incremental snapshot merging to reduce syscall count; upstream keeps small batches with low latency as the priority.
    • Serialization choice: the core path uses fixed-length binary encoding rather than text formats, avoiding parsing overhead and field drift.

    A common capacity estimation approach: if the peak order rate is R orders per second and average per-order processing time is t microseconds, a single core supports roughly 1/(t×1e-6) orders per second, and you should reserve at least 30% headroom for bursts. This simple formula quickly tells you during selection whether sharding is needed.

    5. Consistency and Clearing: Fast Is Not Enough

    High-frequency systems most easily lose balance between “fast” and “correct.” The reliable approach is event sourcing plus an ordered log:

    1. Every instruction entering the system is first appended to an ordered log and synchronously replicated to at least two replicas;
    2. the matching core replays from the log and produces fill events;
    3. the ledger layer consumes fill events in the same order and applies idempotent balance changes;
    4. on crash recovery, replay from the latest snapshot plus subsequent log entries, producing results identical to the state before the crash.

    Idempotency key design is especially critical. A composite key of “order ID + sequence number” combined with a deduplication table is recommended, so duplicate delivery never double-posts.

    1. -- Idempotent ledger posting sketch
    2. INSERT INTO ledger_entry (dedup_key, account, delta, seq)
    3. VALUES (:dedup_key, :account, :delta, :seq)
    4. ON CONFLICT (dedup_key) DO NOTHING;

    6. Replacing Self-Built Infrastructure with Managed Cloud Capabilities

    A team of roughly a dozen people cannot build its own data centers or develop its own storage and monitoring. The workable path is to fully outsource everything peripheral:

    • Container platform: hosts the stateless access layer and peripheral services, with autoscaling to handle market data peaks.
    • Message queue: decouples layers and absorbs peaks, turning burst traffic into a controllable consumption rate.
    • Object storage: holds snapshots, audit logs, and historical market data archives, with naturally high durability and low cost.
    • Log service and monitoring/alerting: uniformly collects metrics such as matching latency percentiles, queue backlog, and ledger lag, with tiered alerting.
    • Key and configuration management: use a managed key service and configuration center to avoid hardcoded credentials.

    The general-purpose capability categories offered by Baidu AI Cloud in these scenarios (container platform, message queue, object storage, log service, monitoring and alerting) cover the requirements above, so the team does not need dedicated operations staff for each class of infrastructure.

    7. Observability: Latency Percentiles Matter More Than Averages

    The health of a trading system is measured not by average latency but by P99, P99.9, and maximum queueing time. Instrument at least the following metrics:

    • wait time from instruction enqueue to matching start;
    • histogram of per-order matching processing time;
    • lag in bytes for ordered log writes and replication;
    • the difference between the ledger consumption position and the matching output position;
    • risk control metrics such as cancels per second and self-trade interception rate.

    Histograms rather than averages, because long tails usually correspond to real failures; the position difference is the only reliable signal for detecting that “clearing has fallen behind.”

    8. Capacity and Evolution Roadmap

    The pragmatic order of evolution: first build single-process, single-threaded matching plus an ordered log, and polish correctness to the extreme; then introduce sharding (routing by trading pair or account hash) so multiple matching cores run in parallel; finally add cross-shard portfolio margin and global risk control. Introducing distributed consensus protocols too early traps a small team in endless tuning and troubleshooting.

    9. Common Pitfalls

    • Logging or doing JSON serialization on the hot path;
    • implementing matching with multithreading plus locks, making tail latency uncontrollable;
    • backing up only the database without event replay, leaving you unable to prove correctness after a failure;
    • hardcoding risk rules inside the matching process, so changing one rule requires restarting the core;
    • monitoring only availability, not latency percentiles and position lag.

    10. Conclusion

    A small team delivering a high-value trading system is not a myth. It is extreme scope reduction plus obsessive optimization of the core path plus fully externalizing peripheral capabilities. Concentrate complexity in the one matching core that must be serialized, hand everything else to elastically scalable general-purpose cloud capabilities, and a dozen people can operate microsecond-level matching infrastructure stably over the long term.