Skip to content
LeetQuant
QD08 Trading Systems Architecture

QD08 · Trading Systems Architecture · Lesson 4 of 5

Event-Driven Architecture

Event loops, a single-threaded hot path, lock-free queues between components, latency budgets and queueing under bursts, and deterministic replay for testing.

17 min

Objective

Explain how the components of a trading system are wired together, why the critical path is usually one thread, how data crosses between threads, how to budget and reason about latency, and how event-driven design makes the whole system testable by replay.

The pipeline

A typical low-latency stack, in the order a market-data packet travels:

feed handler (decode, sequence check) → book builder → strategy (signal, decide) → pre-trade risk → order gateway (encode, send) → exchange

and in the other direction, exchange responses (acks, fills) → gateway → order manager → strategy. Logging, persistence, monitoring and position reporting hang off the side and must never block the path above.

The event loop

Each component is written as handlers that react to events: on_book_update, on_fill, on_timer. One loop owns the thread:

  1. Poll every input (network socket, inbound queues, timer).
  2. For each event, call the handler to completion.
  3. Repeat, without sleeping: busy-polling avoids the microseconds a thread takes to wake up.

The hot path (feed → book → strategy → risk → gateway) often runs entirely on one thread, pinned to an isolated CPU core. The reasons:

  • No locks: one thread owns the book and the positions, so nothing needs synchronising.
  • Warm caches: the data stays in that core's caches; handing off to another thread means the data must move between cores.
  • Determinism: the order of events is the order the loop sees them, which makes replay exact (below).

The cost is that a slow handler delays everything behind it. So handlers must be short and bounded: no allocation, no system calls, no logging that formats strings on the hot path. Slow work goes to another thread through a queue.

Queues between threads

Where a thread boundary is unavoidable (a logger, a second strategy, a separate feed thread), the standard tool is a bounded single-producer single-consumer (SPSC) ring buffer. With exactly one writer and one reader, each index has one owner, so no locks or compare-and-swap are needed: just atomic loads and stores with acquire/release ordering.

#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <optional>
#include <thread>

// Single-producer single-consumer ring buffer. N must be a power of two.
template <class T, std::size_t N>
class SpscQueue {
    static_assert((N & (N - 1)) == 0, "N must be a power of two");
public:
    bool push(const T& v) {  // producer thread only
        auto head = head_.load(std::memory_order_relaxed);
        if (head - tail_.load(std::memory_order_acquire) == N) return false;  // full
        buf_[head & (N - 1)] = v;
        head_.store(head + 1, std::memory_order_release);  // publish the slot
        return true;
    }
    std::optional<T> pop() {  // consumer thread only
        auto tail = tail_.load(std::memory_order_relaxed);
        if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;  // empty
        T v = buf_[tail & (N - 1)];
        tail_.store(tail + 1, std::memory_order_release);  // free the slot
        return v;
    }
private:
    std::array<T, N> buf_{};
    alignas(64) std::atomic<std::size_t> head_{0};  // written by producer
    alignas(64) std::atomic<std::size_t> tail_{0};  // written by consumer
};

struct Tick { uint64_t seq; int64_t px; };

int main() {
    constexpr uint64_t kMsgs = 1'000'000;
    SpscQueue<Tick, 1024> q;

    std::thread producer([&] {
        for (uint64_t i = 1; i <= kMsgs; ++i)
            while (!q.push({i, int64_t(10000 + i % 7)})) {}  // full: spin (back-pressure)
    });

    uint64_t expected = 1, checksum = 0;
    while (expected <= kMsgs) {
        if (auto t = q.pop()) {
            if (t->seq != expected) { std::printf("out of order!\n"); return 1; }
            checksum += t->px;
            ++expected;
        }
    }
    producer.join();
    std::printf("received %llu messages in order, checksum %llu\n",
                (unsigned long long)(expected - 1), (unsigned long long)checksum);
}

Output (c++ -std=c++20 -O2; also clean under ThreadSanitizer):

received 1000000 messages in order, checksum 10002999998

The details that interviewers look for:

  • Release/acquire: the producer writes the slot, then stores head_ with release; the consumer loads head_ with acquire, so it is guaranteed to see the slot's contents. The same pairing on tail_ tells the producer a slot is free.
  • Power-of-two capacity: index & (N - 1) replaces a modulo; the indices increase forever and wrap naturally.
  • Cache-line padding: head_ and tail_ are written by different cores; on one cache line they would cause false sharing, bouncing the line between cores on every operation.
  • Full queue policy: here the producer spins (back-pressure). Alternatives are dropping (acceptable for some telemetry) or conflating to the latest value (market-data snapshots for a slow consumer). Never grow without bound.

Worked example

a tick-to-trade latency budget

Illustrative median timings for one market-data packet that triggers an order: network receive with kernel bypass 1.0 µs; decode and book update 0.8 µs; strategy 1.5 µs; risk checks 0.3 µs; order encode and send 0.9 µs. Design A runs it all on one thread. Design B puts the strategy on its own thread, adding two SPSC hops at 0.2 µs each. What is tick-to-trade in each, and what should you measure besides the median?

Show solution

Design A: 1.0+0.8+1.5+0.3+0.9=4.51.0 + 0.8 + 1.5 + 0.3 + 0.9 = 4.5 µs.

Design B: 4.5+2×0.2=4.94.5 + 2 \times 0.2 = 4.9 µs, about 9% slower, and the data must also move between cores, which can add cache misses not in the budget.

The median is the wrong headline. Measure the distribution (p99, p99.9, maximum) at the moments that matter, which are bursts: a big trade sends a flood of updates, and that is exactly when your order needs to be fast. Measure with timestamps taken at the network card or at well-defined points in the loop, not by averaging. A budget also says where to spend effort: here the strategy is a third of the total.

Worked example

a burst and the queue

A consumer handles one message in 0.8 µs (1.25 million per second). A burst arrives at 2 million messages per second for 5 ms. How large does the backlog get, how long does the last message of the burst wait, and what ring-buffer capacity avoids blocking the producer?

Show solution

During the burst 2,000,000×0.005=10,0002{,}000{,}000 \times 0.005 = 10{,}000 messages arrive and 1,250,000×0.005=6,2501{,}250{,}000 \times 0.005 = 6{,}250 are processed. The backlog at the end is 10,000−6,250=3,75010{,}000 - 6{,}250 = 3{,}750 messages.

The last message waits behind that backlog: 3,750×0.83{,}750 \times 0.8 µs =3= 3 ms, even though the consumer's own processing time is under a microsecond. Queueing, not processing, dominates latency under load.

To absorb the burst without blocking the producer, the capacity must be at least 3,750; the next power of two is 4,096. The deeper lesson is that whenever arrivals exceed the service rate, a queue only delays the problem: faster handlers, conflation, or dropping work is the fix. For any steady arrival rate the consumer's utilisation (arrival rate × service time) must stay well below 1.

Replay: the payoff of event-driven design

If every component's behaviour is a function of the events it receives, and time itself is delivered as an event (a timestamp on each message, plus timer events), then recording the inputs is enough to reproduce a whole session. Replaying the recorded log through the same code gives the same decisions, which supports regression tests ("did this change alter any order we sent last Tuesday?"), debugging of production incidents, and backtesting with the production code path.

import hashlib
from collections import deque


class Strategy:
    """Quotes one tick inside the touch when the spread is wide; pure function of its inputs."""

    def __init__(self) -> None:
        self.bid = self.ask = 0

    def on_quote(self, ts: int, bid: int, ask: int) -> list[str]:
        self.bid, self.ask = bid, ask
        if ask - bid >= 3:
            return [f"{ts} QUOTE {bid + 1} / {ask - 1}"]
        return []

    def on_timer(self, ts: int) -> list[str]:
        return [f"{ts} HEARTBEAT mid={(self.bid + self.ask) / 2}"]


def run(inputs: list[tuple[int, str, tuple[int, ...]]]) -> list[str]:
    strat, out = Strategy(), []
    queue = deque(inputs)  # the single input queue, in sequence order
    while queue:
        ts, kind, args = queue.popleft()  # time comes from the event, never the wall clock
        if kind == "quote":
            out += strat.on_quote(ts, *args)
        elif kind == "timer":
            out += strat.on_timer(ts)
    return out


# The recorded input log (in production: written by the gateway before processing).
log = [
    (1_000, "quote", (10000, 10002)),
    (1_250, "quote", (9999, 10003)),
    (2_000, "timer", ()),
    (2_100, "quote", (10000, 10004)),
]
live = run(log)
replayed = run(list(log))
print("\n".join(live))
digest = lambda lines: hashlib.sha256("\n".join(lines).encode()).hexdigest()[:12]
print("live", digest(live), "replay", digest(replayed), "identical:", live == replayed)

Output:

1250 QUOTE 10000 / 10002
2000 HEARTBEAT mid=10001.0
2100 QUOTE 10001 / 10003
live d112d48cd374 replay d112d48cd374 identical: True

The rules that make this work: handlers never read the wall clock (they use the event's timestamp), never draw unseeded random numbers, and never depend on hash-map iteration order or thread timing. Tests compare a digest of the output stream, so any behavioural change is caught even when nobody knew to look for it.

Knowledge check

Why do low-latency systems often run the whole feed-to-order path on a single pinned thread?

Knowledge check

A consumer processes 1 million messages per second. A burst arrives at 1.5 million per second for 4 ms. What is the backlog at the end of the burst, and roughly how long does the last message of the burst wait?

Knowledge check

A replay of yesterday's recorded inputs produces slightly different orders from the live session. Which is the most likely cause?

Key takeaways

  • Components are event handlers driven by a busy-polling loop; the hot path is usually one pinned thread with no locks, allocation or system calls.
  • Cross threads with bounded SPSC ring buffers: release/acquire on the indices, power-of-two capacity, padding against false sharing, and an explicit full-queue policy.
  • Budget latency per component and measure tails during bursts, not medians.
  • When arrivals exceed the service rate, backlog grows linearly and queueing delay dominates; a bigger queue does not fix it.
  • Deliver time as an event and avoid hidden inputs, and the recorded input log replays the session exactly.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).