Objective
Design the component that turns an exchange's market-data stream into a correct local book, and that knows, at every moment, whether its book can be trusted. Interviewers ask "what happens when you miss a packet?" because the honest answer requires sequence numbers, buffering and a recovery protocol.
How exchanges publish
- Incremental feed: each message is a change ("add order 812 buy 300 @ 10001", or "level 10001 bid is now 900"). Small and fast, but useless on its own: you need a starting state, and every message.
- Snapshot: the full book (or the levels in it) as of a sequence number. Large, sent periodically on a separate channel or on request.
Feeds also differ by granularity: market-by-order (MBO, sometimes called L3) carries every order event with an order id, so you can rebuild queues and estimate your own queue position; market-by-price (MBP, L2) carries aggregate size per level, often for a limited depth; top of book (L1) carries only the best bid and ask. MBO lets you rebuild MBP, never the reverse.
Incremental feeds are usually UDP multicast: one send reaches every subscriber with minimal latency, but packets can be dropped and nothing retransmits them automatically. So every message carries a sequence number, increasing by one per message on its channel.
Gap detection
Keep next_seq, the sequence you expect next. For each message with sequence :
-
next_seq: apply it, advance. -
next_seq: a duplicate (common with redundant lines); drop it. -
next_seq: a gap. The book is now wrong, possibly at the touch. Mark it stale, stop trading on it, and recover.
A/B arbitration
Exchanges usually send each channel twice, on lines A and B over separate network paths. The handler takes whichever copy of each sequence number arrives first and drops the second. A gap only occurs if a message is lost on both lines.
Recovery
Two common mechanisms:
- Snapshot recovery: subscribe to the snapshot channel (or request one), buffer incrementals meanwhile, load the snapshot taken at sequence , discard buffered messages with sequence , and apply the rest in order.
- Retransmission request: ask a TCP replay server for the missing range. Good for small gaps; it is rate-limited and slower for large ones.
While recovering, the book is stale. Strategies must not quote off it; usually they pull quotes on that instrument until the handler reports it is synced again.
A book builder with gap recovery
A market-by-price builder: each update sets a level's size, and size 0 deletes the level.
from dataclasses import dataclass
@dataclass
class Update: # incremental, market-by-price: qty 0 deletes the level
seq: int
side: str # "B" or "A"
price: int # in ticks
qty: int
@dataclass
class Snapshot:
seq: int # last incremental already reflected in this snapshot
bids: dict[int, int]
asks: dict[int, int]
class BookBuilder:
def __init__(self) -> None:
self.bids: dict[int, int] = {}
self.asks: dict[int, int] = {}
self.next_seq: int | None = None # None = not synced
self.buffer: list[Update] = []
def on_update(self, u: Update) -> None:
if self.next_seq is None: # recovering: hold until a snapshot arrives
self.buffer.append(u)
return
if u.seq < self.next_seq: # duplicate (e.g. from the A/B redundant feed)
return
if u.seq > self.next_seq: # gap
print(f" gap: expected {self.next_seq}, got {u.seq}; requesting snapshot")
self.next_seq = None
self.buffer.append(u)
return
self._apply(u)
def on_snapshot(self, s: Snapshot) -> None:
if self.next_seq is not None:
return # already synced; ignore
self.bids, self.asks = dict(s.bids), dict(s.asks)
self.next_seq = s.seq + 1
pending, self.buffer = sorted(self.buffer, key=lambda u: u.seq), []
for u in pending:
self.on_update(u) # stale ones (seq <= s.seq) are dropped as duplicates
if self.next_seq is not None:
print(f" resynced at snapshot {s.seq}; next expected {self.next_seq}")
def _apply(self, u: Update) -> None:
book = self.bids if u.side == "B" else self.asks
if u.qty == 0:
book.pop(u.price, None)
else:
book[u.price] = u.qty
self.next_seq = u.seq + 1
def top(self) -> str:
if self.next_seq is None:
return "top: STALE (recovering)"
bb, ba = max(self.bids, default=None), min(self.asks, default=None)
return f"top: {self.bids.get(bb)} @ {bb} / {ba} @ {self.asks.get(ba)}"
b = BookBuilder()
b.on_snapshot(Snapshot(100, {9999: 500, 9998: 800}, {10001: 300, 10002: 700}))
events: list[Update | Snapshot] = [
Update(101, "B", 10000, 200), # new best bid
Update(102, "A", 10001, 0), # best ask level removed
Update(102, "A", 10001, 0), # duplicate: ignored
Update(104, "B", 10000, 0), # 103 was lost: gap
Update(105, "A", 10002, 650),
Snapshot(103, {10000: 200, 9999: 450, 9998: 800}, {10002: 700}),
Update(106, "B", 9999, 0),
]
for ev in events:
if isinstance(ev, Snapshot):
print(f"snapshot seq={ev.seq}")
b.on_snapshot(ev)
else:
print(f"update seq={ev.seq} {ev.side} {ev.price} -> {ev.qty}")
b.on_update(ev)
print(" " + b.top())
print("bids", dict(sorted(b.bids.items(), reverse=True)), "asks", dict(sorted(b.asks.items())))
Output:
resynced at snapshot 100; next expected 101
update seq=101 B 10000 -> 200
top: 200 @ 10000 / 10001 @ 300
update seq=102 A 10001 -> 0
top: 200 @ 10000 / 10002 @ 700
update seq=102 A 10001 -> 0
top: 200 @ 10000 / 10002 @ 700
update seq=104 B 10000 -> 0
gap: expected 103, got 104; requesting snapshot
top: STALE (recovering)
update seq=105 A 10002 -> 650
top: STALE (recovering)
snapshot seq=103
resynced at snapshot 103; next expected 106
top: 450 @ 9999 / 10002 @ 650
update seq=106 B 9999 -> 0
top: 800 @ 9998 / 10002 @ 650
bids {9998: 800} asks {10002: 650}
Worked example
following the recovery
In the run above, message 103 was lost. Explain each line from the gap onward, and why the snapshot's sequence number is essential.
Show solutionHide solution
- 104 arrives while expecting 103. Gap. The builder marks itself unsynced and buffers 104. The top of book prints STALE: the builder does not know what 103 changed, so even the touch could be wrong.
- 105 arrives. Still unsynced, so it is buffered too.
- Snapshot at seq 103 arrives. It reflects every message up to and including 103. The builder loads it (bids 10000: 200, 9999: 450, 9998: 800; asks 10002: 700), sets
next_seq= 104, and replays the buffer in order: 104 deletes the 10000 bid, 105 sets the 10002 ask to 650. Now synced, expecting 106. The lost 103 had changed 9999 from 500 to 450, and the snapshot supplied that. - 106 deletes the 9999 bid; the best bid becomes 800 @ 9998.
Without a sequence number on the snapshot, you could not know which buffered messages it already contains. Applying 104 twice is harmless here (deleting a deleted level), but applying a stale size update after the snapshot would overwrite a newer value. Snapshot plus sequence number makes recovery exact.
Worked example
what A/B arbitration buys
A channel carries 1,000,000 messages per second at peak. Each line independently drops a given message with probability . How many gaps per second with one line, and with A/B arbitration? What could make the real number much worse than this estimate?
Show solutionHide solution
One line: gaps per second, a constant stream of recoveries.
Both lines must drop the same message: , so gaps per second, about 36 per hour at sustained peak.
The independence assumption is the weak point. Losses are often correlated: a microburst that overflows a shared switch buffer, or the handler itself falling behind and its socket buffer overflowing, drops both copies. That last case is a reason to keep the handler's hot path short and to size receive buffers generously.
Normalisation
A firm trading on many venues converts each venue's protocol into one internal format, so strategies never see venue specifics:
- Prices: each venue's scaling (implied decimals, tick tables that change with price) into one integer representation.
- Symbols: venue codes into an internal instrument id.
- Events: order-level or level-level updates into a common schema; trades flagged consistently (aggressor side, auction or continuous).
- Timestamps: keep both the exchange timestamp and your receive timestamp; the difference measures feed latency.
- Book state flags: stale, recovering, trading halted, auction.
Normalisation runs on the hot path, so it should be a cheap translation (fixed-layout structs, no allocation), not a general-purpose parser.
Conflation is a related choice: when a consumer cannot keep up, send it only the latest state of each level rather than every change. It is fine for a dashboard and wrong for anything that needs every event, such as queue-position tracking.
Knowledge check
During recovery you have buffered incrementals 198, 199, 201, 202 and 204. A snapshot at sequence 200 arrives. What should the handler do?
Knowledge check
A strategy needs to estimate its own queue position at a price level. Which feed does it need?
Knowledge check
After detecting a gap, why must the book be marked stale instead of continuing to apply later messages?
Key takeaways
- Incremental feeds are small and fast but need a start state and every message; snapshots provide the start state as of a sequence number.
- Track the next expected sequence: equal means apply, lower means duplicate, higher means gap.
- On a gap: mark the book stale, buffer, load a snapshot at sequence , drop buffered messages , replay the rest, and check for further gaps.
- A/B arbitration turns per-line loss into roughly , if losses are independent; correlated drops (microbursts, a slow handler) defeat it.
- Normalise venue formats into one internal schema cheaply, and keep both exchange and receive timestamps.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).