Cross-Venue Arbitrage Detector for a Million Quotes a Second
System DesignModel answerLast updated
Design an in-process, lock-free engine that tracks the best bid and ask across up to 16 venues for 10,000 instruments and flags crossed markets within microseconds.
Problem
A proprietary trading desk consumes top-of-book quotes from several stock exchanges. Each venue publishes, per instrument, its current best bid and best ask. If one venue's bid is higher than a different venue's ask for the same instrument, the market is crossed. The desk can buy on the cheap venue, sell on the expensive one, and lock in the difference. Your task is to design the in-process component that spots this condition and signals the execution layer.
Each incoming message looks like:
QuoteUpdate(instrument_id, venue_id, bid_price, bid_size, ask_price, ask_size, timestamp_ns)
For every instrument, the component must:
- Keep the latest quote from each venue.
- Continuously know the highest bid and lowest ask across venues.
- When the highest bid exceeds the lowest ask and they come from different venues, emit an
ArbitrageOpportunitycontaining the buy venue, sell venue, spread, and the maximum quantity that can be executed.
Constraints
- Sustained load of 1,000,000 updates/s, with bursts up to 3,000,000 updates/s.
- P99 latency below 5 microseconds from message arrival to signal emission.
- No dynamic heap allocation on the critical path.
- Up to 10,000 instruments and 16 venues.
- Multiple venue network threads deliver updates concurrently, so the design must be correct under concurrency.
What to cover in your answer
- Per-instrument and per-venue data layout: preallocation, alignment, and how you avoid cache-line contention.
- The threading model. Compare shared state with locks, lock-free shared state, and pinned single-writer shards fed by ring buffers.
- The algorithm for updating the extrema when a quote improves the top or worsens the current leader.
- Failure handling: stale venues, sequence gaps or reordering, full queues, and the trade-offs between your chosen concurrency approach and the alternatives.
Hints
Hint 1
Do the arithmetic first: 1M/s is about 1 µs per update on one core, and 10,000 x 16 quote slots is only a few MB. The hard part is contention and cache misses, not algorithmic complexity.
Hint 2
If every instrument has exactly one thread that writes to it, you need no locks on the book at all. Think about how updates from many venue threads reach that owner thread without sharing mutable state.
Hint 3
With at most 16 venues, a full rescan of one cache line may be cheaper than any clever structure. Still, describe the cheap incremental rule: a new quote that beats the leader replaces it, and only a worsening of the current leader forces a rescan.
Hint 4
A crossed market where the best bid and best ask come from the same venue is bad data, not arbitrage. Also decide how you handle a venue that goes silent or skips sequence numbers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the problem with numbers
| Quantity | Value | Consequence |
|---|---|---|
| Sustained rate | 1M/s | ~1 µs per update if one core did everything |
| Burst rate | 3M/s | ~330 ns per update on one core, so shard the work |
| State | 10,000 x 16 = 160K quote slots | A few MB, which fits in L2/L3 if laid out densely |
| Latency | P99 < 5 µs, no allocation | No locks, syscalls, allocator calls or page faults on the hot path |
The work per update is trivial: compare against at most 16 values. The real risks are cache-line contention, cache and TLB misses, and tail jitter. The design should be built around those.
Assumptions to state: prices are integer ticks (never floats), each venue provides a per-instrument sequence number, and "max executable volume" is min(bid_size at buy side, ask_size at sell side) at the top of book.
2. Data layout
Map instrument IDs to a dense index 0..N-1 at startup so lookup is an array access, not a hash.
struct alignas(64) Book {
int32_t bid_px[16]; // one cache line
int32_t ask_px[16]; // one cache line
int32_t bid_sz[16];
int32_t ask_sz[16];
uint64_t last_seq[16];
uint64_t last_ts[16];
uint16_t valid_mask;
uint8_t best_bid_v, best_ask_v;
int32_t best_bid, best_ask;
// last emitted signal (for de-duplication)
int32_t sig_spread, sig_qty;
};
- Structure of arrays: the price arrays are scanned together, so each side is exactly one 64-byte line (or one SIMD register).
- Sentinels instead of branches: an invalid venue holds
bid = INT32_MINandask = INT32_MAX, so a max/min scan ignores it automatically. - Preallocation: allocate the whole table at startup on huge pages, prefault it and
mlockit. That removes page faults and most TLB misses. Total is roughly 600 B x 10,000, about 6 MB, or about 1.5 MB per shard with 4 shards. - Single owner per book: each book is written by one core only, so its cache lines never bounce between cores.
3. Threading model: pinned single-writer shards
Venue feed threads (pinned, one per venue)
decode, look up shard_of[instrument]
|
SPSC rings, one per (venue, shard): 16 x 4 = 64 rings
|
Shard workers (pinned, isolated cores, busy-polling their rings)
update book, detect crossing
|
SPSC signal ring per shard -> execution/risk thread
- Every ring has exactly one producer and one consumer, so it needs only acquire/release atomics, with no CAS and no locks. Put head and tail on separate cache lines, and let each side cache the other's index to cut cross-core traffic.
- Rings are power-of-two sized and preallocated. Size them for the 3M/s burst times the longest plausible consumer stall, plus margin.
- A per-venue ring (rather than one shared ring per shard) preserves per-venue ordering and avoids multi-producer contention.
Why not shared books with locks or CAS? Two venues updating a hot symbol would fight over the same cache lines. Lock hold times are short, but under bursts you get convoying and unbounded tail latency, which violates a P99 target. Lock-free CAS loops fix blocking but not cache-line ping-pong.
Cost of sharding: load skew. A handful of symbols carry a disproportionate share of messages. Do not use id % N. Build a static assignment from historical message counts so each shard gets balanced load, and rebalance only outside trading hours. A single extremely hot symbol still lives on one core, so check that its peak rate fits within one core's budget (it should, at a few hundred ns per update).
4. Updating the extrema
For an update from venue v on one book:
- Sequence check. If
seq <= last_seq[v], drop it as old or duplicate. Ifseq > last_seq[v] + 1, there is a gap: clearvinvalid_mask, write sentinels to its slot, and request a snapshot. Otherwise accept. - Write the new price, size, sequence and timestamp into slot
v. - Bid side:
- If
bid_px[v] >= best_bid, this venue is the new leader. Setbest_bidandbest_bid_vin O(1). - Else if
v == best_bid_v, the leader got worse, so rescan the 16 slots for the new maximum. - Else nothing changes.
- If
- Mirror the logic for asks using minimum.
A linear scan beats a heap or tree here. Sixteen int32 values sit in one cache line, a SIMD max plus mask finds the leader in a few nanoseconds, and there is no pointer chasing or branch misprediction. Many production systems always rescan branch-free precisely because latency becomes constant.
Define tie-breaking explicitly (for example larger size first, then earlier timestamp) so results are deterministic.
5. Arbitrage detection
Signal when best_bid > best_ask and best_bid_v != best_ask_v.
- If both leaders are the same venue, that venue's own quote is crossed. This is a data error. Mark it suspect and recompute the best bid excluding the ask venue (and vice versa) before deciding.
spread = best_bid - best_ask,qty = min(bid_sz[best_bid_v], ask_sz[best_ask_v]).- Buy at
best_ask_v, sell atbest_bid_v. - Gate on
spread > fees + minimum_edge, otherwise the trade loses money. - De-duplicate: emit only when the opportunity first appears or its spread or quantity changes. Otherwise every unrelated tick on that instrument re-fires the same signal.
Per-update cost is about 50-150 ns plus roughly 100 ns per ring hop, well within the 5 µs P99.
6. Failure modes
- Stale quotes. Each worker periodically sweeps its books (no extra thread) and invalidates any venue whose
last_tsor heartbeat is older than a threshold. Invalid venues never contribute to signals. - Gaps and reordering. Handled by the sequence logic. Snapshots are replayed through the same ring so the single-writer invariant is never broken.
- Ring full. Never block a feed thread. If a ring fills, mark the affected instruments invalid for that venue and resynchronize rather than silently dropping updates, because a silent drop leaves a wrong best price.
- Slow signal consumer. Drop or overwrite stale signals. An old arbitrage signal is worse than none, since the market has probably moved.
- Clock issues. Use the local receive timestamp for staleness decisions, and the venue timestamp only for ordering diagnostics.
7. Trade-offs and common mistakes
- Sharding vs. lock-free shared state: sharding gives deterministic latency and simple reasoning but suffers from skew and needs a routing hop. Shared lock-free state avoids the hop but risks contention and is much harder to verify.
- Always rescan vs. incremental: incremental is faster on average, always-rescan has flatter latency. With 16 venues the difference is small, so choose predictability unless profiling says otherwise.
- Common mistakes: using floating-point prices, using a hash map or allocating on the hot path, locking per instrument, treating same-venue crosses as arbitrage, forgetting to de-duplicate signals, ignoring stale venues, and hashing instruments to shards without considering skew.
- Validation: replay recorded feeds in a test harness, assert invariants (single writer, best equals brute-force maximum), and measure latency with histograms on isolated cores, looking at P99.9 and not just the mean.