Trading Systems, Order Books, And Message Flows
Asked of: Software Engineer
Last updated

What's being tested
These problems test whether you can design and reason about deterministic, fault-tolerant message flows around an exchange and its order book. You need to connect protocol details—framing, sequence numbers, acknowledgments, replay, and idempotency—to data-structure invariants and canonical ordering. Jane Street cares because small ambiguities in ordering or recovery can produce incorrect positions, duplicated orders, or irreconcilable trading records; a Software Engineer must make those failure modes explicit and testable.
Core knowledge
-
Message contracts should define message type, schema version, required fields, identifiers, timestamps, sequence numbers, and semantic validation. Distinguish client order ID, exchange order ID, execution ID, and correlation ID; never use a timestamp as a unique identifier.
-
A trading session commonly has connection establishment, authentication, negotiation, heartbeat, normal traffic, and logout phases. Protocols such as
`FIX`use logon messages, sender/target IDs, sequence numbers, heartbeats, resend requests, and administrative rejects. -
TCP provides ordered, reliable bytes—not messages, durability, or application-level deduplication. Implement explicit framing using a length prefix or delimiter, handle partial reads and coalesced messages, enforce maximum frame sizes, and reject malformed or oversized input.
-
Sequence numbers detect gaps and duplicates. If message arrives before , pause dependent processing and request replay; if an already-applied message reappears, use a durable idempotency key such as
(session_id, sequence_number)orexecution_id. -
Exactly-once effects usually require at-least-once delivery plus idempotent processing, not a magical network guarantee. Persist the deduplication decision and resulting state atomically, or a crash between “apply” and “record seen” can double-apply an execution.
-
A robust outbound flow separates intent persistence from transmission: write the order and client ID to a durable log, send it, then reconcile acknowledgments and executions. On restart, replay intent state and resend only messages whose effects are safely deduplicated.
-
An order book is typically indexed by price, with bids descending and asks ascending. At each price level, preserve price-time priority using a queue; cancellation and partial fills must remove or reduce the exact order, not merely subtract aggregate quantity.
-
Core order-book invariants include nonnegative quantities, no order simultaneously resting on both sides, unique live order IDs, executed quantity no greater than original quantity, and
best_bid < best_askunless a crossing state is intentionally being processed. -
Canonical execution ordering needs an explicit total order, for example
(exchange_sequence, execution_id)or(event_time, venue, venue_sequence, execution_id). If two records tie on every semantic key, retain input position or use a stable sort; never rely on hash-map iteration order. -
For executions, comparison sorting costs time and auxiliary space in common implementations. If sequence numbers lie in a bounded dense range, a bitmap or counting-style approach can approach , but sparse or adversarial IDs favor comparison sorting.
-
Reconciliation compares independently persisted views using keys, quantities, statuses, and checksums. Normalize decimal prices and quantities to fixed-point integers, define tolerances only when justified, and classify missing, duplicated, stale, and conflicting records separately rather than hiding them behind one mismatch count.
-
Recovery must be deterministic: snapshot the book at sequence , then replay every valid event with sequence greater than . Validate snapshot sequence, event continuity, and final invariants; a checksum can detect divergence, but it cannot explain or repair it.
Worked example — Design exchange–trading system message flow
For “Design exchange–trading system message flow,” I would first clarify whether the scope is one client-to-exchange session or a full order lifecycle, the required latency and availability, whether orders may be retried, and what the exchange guarantees about sequence numbers and replay. I would state assumptions: messages use framed `FIX`-like records, the transport is `TCP`, and correctness of order and execution effects matters more than availability during an unrecoverable sequence gap. I would organize the answer around four pillars: versioned message contracts, session/heartbeat state machines, durable outbound and inbound sequencing, and idempotent recovery with observability. I would describe an order path from durable client intent to exchange acknowledgment, order acceptance or rejection, execution reports, and final reconciliation. I would explicitly distinguish transport acknowledgment from business acknowledgment: receiving bytes does not mean the order was accepted or executed. The key tradeoff is whether to block all later messages on a gap or process independent messages concurrently; blocking simplifies deterministic state but increases latency, while concurrency requires stronger per-order causal handling. I would close by saying that, with more time, I would specify crash-recovery transitions, replay limits, metrics such as gap rate and acknowledgment `p99`, and property-based tests for duplicate and reordered messages.
A second angle
For “Sort trade executions into a canonical order,” the same correctness principle appears without session negotiation or network recovery. The framing shifts to defining a total ordering across venues, normalizing timestamps and identifiers, handling ties, and choosing an algorithm that fits the input size and memory budget. A strong answer should reject “sort by timestamp” as incomplete because clocks can have equal, skewed, or lower-resolution values. It should also preserve determinism across runs, since downstream reconciliation and position calculations must produce identical results from identical inputs. If records arrive incrementally, I would discuss buffering by watermark or using a priority queue, while clearly stating the lateness assumption.
Common pitfalls
Pitfall: Treating
`TCP`as a message protocol or claiming it provides exactly-once delivery.`TCP`only gives an ordered byte stream; application framing, durable sequencing, replay, and idempotent effects remain the service’s responsibility.
Pitfall: Saying “sort by execution timestamp” or “compare database row counts” without defining tie-breaking and semantic reconciliation. A better answer specifies a total order and compares normalized identities, quantities, statuses, and sequence continuity.
Pitfall: Jumping straight to
`Kafka`, databases, or microservices without first stating invariants and failure behavior. Interviewers want to hear what happens after a timeout, duplicate, crash, gap, partial fill, or ambiguous acknowledgment—not just a component diagram.
Connections
The interviewer may pivot to matching-engine data structures, event sourcing and snapshot recovery, distributed consensus and failure detectors, or property-based testing. They may also ask how to expose operational signals such as sequence gaps, replay volume, stale sessions, and reconciliation mismatches without changing the correctness model.
Further reading
-
FIX Protocol — Session Layer — authoritative coverage of logon, sequence numbers, heartbeats, resend requests, and rejects.
-
Designing Data-Intensive Applications by Martin Kleppmann — strong treatment of logs, delivery semantics, idempotency, replication, and recovery.
-
The Art of Computer Programming, Vol. 3: Sorting and Searching by Donald Knuth — rigorous background for ordering, stable sorting, and deterministic algorithms.
Practice questions
Related concepts
- Crypto Trading And Order Routing SystemsSystem Design
- Order Book Data Structures And Market Data AggregationSoftware Engineering Fundamentals
- Low-Latency Trading System ArchitectureSystem Design
- Crypto Trading Order LifecycleSystem Design
- Order Book And Matching Engine Data StructuresCoding & Algorithms
- Transactional Banking System DesignSystem Design