Order Gateway Protocol Design for Connecting to a Trading Venue
System DesignModel answerLast updated
Design the session and application messages between an in-house order management system and an external venue, covering dedupe, sequencing, replay and recovery after disconnects.
You are building the link between a firm's internal order management system and an external trading venue reachable over the network. The firm sends orders; the venue answers with acknowledgements, rejections, cancellations, and executions.
The design has to cope with:
- retransmissions after timeouts,
- orders that fill in several pieces,
- messages that arrive out of order or more than once,
- dropped connections followed by reconnection.
Answer the following:
- Which message types are needed in each direction (firm to venue, and venue to firm)?
- What are the key fields of each message (identifiers, timestamps, quantities, prices, and so on)?
- How do you achieve idempotency, ordering, and exactly-once or effectively-once handling at the application level?
- How do you manage the session (heartbeats, sequence numbers, resend and replay), and how do you handle failure modes such as timeouts, duplicates, and reconnects?
State your assumptions about order types, throughput, and latency, and explain the trade-offs you make.
Hints
Hint 1
Split the design into two layers: a session layer (sequence numbers, heartbeats, replay) and an application layer (orders and execution events). Decide which guarantees belong to each.
Hint 2
Think about which identifier makes a retried order safe to resend, and which identifier lets you recognize a repeated execution event coming back. Why must a timed-out order never be resent under a new client ID?
Hint 3
Consider what happens when a fill crosses with your cancel request, when a gap appears in inbound sequence numbers, and when your process crashes between receiving a fill and updating positions.
Hint 4
Finish with a safety net: an independent feed or end-of-day reconciliation that catches anything the protocol-level guarantees miss.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
I would split the design into two layers and keep their responsibilities separate:
- Session layer: transport reliability, per-direction sequence numbers, heartbeats, gap detection, and replay.
- Application layer: order requests, execution events, and the per-order state machine.
Real venues use FIX or binary protocols modeled on it, so I will use FIX-style vocabulary.
Assumptions I would confirm first:
- Limit and market orders, with IOC and Day time-in-force, plus cancel and cancel/replace.
- Peak around 50k messages per second per session, with bursts at the open.
- A latency budget from microseconds to low milliseconds, which limits how much synchronous persistence we can afford.
- Correctness outranks speed: never lose a fill, never double-count a fill, never send an unintended order.
- Whether the venue supports cancel-on-disconnect, order status queries, and a drop-copy feed.
Message types
Firm to venue
- Session: Logon, Logout, Heartbeat, TestRequest, ResendRequest, SequenceReset (gap fill).
- Application: NewOrder, CancelRequest, CancelReplaceRequest, OrderStatusRequest (single and mass), MassCancel (kill switch).
Venue to firm
- Session: the same set, plus a session-level Reject.
- Application: ExecutionReport, CancelReject, BusinessReject.
A single ExecutionReport type carries every order-state change (new, partial fill, fill, canceled, replaced, rejected, expired, pending states). That yields one stream of order events that is simple to dedupe and replay.
Key fields
Header on every message: sequence number (per session, per direction, strictly increasing), sender and target IDs, sending time, and a possible-duplicate flag with the original sending time on replays.
NewOrder: client order ID (unique per trading day, such as {gateway}-{date}-{counter}), account, symbol, side, quantity, order type, price, time-in-force, transact time.
Cancel / Replace: a new client order ID for the request, the original client order ID, the venue order ID if known, and the new quantity and price for a replace.
ExecutionReport: venue order ID, client order ID and original client order ID, a unique execution ID, exec type and order status, last quantity and last price (this fill only), cumulative quantity, leaves quantity, average price, venue transact time, and reject reason where relevant.
CancelReject: client order ID, original client order ID, order status, and a reason such as "too late to cancel" or "unknown order".
Prices are fixed-point integers (ticks or scaled decimals), never floating point.
Architecture
Strategies -> OMS (state machine, risk, positions)
-> Gateway (session layer, sequence store, journal, codec) <-> Venue
Drop-copy feed -> Reconciler <- OMS state
The gateway owns the connection, sequence numbers, and an append-only journal of everything sent and received. The journal is replicated to a hot standby. The OMS owns per-order state keyed by client order ID, with a secondary index on venue order ID. The reconciler compares an independent drop-copy feed against OMS positions.
Idempotency, ordering, effectively-once
Outbound. Generate and journal the client order ID before sending. The venue rejects a duplicate ID rather than creating a second order. After a timeout, never resend under a fresh ID, because that is how a position doubles. Instead, either let session-level resend replay the original message flagged as a possible duplicate, or send an order status request for that ID.
Inbound. Deduplicate on execution ID using a persistent per-day set. As defense in depth, apply a fill only if it raises cumulative quantity. The "seen" mark and the position update must commit atomically, either in one journal record or by deriving positions from journal replay.
Ordering. TCP orders bytes within a connection; sequence numbers extend that guarantee across reconnects.
- Received sequence above expected: send a ResendRequest, buffer later messages, and apply nothing until the gap closes.
- Received sequence below expected without the duplicate flag: the session is corrupt, so log out and alert.
- Across sources (primary session, drop copy, failover gateway) there is no ordering guarantee, so the state machine must tolerate reordering: treat cumulative and leaves quantity as truth, make terminal states sticky (a late pending-cancel after canceled is ignored), and accept that a fill after you sent a cancel is normal and yields "too late to cancel" or a cancel of the remainder only.
Effectively-once equals at-least-once delivery (replay) plus idempotent application (execution ID dedupe and monotonic cumulative quantity). True exactly-once over an unreliable network is not achievable, and I would say so explicitly.
def on_exec_report(er, state):
if er.exec_id in state.seen_exec_ids:
return # duplicate or replay
order = state.orders.get(er.cl_ord_id) or state.by_order_id.get(er.order_id)
if order is None:
order = state.adopt_unknown(er) # e.g. sent just before a crash
if er.exec_type in ("PARTIAL_FILL", "FILL") and er.cum_qty > order.cum_qty:
state.positions.apply(order.symbol, order.side, er.last_qty, er.last_px)
order.cum_qty, order.leaves_qty = er.cum_qty, er.leaves_qty
order.transition(er.ord_status) # ignores regressions from terminal states
state.journal.commit(er, mark_seen=er.exec_id) # atomic with the apply
Session management and failure modes
Logon. Negotiate the heartbeat interval (for example 1 second) and exchange next-expected sequence numbers. Each side immediately requests anything it missed.
Heartbeats. Send one after an idle interval. If nothing arrives for roughly one interval plus tolerance, send a TestRequest; if that goes unanswered, drop the connection and reconnect.
Replay. On a ResendRequest, resend application messages with the duplicate flag and original sending time. Replace administrative messages (heartbeats and the like) with a gap-fill SequenceReset.
Failure modes:
- Order sent, no response: do not resend under a new ID. Query status by client order ID or rely on session replay. Treat the order as "unknown, possibly live" and keep it counted in risk exposure.
- Disconnect with live orders: use cancel-on-disconnect if the venue offers it. Otherwise, after reconnect, request mass status and reconcile against OMS state.
- Gateway crash: the standby loads the journal, restores sequence numbers, and resumes. Because the journal write precedes sending, no order is lost; some may be replayed, and the venue deduplicates them.
- Duplicate or reordered fills: handled by execution ID dedupe and monotonic cumulative quantity.
- Sequence reset at start of day: reset both counters only at an agreed session boundary, never mid-day, to avoid silently losing messages.
Trade-offs
- Synchronous journaling before send costs microseconds but removes the risk of sending an order we cannot later explain. A memory-mapped journal with async replication is a common compromise.
- Strict in-order application stalls processing during a gap, but keeps the state machine simple and safe.
- A kill switch (mass cancel) and pre-trade risk limits belong in the path, even though they add latency.
Common mistakes
- Retrying a timed-out order with a new client ID.
- Deduplicating on client order ID instead of execution ID, which drops legitimate partial fills.
- Applying a fill and recording its ID in separate, non-atomic steps.
- Using floats for prices.
- Assuming a cancel always succeeds, or that a fill cannot cross with it.
- Claiming exactly-once delivery instead of effectively-once processing.
- Skipping the independent reconciliation layer.