4 min read
Event-driven architecture on the order path: sequencing, backpressure, recovery
Event-driven design in trading is less about brokers and more about three decisions: who assigns the order of events, what each stream does when a consumer falls behind, and how a component recovers after a gap.
"Asynchronous, scalable, resilient" describes every event-driven system on a slide and none of them at 14:30 on a payrolls Friday. In a trading stack the architecture is decided by three questions that the generic description skips: who decides the order of events, what happens when a consumer is slower than its producer, and how a component gets back to a correct state after it misses something.
Sequence is the contract
An event is a fact with a position in a stream. The position matters more than the timestamp, because two processes that apply the same events in a different order end up with different books and different positions.
The simplest robust design gives each stream a single writer that stamps a monotonically increasing sequence number, and makes every consumer check it. This is how exchange feeds work and it is worth copying internally:
- a consumer that sees sequence
n + 2afternknows immediately that it lost a message, instead of discovering it later as a position break; - a consumer that sees
ntwice can discard the duplicate, which turns at-least-once delivery into effectively-once processing with no coordination; - anything that needs a total order across streams (orders, market data, timers) is fed through one sequencer, which is the core of the LMAX architecture and of replicated state machines such as Aeron Cluster.
The alternative, ordering by wall-clock timestamps from several machines, fails in the cases that matter. Clocks disagree by more than the gap between events.
Backpressure is a per-stream decision
Every queue between two components is a statement about what happens under load, and an unbounded queue is the statement "we will find out in production". Memory grows, latency grows with it, and the data being delivered is increasingly a description of the past.
The right policy depends on what the stream carries:
| Stream | When the consumer is slow | Why |
|---|---|---|
| Top-of-book, prices to UIs | Conflate: keep the latest value per instrument | Only the current state has value |
| Trades, time and sales | Buffer within a bound, then disconnect and resync | Every event matters, but not to this consumer's schedule |
| Orders, executions | Never drop; bounded queue, reject new work upstream | Loss is a position break |
| Audit, regulatory records | Durable log, consumer may lag | Completeness over latency |
Conflation is the one that is specific to market data and it is cheap to implement. A Map keeps insertion order and overwrites in place, so the queue depth is bounded by the number of instruments and a busy instrument cannot starve a quiet one:
/** Keeps only the latest update per key; drains in first-dirtied order. */
class ConflatingQueue<K, V> {
private pending = new Map<K, V>();
offer(key: K, value: V) {
this.pending.set(key, value); // overwrites in place, keeps queue position
}
drain(max: number, handle: (key: K, value: V) => void) {
for (const [key, value] of this.pending) {
if (max-- <= 0) break;
this.pending.delete(key);
handle(key, value);
}
}
get depth() {
return this.pending.size; // bounded by the number of instruments
}
}Offering EURUSD, GBPUSD, EURUSD again and USDJPY, then draining two, delivers the second EURUSD price and GBPUSD; the first EURUSD price is never sent. That is correct for a price display and wrong for a trade tape, which is the point of deciding per stream.
The difference under load is easier to watch than to describe. Both consumers below read at the same rate from the same producer. While the producer is faster, the FIFO queue grows without bound and delivers prices that are steadily older; the conflating queue never holds more than one entry per instrument and stays current. Drag the consumer rate above the producer rate and the FIFO queue drains, but only after it has replayed every stale price in order.
This interactive figure needs JavaScript.
For streams that cannot be conflated, the slow consumer is the problem to isolate. A producer that blocks on its slowest subscriber has handed its latency to the least important client. Give each subscriber a bounded buffer, and when it overflows, disconnect that subscriber and let it recover.
Recovery: snapshot plus deltas
Gap detection and disconnection are only acceptable if rejoining is routine. The standard protocol, again borrowed from exchange feeds, has two channels: an incremental stream of sequenced deltas, and a way to request a snapshot that states the sequence number it is consistent with.
A consumer that starts, or detects a gap, does the following:
- start buffering the incremental stream;
- request a snapshot and note its sequence number
s; - discard buffered deltas with sequence
<= s, apply the rest in order; - go live.
The mistake to avoid is requesting the snapshot before subscribing to the deltas, which leaves a window in which updates are lost with nothing to detect it.
Because every component can do this, restart becomes the universal recovery mechanism. A process in an unknown state is killed and rejoins, instead of being repaired in place.
Handlers must be idempotent
Exactly-once delivery across a network does not exist; retries after a timeout produce duplicates. What can be built is at-least-once delivery plus handlers that tolerate repetition. In practice that means every event carries an identity (stream and sequence, or an execution id assigned at the source), and every state change records the identity it was caused by. Applying a fill twice then changes nothing the second time.
The same rule covers outputs. An order sent to a venue carries a client order id generated before the first attempt, so that a resend after a timeout is recognised as the same order and not a second one.
What this buys
A component built this way is a deterministic function of a sequenced input. That gives replay for debugging, a hot standby that is simply a second consumer of the same stream, and regression tests made of recorded production days. Those properties come from sequencing, bounded queues with an explicit policy, snapshot recovery and idempotent handlers. The broker in the middle is the least important choice in the design.