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

  1. 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 duplicate ClOrdIDs within a session's trading day (we also cover what changes if a venue lacks ClOrdID deduplication). The exchange assigns OrderID and a unique ExecID for each execution event.
  2. 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/s
    

    What these numbers tell us:

    • Network and disk capacity are trivial: 90 Mbit/s is under 1% of a 10 GbE cross-connect, and 5.3 GB/day fits 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's 5,000 msg/s limit, 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,000 outbound requests per day, even a one-in-a-million race condition fires ten times every day.
  3. 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
    Logon A Authenticate and open or resume a session; announces sender's next sequence number and heartbeat interval
    Heartbeat 0 Periodic liveness signal during idle periods, or immediate reply to a TestRequest
    TestRequest 1 Probes a silent peer ("Are you still connected?") with a TestReqID that must be echoed in a Heartbeat
    ResendRequest 2 Requests retransmission of missed sequence numbers from BeginSeqNo to EndSeqNo
    SequenceReset 4 With GapFillFlag=Y, skips sequence numbers that should not be replayed (heartbeats or stale orders); with GapFillFlag=N, performs an emergency sequence reset after catastrophic state loss
    Reject 3 Session-level refusal of a malformed message (missing required tag, invalid syntax)
    Logout 5 Graceful session termination with a human-readable reason

    2. Trading system -> Exchange (application layer)

    Message FIX MsgType Purpose
    NewOrderSingle D Submit a brand-new buy or sell order
    OrderCancelRequest F Cancel all remaining open quantity of an existing order
    OrderCancelReplaceRequest G Amend an existing order's price and/or total target quantity under a new ClOrdID
    OrderStatusRequest H Query the current state of an order (used when an acknowledgement times out)
    OrderMassCancelRequest q Emergency kill switch requesting cancellation of all open orders (per symbol, session, or firm)

    3. Exchange -> Trading system (application layer)

    Message FIX MsgType Purpose
    ExecutionReport 8 Unified 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), and Order Status (I, reply to status query)
    OrderCancelReject 9 Refuses a cancel or replace (for example, "Too late to cancel" because the order already filled, or unknown order)
    BusinessMessageReject j Application-level refusal when a syntactically valid message uses an unsupported feature or unknown symbol
    OrderMassCancelReport r Confirms acceptance or rejection of a mass cancel and how many orders were affected

    Why unify acknowledgements, fills, and cancels into one ExecutionReport type? 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 sequenced ExecutionReport stream guarantees one well-defined event order per session.

  4. Payload fields, fixed-point prices, and local state schema

    Every message carries a standard session header: - MsgType, SenderCompID, TargetCompID, MsgSeqNum (per-direction counter 1, 2, ...), and SendingTime (UTC timestamp). - Replay flags: PossDupFlag=Y ("exact retransmission of this same MsgSeqNum", plus OrigSendingTime) versus PossResend=Y ("application content may have been sent earlier under a different MsgSeqNum; check ClOrdID before executing").

    Application-layer key fields by message type:

    Message Key fields Critical semantics
    NewOrderSingle ClOrdID, Account, Symbol (or SecurityID), Side (Buy/Sell), OrderQty, OrdType (Limit, Market), Price, TimeInForce (Day, IOC, GTC), TransactTime ClOrdID is our idempotency key (a unique client-generated ID ensuring retries never create duplicate orders). Unique per session per trading day.
    OrderCancelRequest ClOrdID (fresh ID for this cancel request), OrigClOrdID (currently active ClOrdID on the order), OrderID (exchange ID if known), Symbol, Side, TransactTime Every cancel request gets its own ClOrdID while pointing at OrigClOrdID.
    OrderCancelReplaceRequest ClOrdID (fresh ID), OrigClOrdID, OrderID, Symbol, Side, OrderQty (new total target size), Price, OrdType, TimeInForce, TransactTime OrderQty is the total desired quantity including already-filled shares (new LeavesQty = max(0, new OrderQty - CumQty)), never just the remaining delta!
    OrderStatusRequest ClOrdID (the ClOrdID being queried), OrderID (optional), Symbol, Side Safe read-only probe when an order ack times out.
    ExecutionReport OrderID, 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, TransactTime ExecID uniquely identifies each event; only Trade, Trade Cancel, and Trade Correct events write to our fills table (status replies never create fill rows). While open, LeavesQty = OrderQty - CumQty; terminal states (Filled, Canceled, Rejected, Expired) always have LeavesQty = 0.
    OrderCancelReject OrderID, ClOrdID (of the failed cancel/replace), OrigClOrdID, OrdStatus (order's true status), CxlRejResponseTo (Cancel vs Replace), CxlRejReason Explains why an amendment lost a race without altering existing fills.

    Never store prices as binary floating-point numbers: IEEE-754 floats represent $410.10 as 410.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.25 is 4102500).

    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_at
    

    Crash-safe ClOrdID generation: Format ClOrdID as S03-20261130-000042117 (session_id, trade_date, monotonic counter). The gateway pre-allocates counter ranges in blocks of 10,000 persisted before use; after a restart, it jumps to the next unused block so a ClOrdID can never be generated twice.

  5. 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 assigns MsgSeqNum, appends to out_journal and replicates to Standby Gateway's RAM -> writes bytes to the TCP socket.
    • Receive path: Active Gateway reads bytes from TCP, validates MsgSeqNum, appends to in_journal, and hands the parsed message to OMS -> OMS applies fill insertion, order state update, position update, and last_applied_in_seq in 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.
  6. 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=Y when MsgSeqNum was already processed Exchange rejects any repeated ClOrdID within the session's trading day rather than opening a second order
    Exchange -> Trading system Our gateway ignores messages with MsgSeqNum < next_in_seq when PossDupFlag=Y Our fills table enforces UNIQUE (session_id, trade_date, exec_id) so replayed or drop-copy fills cannot double-count positions

    Four ironclad outbound rules:

    1. One order intent -> one ClOrdID forever: Never retry an unacknowledged NewOrderSingle with a brand-new ClOrdID! Generating a new ClOrdID tells the exchange "place an additional order."
    2. Write-ahead journal before socket send: Record (session_id, seq, cl_ord_id, raw_bytes) in out_journal (replicated to standby) before calling send(). If our gateway crashes mid-call, the journal knows what might have gone out, and reconnect sequence numbers reveal whether the exchange saw it.
    3. One cancel or replace in flight per order: Keep current_cl_ord_id (last confirmed active ID on the exchange) separate from pending_cl_ord_id (currently unconfirmed cancel/replace). Why? If a replace K101 -> K102 is rejected (OrderCancelReject), the active order on the exchange is still K101! Updating current_cl_ord_id to K102 prematurely would cause our next cancel to send OrigClOrdID = K102 and fail with "Unknown order", leaving a live order stranded. If a strategy wants another price update while K102 is pending, coalesce only the latest target into next_intent and send it as soon as K102 resolves.
    4. Conservative UNKNOWN handling on ack timeout: If NewOrderSingle(K101) receives no acknowledgement within 1 s:
      • Transition the order to UNKNOWN and keep 100% of OrderQty reserved 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 after K101 proves K101 never 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 with PossResend=Y; we rely strictly on session-level ResendRequest answers plus OrderStatusRequest.)

    Three ironclad inbound rules:

    1. Single-transaction state advance: Insert into fills (if ExecType is Trade / Trade Cancel / Trade Correct), update orders and positions, and advance last_applied_in_seq atomically.
    2. Positions move only on fills insert/update: If a resend or drop copy delivers ExecID = X801 a second time, the unique constraint UNIQUE (session_id, trade_date, exec_id) turns it into a no-op.
    3. Deterministic crash replay: On OMS restart, replay in_journal entries with seq > last_applied_in_seq, then let the gateway request any network gap beyond the journal tail.
  7. 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 ResendRequest from the exchange (selective gap-fill): Suppose our TCP write stalled during a disconnect, and on reconnect the exchange sends ResendRequest(BeginSeqNo=50, EndSeqNo=53). Blindly replaying a 5-second-old NewOrderSingle would fire a stale price into a market that has already moved! Instead, FIX provides SequenceReset(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..52 collapse into a single SequenceReset(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 OrderStatusRequest can expose events out of order: - Key fills by ExecID so fill totals are order-independent, and verify sum(non-busted LastQty) == latest CumQty (alerting if CumQty jumps ahead of known fills). - Monotonic CumQty: Ignore status regressions from stale reports carrying a lower CumQty (only Trade Cancel / Trade Correct may reduce filled quantity). - Sticky terminal states: Once an order reaches FILLED, CANCELED, REJECTED, or EXPIRED, late non-terminal reports (New, Pending Cancel) cannot move its status backward (unless a Trade Cancel explicitly reopens it). - Never order events by wall-clock timestamps: Exchange clocks and firm clocks inevitably drift by milliseconds.

  8. 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_intent
    

    Trace 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.
    
  9. Session liveness, failure recovery, and trade-offs

    Heartbeats, dead-connection detection, and reconnect gate:

    • Logon & liveness: Logon negotiates HeartBtInt = 1 s (or venue minimum). If we send nothing for 1.0 s, we send Heartbeat. If we receive nothing for 1.2 s, we send TestRequest(id). If no matching Heartbeat(id) arrives within another 1.0 s (~2.2 s total), we close the TCP socket and trigger reconnect. Because 2.2 s is 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:
      1. Reconnect with exponential backoff + random jitter (100 ms, 200 ms, 400 ms, ... capped at 5 s), failing over to the venue's secondary gateway IP if primary is unreachable.
      2. Send Logon carrying our persisted next_out_seq (never ResetSeqNumFlag=Y mid-day unless instructed by exchange ops).
      3. Complete bidirectional ResendRequest / GapFill recovery.
      4. Reconciliation gate: Verify all UNKNOWN, PENDING_CANCEL, and PENDING_REPLACE orders are resolved and OMS fill totals match the drop copy before unpausing strategy order submission.

    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 via OrderStatusRequest with original ClOrdID
    Cancel ack timeout Unwanted order stays live on book Re-send OrderCancelRequest (fresh cancel ClOrdID, same OrigClOrdID); escalate to OrderMassCancelRequest + alert after N retries
    Gateway 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.
    • UNKNOWN hold + OrderStatusRequest vs. fast retry with new ID: Accepts ~1 s of conservative risk reservation during timeouts to guarantee we never double our position by accident.
    • Selective GapFill for 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.

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 (ClOrdID on orders, ExecID unique 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 UNKNOWN vs. fast retries. Waiting for an OrderStatusRequest reply or reconnect sequence check leaves an unacknowledged order uncertain for roughly 1–3 seconds while risk reserves 100% of its size as worst-case live exposure. Retrying immediately with a new ClOrdID would resolve faster when packets dropped outbound, but risks creating an unintended second live order whenever the original packet actually arrived.
  • Selective GapFill on ResendRequest vs. replaying every journaled message. A gap fill (SequenceReset with GapFillFlag=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 seconds while 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 fsync vs. memory-only journaling. Flushing out_journal to SSD before every send() 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 into next_intent keeps OrigClOrdID chains 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=value FIX (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, and ExecID architecture.

Common mistakes

  • Retrying a timed-out NewOrderSingle with a newly generated ClOrdID, 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_id when sending a replace instead of when Replaced is confirmed, causing the next cancel after a rejected replace to reference the rejected ClOrdID and fail with "Unknown order".
  • Sending remaining quantity instead of total target quantity in OrderCancelReplaceRequest.OrderQty, forgetting that FIX defines OrderQty on a replace as already_filled + desired_remaining.
  • Firing a new ResendRequest on every out-of-order packet during a burst, triggering thousands of redundant retransmissions (a resend storm) instead of tracking active_resend_range.
  • Counting fills per message or keying fills by 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 valid Trade 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 ClOrdID is 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 ExecutionReport with ExecType = Trade Cancel (bust) or Trade Correct, carrying its own unique ExecID and pointing to the original fill via ExecRefID. Our OMS processes this idempotently by ExecID, marking the original row in fills as BUSTED (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 was FILLED hours 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 acquires epoch + 1, it logs onto the exchange using the replicated sequence numbers, answers any ResendRequest, 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 duplicate ClOrdIDs, OMS CumQty and positions exactly match the simulator's matching engine, and zero orders remain stuck in UNKNOWN after recovery. Finally, replay anonymized historical production journals as regression suites and pass the exchange's mandatory certification environment before going live.

Follow-up questions

Similar questions

More Jane Street interview questions

All 47 Jane Street questions →