Trading Gateway and Exchange Messaging Protocol
Easy · System Design · Software Engineer · Onsite
Prompt
Architect the wire protocol, message schemas, and state-machine workflow linking a trading firm's internal order/execution platform (OMS/EMS) with a remote electronic exchange over an unreliable network link.
The trading platform submits order instructions across the network and processes venue responses covering order acceptance, rejections, cancellations, and trade executions (both partial and complete fills). Because network packets can stall, arrive out of sequence, duplicate on retransmission, or drop mid-flight—for example, when a cancel request K102 on a 500-share MSFT order (K101) crosses a 200-share partial execution and a sudden TCP disconnect—the protocol must keep firm positions, open exposure, and venue state strictly synchronized.
Scope & Expectations
- Bidirectional message catalog & schemas: Specify the session-level and application-level messages in both directions along with their essential fields (client/venue identifiers, sequence counters, decimal prices, share quantities, execution statuses, and timestamps).
- Idempotency & effectively-once state transitions: Explain how client request keys, execution identifiers, and local journals prevent duplicate live orders or double-counted fills across retries and replays.
- Ordering, partial fills, and wire races: Detail how sequence numbers and the order state machine handle out-of-order delivery, partial executions, and in-flight cancel/replace race conditions.
- Session lifecycle & fault recovery: Cover logon handshakes, liveness heartbeats, gap detection and selective replay, acknowledgement timeouts, and post-disconnect reconciliation.
Step-by-step walkthrough
Clarify scope, terms, and core guarantees
Designing the link between a trading firm and an exchange is a protocol and state-machine design problem, not just a box-and-arrow diagram. Before picking message fields, let's define the core components and establish the safety guarantees our protocol must uphold:
- OMS / EMS (Order and Execution Management System): Our internal trading software that runs pre-trade risk checks, tracks every order's lifecycle and filled positions (OMS), and slices or routes strategy instructions to exchanges (EMS).
- Exchange: An external electronic marketplace reachable over TCP that matches buy and sell orders in a central order book.
- Fill (execution): A trade event where part (partial fill) or all (full fill) of an order matches against a counterparty on the exchange.
- Drop copy: A separate, read-only session from the exchange that streams an independent copy of every execution report for our firm's orders, used as a second source of truth for auditing.
- Cancel-on-disconnect (CoD): An exchange safety feature that automatically cancels our open resting orders if our network session disconnects unexpectedly.
Functional requirements
- Outbound (trading system -> exchange): Submit new orders, cancel remaining open quantity, amend price or quantity (cancel/replace), query a single order's status, and trigger an emergency mass cancel (kill switch).
- Inbound (exchange -> trading system): Receive order acknowledgements, rejects, partial and full fills, cancel/replace confirmations, cancel rejects, and unsolicited exchange events (order expirations, administrative cancels, and trade busts or corrections where the exchange cancels or adjusts an erroneous past trade).
- Resilience: Automatically handle retries, duplicate deliveries, out-of-order events, and network disconnects/reconnects without manual intervention in normal cases.
Non-functional requirements
- Zero lost fills: Our recorded positions and market exposure must match the exchange's ledger.
- Zero accidental duplicate orders: Retrying after a network timeout must never silently create a second live order in the market.
- Conservative worst-case exposure: Whenever an order's state is uncertain (for example, awaiting acknowledgement during a network blip), risk limits must assume the full order could fill.
- Low gateway overhead: Keep internal gateway processing in the tens of microseconds on the send path, avoiding synchronous disk flushes per order where possible.
- Safe crash recovery: Reconcile open orders and fills with the exchange before allowing strategies to send new orders after a crash or disconnect.
Protocol assumptions to state upfront
- We model a two-layer TCP protocol inspired by FIX 4.4 (Financial Information eXchange), the industry-standard messaging specification: a session layer (logon, heartbeats, sequence numbers, resends) underneath an application layer (orders and execution reports). Many exchanges also offer compact binary protocols (such as Nasdaq OUCH or CME iLink 3); the exact same session and idempotency mechanics apply whether fields are encoded as text tags or fixed-width bytes.
- A session is one bidirectional conversation identified by
(SenderCompID, TargetCompID). Each direction maintains its own strictly increasing integer sequence number (1, 2, 3, ...) that persists across TCP reconnects and resets once per trading day. - Our system chooses every client request ID (
ClOrdID), and the exchange rejects duplicateClOrdIDs within a session's trading day (we also cover what changes if a venue lacksClOrdIDdeduplication). The exchange assignsOrderIDand a uniqueExecIDfor each execution event.
Back-of-the-envelope numbers
Sizing one active exchange connection shows whether bandwidth, CPU, or protocol correctness is the true bottleneck:
Daily order flow on one exchange (quoting / market-making workload) new orders / day 5,000,000 cancels / day 4,000,000 (quoting strategies cancel most resting orders) cancel/replaces / day 1,000,000 total outbound app msgs/day 10,000,000 inbound execution reports ~11,000,000 (1 reply per outbound msg + ~1M fills + rejects) Message rates (6.5-hour US equities day = 23,400 seconds) average outbound rate 10,000,000 / 23,400 s = ~430 msg/s average inbound rate 11,000,000 / 23,400 s = ~470 msg/s peak burst (50x at open) ~21,400 msg/s outbound, ~23,500 msg/s inbound (~45,000 msg/s total) Session sharding venue rate limit / session assume 5,000 outbound msg/s per order-entry session minimum sessions at peak 21,400 / 5,000 = 4.3 -> at least 5; run 7-8 for headroom & failover Storage and network footprint wire size per FIX message ~250 bytes (even smaller in binary protocols: ~60-100 bytes) daily message journal 21M msgs x 250 B = ~5.3 GB / day peak network bandwidth 45,000 msg/s x 250 B = ~11.25 MB/s = ~90 Mbit/sWhat these numbers tell us:
- Network and disk capacity are trivial:
90 Mbit/sis under1%of a10 GbEcross-connect, and5.3 GB/dayfits effortlessly in memory-mapped files and local NVMe storage. - Per-session venue rate limits force session sharding: Because peak outbound traffic (
~21,400 msg/s) exceeds one session's5,000 msg/slimit, we run 7–8 parallel sessions and enforce session stickiness — every cancel or replace for an order must be routed over the exact session where that order was originally submitted. - Edge-case correctness dominates the design: At
10,000,000outbound requests per day, even a one-in-a-million race condition fires ten times every day.
- Network and disk capacity are trivial:
Session and application message catalog
Separating session-layer plumbing from application-layer trading messages keeps transport recovery clean and reusable.
1. Session layer (both directions)
Message FIX MsgType Purpose LogonAAuthenticate and open or resume a session; announces sender's next sequence number and heartbeat interval Heartbeat0Periodic liveness signal during idle periods, or immediate reply to a TestRequestTestRequest1Probes a silent peer ("Are you still connected?") with a TestReqIDthat must be echoed in aHeartbeatResendRequest2Requests retransmission of missed sequence numbers from BeginSeqNotoEndSeqNoSequenceReset4With GapFillFlag=Y, skips sequence numbers that should not be replayed (heartbeats or stale orders); withGapFillFlag=N, performs an emergency sequence reset after catastrophic state lossReject3Session-level refusal of a malformed message (missing required tag, invalid syntax) Logout5Graceful session termination with a human-readable reason 2. Trading system -> Exchange (application layer)
Message FIX MsgType Purpose NewOrderSingleDSubmit a brand-new buy or sell order OrderCancelRequestFCancel all remaining open quantity of an existing order OrderCancelReplaceRequestGAmend an existing order's price and/or total target quantity under a new ClOrdIDOrderStatusRequestHQuery the current state of an order (used when an acknowledgement times out) OrderMassCancelRequestqEmergency kill switch requesting cancellation of all open orders (per symbol, session, or firm) 3. Exchange -> Trading system (application layer)
Message FIX MsgType Purpose ExecutionReport8Unified event stream for every order state change, distinguished by ExecType:New(0, order ack),Rejected(8),Trade(F, partial or full fill),Canceled(4),Replaced(5),Pending Cancel(6),Pending Replace(E),Expired(C),Trade Cancel(H, bust),Trade Correct(G, price/qty adjustment), andOrder Status(I, reply to status query)OrderCancelReject9Refuses a cancel or replace (for example, "Too late to cancel"because the order already filled, or unknown order)BusinessMessageRejectjApplication-level refusal when a syntactically valid message uses an unsupported feature or unknown symbol OrderMassCancelReportrConfirms acceptance or rejection of a mass cancel and how many orders were affected Why unify acknowledgements, fills, and cancels into one
ExecutionReporttype? If fills traveled on one message stream and cancels on another, the receiver could see"Canceled"before a fill that actually happened earlier on the matching engine. Putting every lifecycle transition into a single sequencedExecutionReportstream guarantees one well-defined event order per session.Payload fields, fixed-point prices, and local state schema
Every message carries a standard session header: -
MsgType,SenderCompID,TargetCompID,MsgSeqNum(per-direction counter1, 2, ...), andSendingTime(UTC timestamp). - Replay flags:PossDupFlag=Y("exact retransmission of this sameMsgSeqNum", plusOrigSendingTime) versusPossResend=Y("application content may have been sent earlier under a differentMsgSeqNum; checkClOrdIDbefore executing").Application-layer key fields by message type:
Message Key fields Critical semantics NewOrderSingleClOrdID,Account,Symbol(orSecurityID),Side(Buy/Sell),OrderQty,OrdType(Limit,Market),Price,TimeInForce(Day,IOC,GTC),TransactTimeClOrdIDis our idempotency key (a unique client-generated ID ensuring retries never create duplicate orders). Unique per session per trading day.OrderCancelRequestClOrdID(fresh ID for this cancel request),OrigClOrdID(currently activeClOrdIDon the order),OrderID(exchange ID if known),Symbol,Side,TransactTimeEvery cancel request gets its own ClOrdIDwhile pointing atOrigClOrdID.OrderCancelReplaceRequestClOrdID(fresh ID),OrigClOrdID,OrderID,Symbol,Side,OrderQty(new total target size),Price,OrdType,TimeInForce,TransactTimeOrderQtyis the total desired quantity including already-filled shares (new LeavesQty = max(0, new OrderQty - CumQty)), never just the remaining delta!OrderStatusRequestClOrdID(theClOrdIDbeing queried),OrderID(optional),Symbol,SideSafe read-only probe when an order ack times out. ExecutionReportOrderID,ClOrdID,OrigClOrdID,ExecID,ExecType,OrdStatus,Symbol,Side,OrderQty,Price,LastQty&LastPx(this fill),CumQty(filled so far),LeavesQty(still open),AvgPx,ExecRefID(on busts/corrections),OrdRejReason,TransactTimeExecIDuniquely identifies each event; onlyTrade,Trade Cancel, andTrade Correctevents write to ourfillstable (status replies never create fill rows). While open,LeavesQty = OrderQty - CumQty; terminal states (Filled,Canceled,Rejected,Expired) always haveLeavesQty = 0.OrderCancelRejectOrderID,ClOrdID(of the failed cancel/replace),OrigClOrdID,OrdStatus(order's true status),CxlRejResponseTo(CancelvsReplace),CxlRejReasonExplains why an amendment lost a race without altering existing fills. Never store prices as binary floating-point numbers: IEEE-754 floats represent
$410.10as410.0999999999999659..., breaking equality checks and tick rounding. Transmit prices as exact decimal strings in text FIX and store them internally as 64-bit fixed-point integers (for example, integer units of$0.0001, so$410.25is4102500).Local state in our OMS and gateway journal:
orders order_key PK (our internal ID), session_id, symbol, side, order_qty, price_ticks, tif, state, cum_qty, leaves_qty, avg_px_ticks, exchange_order_id, current_cl_ord_id, pending_cl_ord_id (in-flight cancel/replace), next_intent cl_ord_ids cl_ord_id PK, order_key, req_kind (NEW | CANCEL | REPLACE), out_seq, sent_at fills PK (session_id, trade_date, exec_id), order_key, last_qty, last_px_ticks, status (OK | BUSTED | CORRECTED), ref_exec_id, exch_transact_time -- Note: session_id is ALWAYS the owning order-entry session, even if imported -- via drop copy, so both paths hit the exact same unique key! session_state session_id PK, trade_date, next_out_seq, next_in_seq, last_applied_in_seq, active_resend_begin, active_resend_end out_journal PK (session_id, trade_date, seq), msg_type, cl_ord_id, raw_bytes, sent_at in_journal PK (session_id, trade_date, seq), raw_bytes, recv_atCrash-safe
ClOrdIDgeneration: FormatClOrdIDasS03-20261130-000042117(session_id,trade_date, monotonic counter). The gateway pre-allocates counter ranges in blocks of10,000persisted before use; after a restart, it jumps to the next unused block so aClOrdIDcan never be generated twice.High-level architecture and message flow
Trading Strategies | order / cancel / amend intents (keyed by internal order_key) v +------------------------------+ +-------------------------------+ | OMS / Pre-Trade Risk |<-------->| OMS Store (in-memory + WAL) | | risk limits, order state | | orders, cl_ord_ids, fills | | machine, live positions | | (unique ExecID constraint) | +--------------+---------------+ +-------------------------------+ | sticky routing by order's owning session_id v +------------------------------+ sync memory replication (tens of us) | Exchange Gateway (Active) |------------------------------------------+ | sequence nums, heartbeats, | fenced by epoch lease v | resend logic, token bucket, | +------------------------------+ | write-ahead out/in journals | | Exchange Gateway (Standby) | +--------------+---------------+ +------------------------------+ | TCP cross-connect (order-entry sessions S01..S08) v +------------------------------+ | Exchange Order-Entry Gateway |---> Exchange Matching Engine +--------------+---------------+ | separate TCP session: Drop Copy (all ExecutionReports) v +------------------------------+ | Continuous Reconciler |---> Compares drop-copy fills & open orders | (independent code path) | against OMS within seconds; pages on break +------------------------------+- Send path: Strategy submits an intent -> OMS checks risk limits, assigns
ClOrdID, and routes to the owning session's gateway -> Active Gateway assignsMsgSeqNum, appends toout_journaland replicates to Standby Gateway's RAM -> writes bytes to the TCP socket. - Receive path: Active Gateway reads bytes from TCP, validates
MsgSeqNum, appends toin_journal, and hands the parsed message to OMS -> OMS applies fill insertion, order state update, position update, andlast_applied_in_seqin one atomic local transaction. - Independent verification: The Continuous Reconciler ingests the exchange's drop-copy stream on a separate session and raises an immediate break alert if any fill or open order diverges from the OMS.
- Send path: Strategy submits an intent -> OMS checks risk limits, assigns
Idempotency and effectively-once state updates
Over an unreliable network, true exactly-once message delivery is mathematically impossible: when a request times out, no protocol can distinguish "packet dropped before reaching the exchange" from "exchange executed the order, and the reply packet dropped." Instead, we achieve effectively-once processing (exact-once financial side effects) by combining at-least-once delivery (sequence numbers + retransmissions) with idempotent receivers (deduplicating via deterministic IDs at both protocol layers):
Direction Session-layer deduplication Application-layer deduplication Trading system -> Exchange Exchange ignores resent messages carrying PossDupFlag=YwhenMsgSeqNumwas already processedExchange rejects any repeated ClOrdIDwithin the session's trading day rather than opening a second orderExchange -> Trading system Our gateway ignores messages with MsgSeqNum < next_in_seqwhenPossDupFlag=YOur fillstable enforcesUNIQUE (session_id, trade_date, exec_id)so replayed or drop-copy fills cannot double-count positionsFour ironclad outbound rules:
- One order intent -> one
ClOrdIDforever: Never retry an unacknowledgedNewOrderSinglewith a brand-newClOrdID! Generating a newClOrdIDtells the exchange "place an additional order." - Write-ahead journal before socket send: Record
(session_id, seq, cl_ord_id, raw_bytes)inout_journal(replicated to standby) before callingsend(). If our gateway crashes mid-call, the journal knows what might have gone out, and reconnect sequence numbers reveal whether the exchange saw it. - One cancel or replace in flight per order: Keep
current_cl_ord_id(last confirmed active ID on the exchange) separate frompending_cl_ord_id(currently unconfirmed cancel/replace). Why? If a replaceK101 -> K102is rejected (OrderCancelReject), the active order on the exchange is stillK101! Updatingcurrent_cl_ord_idtoK102prematurely would cause our next cancel to sendOrigClOrdID = K102and fail with"Unknown order", leaving a live order stranded. If a strategy wants another price update whileK102is pending, coalesce only the latest target intonext_intentand send it as soon asK102resolves. - Conservative
UNKNOWNhandling on ack timeout: IfNewOrderSingle(K101)receives no acknowledgement within1 s:- Transition the order to
UNKNOWNand keep 100% ofOrderQtyreserved in pre-trade risk (worst-case exposure). - If the session is healthy, send
OrderStatusRequest(ClOrdID=K101). On a venue that processes a single session strictly in FIFO order, an"Unknown order"reply sent afterK101provesK101never executed; if the session dropped, wait for reconnect sequence synchronization. - (Venue nuance: if an exchange does not deduplicate
ClOrdID, we never re-send application messages under a new sequence number withPossResend=Y; we rely strictly on session-levelResendRequestanswers plusOrderStatusRequest.)
- Transition the order to
Three ironclad inbound rules:
- Single-transaction state advance: Insert into
fills(ifExecTypeisTrade/Trade Cancel/Trade Correct), updateordersandpositions, and advancelast_applied_in_seqatomically. - Positions move only on
fillsinsert/update: If a resend or drop copy deliversExecID = X801a second time, the unique constraintUNIQUE (session_id, trade_date, exec_id)turns it into a no-op. - Deterministic crash replay: On OMS restart, replay
in_journalentries withseq > last_applied_in_seq, then let the gateway request any network gap beyond the journal tail.
- One order intent -> one
Sequence numbers, ordering, and selective gap-fill
TCP guarantees byte order only inside one surviving socket. Sequence numbers (
MsgSeqNum) guarantee message order across socket drops, gateway failovers, and retransmissions.Inbound sequence state machine (with resend-storm suppression):
Incoming message with sequence number `seq` (expected = `next_in_seq`): 1. seq == next_in_seq: Journal & apply message -> next_in_seq += 1 Drain any contiguous messages waiting in `out_of_order_buffer` (101, 102, ...) If next_in_seq > active_resend_end: clear active_resend_range 2. seq > next_in_seq (sequence gap detected!): Buffer message in bounded `out_of_order_buffer[seq]` (do NOT apply out of order yet) If no ResendRequest is currently active for next_in_seq: Send ResendRequest(BeginSeqNo = next_in_seq, EndSeqNo = 0) -- 0 means "up to latest" Record active_resend_range = [next_in_seq, seq] -- avoids firing 1,000 duplicate -- ResendRequests during a burst! 3. seq < next_in_seq AND PossDupFlag == 'Y': Already processed before disconnect/resend -> safely ignore 4. seq < next_in_seq AND PossDupFlag != 'Y': Fatal protocol violation (peer lost sequence state without resetting) -> Send Logout("MsgSeqNum too low"), freeze session, page on-call!How our gateway answers a
ResendRequestfrom the exchange (selective gap-fill): Suppose our TCP write stalled during a disconnect, and on reconnect the exchange sendsResendRequest(BeginSeqNo=50, EndSeqNo=53). Blindly replaying a 5-second-oldNewOrderSinglewould fire a stale price into a market that has already moved! Instead, FIX providesSequenceReset(GapFillFlag=Y, NewSeqNo=...)to legally skip sequence numbers we no longer wish to execute:Journal seq Original message Our replay action on reconnect (4 s later) ----------- -------------------------------------- ---------------------------------------------------------- 50 Heartbeat SequenceReset(MsgSeqNum=50, GapFillFlag=Y, NewSeqNo=51) 51 NewOrderSingle(ClOrdID=C8, age = 4.2 s) Too old (> 2 s staleness limit)! Gap-fill to 52; mark C8 locally CANCELED/UNSENT so risk frees its reservation. 52 OrderCancelReplace(C5->C9, age = 3.8 s) Too old! Gap-fill to 53; original order C5 is STILL live at its old price/qty -> clear pending_cl_ord_id, notify strategy! 53 OrderCancelRequest(OrigClOrdID=C4) ALWAYS resend cancels with PossDupFlag=Y (reducing risk is always safe; if C4 already filled, exchange sends CancelReject).(Contiguous skipped entries
50..52collapse into a singleSequenceReset(MsgSeqNum=50, GapFillFlag=Y, NewSeqNo=53).)Application-level out-of-order guards: Even with session sequence numbers, importing a fill from the drop copy during recovery or polling
OrderStatusRequestcan expose events out of order: - Key fills byExecIDso fill totals are order-independent, and verifysum(non-busted LastQty) == latest CumQty(alerting ifCumQtyjumps ahead of known fills). - MonotonicCumQty: Ignore status regressions from stale reports carrying a lowerCumQty(onlyTrade Cancel/Trade Correctmay reduce filled quantity). - Sticky terminal states: Once an order reachesFILLED,CANCELED,REJECTED, orEXPIRED, late non-terminal reports (New,Pending Cancel) cannot move its status backward (unless aTrade Cancelexplicitly reopens it). - Never order events by wall-clock timestamps: Exchange clocks and firm clocks inevitably drift by milliseconds.Deep dive: Order state machine, partial fills, and cancel/replace races
PENDING_NEW --(journal + send)--> SENT --(ExecType=New)--> NEW --(Trade, Leaves>0)--> PARTIALLY_FILLED | \--(Trade, Leaves=0)----> FILLED |--(ExecType=Rejected)--> REJECTED \--(no ack after 1 s)---> UNKNOWN --(OrderStatus / Resend)--> resolved From NEW or PARTIALLY_FILLED: send Cancel --> PENDING_CANCEL + Trade (Leaves > 0) --> record fill, stay PENDING_CANCEL + Trade (Leaves == 0) --> record fill, transition to FILLED + ExecType=Canceled --> CANCELED (CumQty preserves partial fills!) + OrderCancelReject --> revert to NEW / PARTIALLY_FILLED (or FILLED) send Replace --> PENDING_REPLACE + Trade (Leaves > 0) --> record fill, stay PENDING_REPLACE + ExecType=Replaced --> current_cl_ord_id = pending_cl_ord_id, clear pending_cl_ord_id, dispatch next_intent + OrderCancelReject --> keep current_cl_ord_id & old price/qty, clear pending_cl_ord_id, dispatch next_intentTrace the four classic races that break naive OMS implementations:
Race 1 — Cancel crosses a Fill on the wire (Order K101 for 500 shares of MSFT): Us -> Exch: OrderCancelRequest(ClOrdID=K102, OrigClOrdID=K101) [K101 enters PENDING_CANCEL] Exch -> Us: ExecutionReport(ExecType=Trade, ExecID=X801, LastQty=500, CumQty=500, LeavesQty=0) -> Fill X801 recorded while PENDING_CANCEL! LeavesQty == 0 -> state becomes FILLED. Exch -> Us: OrderCancelReject(ClOrdID=K102, OrigClOrdID=K101, OrdStatus=Filled, Reason=TooLate) -> Expected loser of the race; state stays FILLED, position = +500. Race 2 — Partial Fill during Replace (Order K101 for 1,000 shares @ $410.00): Us -> Exch: OrderCancelReplaceRequest(ClOrdID=K102, OrigClOrdID=K101, OrderQty=800, Price=$410.25) Exch -> Us: Trade(ClOrdID=K101, ExecID=X801, LastQty=600, CumQty=600, LeavesQty=400) -> Note fill still carries old ClOrdID=K101! cl_ord_ids maps K101 -> same order_key. Exch -> Us: Replaced(ClOrdID=K102, OrigClOrdID=K101, OrderQty=800, CumQty=600, LeavesQty=200) -> Remaining open size is 800 - 600 = 200 shares @ $410.25, current_cl_ord_id = K102. (Had K102 asked for OrderQty=500 <= CumQty=600, exchange sets LeavesQty=0 -> FILLED!) Race 3 — Drop-copy Fill arrives before Order-Entry Ack: Drop Copy: Trade(ClOrdID=K101, ExecID=X801, LastQty=200, CumQty=200, LeavesQty=300) -> Order jumps straight from SENT to PARTIALLY_FILLED (+200 position). Order Entry: ExecutionReport(ExecType=New, ClOrdID=K101, CumQty=0, LeavesQty=500) -> CumQty (0) < our CumQty (200): recognized as stale ack; exchange_order_id saved, status stays PARTIALLY_FILLED! Race 4 — Fill arrives for an unrecognized ClOrdID: Exch -> Us: Trade(ClOrdID="MANUAL-99", ExecID=X807, LastQty=200) -> NEVER drop an exchange fill! Book +200 into a dedicated SUSPENSE account so firm-wide risk exposure stays accurate, and page operations immediately.Session liveness, failure recovery, and trade-offs
Heartbeats, dead-connection detection, and reconnect gate:
- Logon & liveness:
LogonnegotiatesHeartBtInt = 1 s(or venue minimum). If we send nothing for1.0 s, we sendHeartbeat. If we receive nothing for1.2 s, we sendTestRequest(id). If no matchingHeartbeat(id)arrives within another1.0 s(~2.2 stotal), we close the TCP socket and trigger reconnect. Because2.2 sis an eternity in automated trading, enabling cancel-on-disconnect at the venue ensures resting quotes are pulled automatically when the link drops. - Controlled reconnect & reconciliation gate:
- Reconnect with exponential backoff + random jitter (
100 ms, 200 ms, 400 ms, ...capped at5 s), failing over to the venue's secondary gateway IP if primary is unreachable. - Send
Logoncarrying our persistednext_out_seq(neverResetSeqNumFlag=Ymid-day unless instructed by exchange ops). - Complete bidirectional
ResendRequest/GapFillrecovery. - Reconciliation gate: Verify all
UNKNOWN,PENDING_CANCEL, andPENDING_REPLACEorders are resolved and OMS fill totals match the drop copy before unpausing strategy order submission.
- Reconnect with exponential backoff + random jitter (
End-to-end failure modes and mitigations:
Failure mode Financial / operational risk Protocol & system handling New-order ack timeout Blind retry creates duplicate market exposure Mark UNKNOWN, reserve full risk, query viaOrderStatusRequestwith originalClOrdIDCancel ack timeout Unwanted order stays live on book Re-send OrderCancelRequest(fresh cancelClOrdID, sameOrigClOrdID); escalate toOrderMassCancelRequest+ alert after N retriesGateway process or host crash Lost in-memory sequence state or split-brain double logon Standby gateway holds synchronously replicated journal and acquires a coordination epoch lease (a monotonically numbered lock token so a paused old primary cannot write or log on) Exchange intraday failover resets sequences Persisted sequence numbers no longer match venue Halt session strategies, treat as fresh sequence epoch, query open orders + reconcile against drop copy before resuming Strategy burst hits venue rate limit Venue throttles or disconnects session Local per-session token bucket capped ~10% below venue limit with priority queueing for cancels ahead of new orders Summary of architectural trade-offs:
- At-least-once + idempotent keys (
ClOrdID,ExecID) vs. blind retries: Eliminates duplicate orders and double-counted fills at the cost of persisting journals and unique-key tables. UNKNOWNhold +OrderStatusRequestvs. fast retry with new ID: Accepts~1 sof conservative risk reservation during timeouts to guarantee we never double our position by accident.- Selective
GapFillfor stale orders (> 2 s) vs. full journal replay: Intentionally drops delayed new orders/replaces rather than trading on stale prices, while always replaying risk-reducing cancels. - Synchronous RAM replication to standby vs. per-message disk
fsync: Keeps send-path durability overhead to tens of microseconds across one local network hop while surviving single-host hardware failure. - Cancel-on-disconnect enabled vs. disabled: Protects the firm from unmanaged fills while disconnected, at the cost of losing order-book queue priority on brief network blips.
- Logon & liveness:
Intuition & how it works
Think of connecting a trading firm's software to a stock exchange like communicating with an auction floor clerk via numbered courier envelopes over a road where messengers occasionally stall, arrive late, or lose return receipts. Every envelope you send carries two numbers: a sequential envelope number (MsgSeqNum, counting 1, 2, 3, ... for the courier link) and a unique order ticket ID (ClOrdID, an idempotency key — a client-chosen unique identifier ensuring that handing the clerk the same ticket twice never places a second bet). Every trade receipt the clerk sends back carries its own sequential envelope number plus a unique execution receipt ID (ExecID).
Why does a naive request/response API (like plain REST calls with timeouts and retries) fail catastrophically in trading? First, if your "Buy 1,000 shares" request times out because only the return packet dropped, retrying with a fresh request buys 2,000 shares — doubling your financial risk. Second, if you treat a timeout as "the order failed" and free up your risk budget, that hidden order can still fill on the exchange and breach your firm's exposure limits. Third, when a dropped TCP connection reconnects and replays missed messages, counting trade messages without deduplicating by ExecID double-counts your position.
Let's trace a concrete 5-step scenario on Session S03 showing how sequence numbers, ClOrdID, and ExecID work together when a cancel request (K102) on a 500-share MSFT order (K101) crosses a 200-share partial fill and a sudden TCP drop:
1. Send order OMS sends OutSeq=41: NewOrderSingle(ClOrdID="K101", Buy 500 MSFT @ $410.25).
Exchange replies InSeq=90: ExecutionReport(ExecType=New, ClOrdID="K101", LeavesQty=500).
2. Partial fill 200 shares trade! Exchange sends InSeq=91:
ExecutionReport(ExecType=Trade, ClOrdID="K101", ExecID="X801", LastQty=200, CumQty=200, LeavesQty=300).
OMS inserts X801 into `fills` -> position = +200, remaining open = 300.
3. Disconnect race Strategy sends OutSeq=42: OrderCancelRequest(ClOrdID="K102", OrigClOrdID="K101"),
but TCP drops BEFORE OutSeq=42 leaves! Meanwhile on the exchange, the remaining
300 shares fill (InSeq=92, ExecID="X802", LastQty=300, CumQty=500, LeavesQty=0).
4. Reconnect & sync Gateway reconnects and sends Logon(NextExpectedOut=43, ExpectedIn=92).
- Exchange missed OutSeq=42 -> sends ResendRequest(42). Because OutSeq=42 is a
CANCEL (risk-reducing), we resend OutSeq=42 with PossDupFlag=Y!
- Exchange resends InSeq=91 (PossDupFlag=Y, ExecID="X801") and InSeq=92 (ExecID="X802"):
`fills` ignores duplicate "X801", inserts new "X802" once -> position = +500, state = FILLED!
5. Clean resolution Exchange processes our resent cancel OutSeq=42 after K101 already filled, replying
InSeq=93: OrderCancelReject(ClOrdID="K102", OrigClOrdID="K101", Reason="Too late to cancel").
OMS sees K101 is already FILLED and cleanly closes out the cancel attempt.
Key trade-offs
- Effectively-once processing vs. attempting network-level exactly-once delivery. Over an asynchronous network, no transport protocol can tell a lost request apart from a lost reply. Combining at-least-once delivery (persistent sequence numbers and
ResendRequests) with idempotent state transitions (ClOrdIDon orders,ExecIDunique keys on fills) guarantees exact financial side effects, at the cost of maintaining write-ahead journals and deduplication tables across every session and drop copy (a separate read-only session streaming duplicate execution reports for independent auditing). - Holding timed-out orders in
UNKNOWNvs. fast retries. Waiting for anOrderStatusRequestreply or reconnect sequence check leaves an unacknowledged order uncertain for roughly1–3 secondswhile risk reserves 100% of its size as worst-case live exposure. Retrying immediately with a newClOrdIDwould resolve faster when packets dropped outbound, but risks creating an unintended second live order whenever the original packet actually arrived. - Selective
GapFillonResendRequestvs. replaying every journaled message. A gap fill (SequenceResetwithGapFillFlag=Y) tells the peer's session layer to advance past skipped sequence numbers without executing anything. Skipping new orders and price amendments older than~2 secondswhile always replaying cancels intentionally sacrifices stale trading opportunities rather than executing prices chosen for an old market; for a skipped replace, the gateway must also notify the strategy that its original order is still resting at its previous price. - Synchronous standby RAM replication vs. local disk
fsyncvs. memory-only journaling. Flushingout_journalto SSD before everysend()is simple but adds storage tail latency to every order; writing only to local memory is fastest (< 1 us) but loses the tail of unacknowledged messages if the host machine dies. Synchronously replicating journal entries to a standby gateway's memory inside the same rack adds only tens of microseconds while surviving any single-machine failure. - Cancel-on-disconnect (CoD) enabled vs. disabled. With cancel-on-disconnect (where the exchange automatically cancels resting orders when a session drops), our firm cannot accumulate unmanaged fills while blind during an outage, at the cost of losing time-priority queue position in the order book whenever a brief TCP blip occurs.
- Single in-flight cancel/replace per order vs. pipelining amendments. Allowing at most one pending cancel/replace (
pending_cl_ord_id) and coalescing newer strategy edits intonext_intentkeepsOrigClOrdIDchains unambiguous and avoids exchange rejections on chained pending replaces, trading off one round-trip of amendment latency when strategies re-quote faster than exchange RTT. - Text FIX vs. native binary exchange protocols. Text
tag=valueFIX (such as FIX 4.4) is human-readable and universally supported across brokers and venues, whereas native binary protocols (such as Nasdaq OUCH or CME iLink 3) avoid string parsing/formatting and shrink wire payloads ~3x; both use the exact same sequence-number,ClOrdID, andExecIDarchitecture.
Common mistakes
- Retrying a timed-out
NewOrderSinglewith a newly generatedClOrdID, which places a second independent order on the exchange whenever the original order actually arrived. - Treating an acknowledgement timeout as a rejection, releasing pre-trade risk limits while the order may actually be resting or filling on the exchange.
- Updating
current_cl_ord_idwhen sending a replace instead of whenReplacedis confirmed, causing the next cancel after a rejected replace to reference the rejectedClOrdIDand fail with"Unknown order". - Sending remaining quantity instead of total target quantity in
OrderCancelReplaceRequest.OrderQty, forgetting that FIX definesOrderQtyon a replace asalready_filled + desired_remaining. - Firing a new
ResendRequeston every out-of-order packet during a burst, triggering thousands of redundant retransmissions (a resend storm) instead of trackingactive_resend_range. - Counting fills per message or keying
fillsby the arrival session rather than the owning order-entry session, allowing resends or drop-copy imports to double-count positions. - Applying
"CumQty never decreases"blindly to trade busts, accidentally discarding validTrade Cancel(ExecType=H) reports and leaving positions overstated. - Resetting sequence numbers (
ResetSeqNumFlag=Y) on intraday reconnects, wiping out the sequence gap detection needed to recover fills missed during the outage. - Silently dropping a fill whose
ClOrdIDis unknown to the OMS, hiding real financial exposure instead of booking it into a suspense account and paging operations. - Representing prices with binary
float/double, introducing rounding drift on decimal ticks like$410.10.
Follow-up questions
- How should the OMS process an unsolicited exchange trade bust or price adjustment that arrives hours after an order reached FILLED status? The exchange sends an
ExecutionReportwithExecType = Trade Cancel(bust) orTrade Correct, carrying its own uniqueExecIDand pointing to the original fill viaExecRefID. Our OMS processes this idempotently byExecID, marking the original row infillsasBUSTED(or recording an immutable compensating adjustment row rather than deleting audit history) and updating live positions and cash balances immediately. Even if the parent order wasFILLEDhours ago, we immediately alert both risk and the trading strategy because busting one leg of a hedged trade suddenly leaves the firm with unhedged market exposure. - When failing over from a crashed primary order gateway to a warm standby, how do you prevent split-brain duplicate logons or double-sent orders? Both gateways coordinate through a short-lived lease (a time-bounded lock in a consensus store such as Raft/etcd) that issues a monotonically increasing epoch number (
epoch = 41, 42, ...). Every write to the replicated journal carries the writer's epoch, and journal nodes reject any write with a stale epoch — fencing an old gateway that merely froze during a network pause so it can never wake up and send duplicate orders alongside the new primary. Once the standby acquiresepoch + 1, it logs onto the exchange using the replicated sequence numbers, answers anyResendRequest, and runs the drop-copy reconciliation gate before opening strategy flow. - What deterministic simulation and verification harness would you build to test disconnect races and sequence recovery before certifying against a live venue? Build an in-memory deterministic fault-injecting exchange simulator that speaks the exact wire protocol and systematically injects packet drops, mid-resend disconnects, out-of-order drop-copy fills, cancel/fill wire races,
OrderCancelRejects, trade busts, and unsolicited sequence resets. Drive millions of randomized strategy intents against it using property-based tests that assert core invariants after every run: zero duplicateClOrdIDs, OMSCumQtyand positions exactly match the simulator's matching engine, and zero orders remain stuck inUNKNOWNafter recovery. Finally, replay anonymized historical production journals as regression suites and pass the exchange's mandatory certification environment before going live.
Follow-up questions
- How should the OMS process an unsolicited exchange trade bust or price adjustment that arrives hours after an order reached FILLED status?
- When failing over from a crashed primary order gateway to a warm standby, how do you prevent split-brain duplicate logons or double-sent orders?
- What deterministic simulation and verification harness would you build to test disconnect races and sequence recovery before certifying against a live venue?
Similar questions
- Designing a Minimal Imperative Language Runtime
- Designing a Small Scripting Language Compiler and VM
- Low-Latency Multi-Venue BBO Arbitrage Engine
- Multi-Store Order Book Validation and Reconciliation
- Optimal Stopping Strategy in a Two-Player Signed-Die Game
- Modeling RFQ Quote Competitiveness and Information Edge
More Jane Street interview questions
- Three-Player Fair Die Playoff Probability Medium
- Cross-Venue Top-of-Book Quote Aggregator and Arbitrage Detector Medium
- Positive-Only Integer Expression Evaluator Medium Pro
- Low-Latency Multi-Venue BBO Arbitrage Engine Medium Pro
- Probability and Strategic Game Puzzles Easy Pro
- Canonical Trade Execution Ordering Easy Pro
- Multi-Store Order Book Validation and Reconciliation Easy Pro
- Stack-Based Load/Store Language Interpreter Medium Pro
- Optimal Stopping Strategy in a Two-Player Signed-Die Game Hard Pro
- Modeling RFQ Quote Competitiveness and Information Edge Medium Pro