Exchange connectivity: sessions, sequence numbers, reconnects, and failover that does not double-fire

A venue session is stateful: sequence numbers, heartbeats and a resend protocol. Reconnecting means restoring that state correctly, order entry must be idempotent, and failover must guarantee exactly one active session — the same discipline that stops a validator double-signing.

Read the briefing
About 4 min to read 6 drills

What to remember

  1. A sequence gap means your view is wrong, not slow. Recover via resend or snapshot before trusting the book again. Trading through a gap is how desks lose money quietly.
  2. One active order-entry session per account. Always. Two sessions can both place orders. Failover is a verified handover with a kill of the old session, not an automatic race.
  3. Client order IDs are your idempotency key. A reconnect or a retry with a fresh ID becomes a duplicate order. With a stable ID you can ask the venue what happened.
  4. Cancel-on-disconnect is a venue feature — know whether yours has it. If it does not, a dropped session leaves live orders in the market with nobody watching them.
  5. Venue limits are part of the protocol. Message rates, order-to-trade ratios, cancel ratios and self-match prevention are enforced by disconnection. Rate control belongs in the gateway.

The big picture

Connectivity is where protocol correctness meets money. This topic covers session state and sequence numbers, gap recovery, idempotent order entry, the shapes venue outages actually take, and failover that cannot end with two sessions placing orders at once.

The mental model

Think of a venue session as a replicated log with money attached. Both sides count messages; either side can miss some; the protocol exists to detect and repair that. Everything you build on top must assume at-least-once delivery and a peer that can vanish mid-conversation.

In depth

Session state: login, heartbeat, sequence

A session (FIX, a binary order-entry protocol, or an exchange's websocket API) has a login handshake, a heartbeat interval, and monotonically increasing sequence numbers in each direction. Both sides track both counters. A message arriving with a higher-than-expected sequence means messages were lost; a lower one means a duplicate or a reset. The protocol's repair mechanism — a resend request in FIX, a snapshot in many binary protocols — is not optional cleverness, it is the only way back to a correct view.

Reconnect logic therefore has to decide, deliberately: resume the existing session with the stored sequence numbers, or reset and take a fresh snapshot. Getting that wrong produces a session that logs in happily and is silently missing messages.

Order entry, idempotency and reconciliation

Order entry is at-least-once with money attached. You send a new order and the connection drops before the acknowledgement: the order may be live, may be rejected, may never have arrived. The only safe design is a stable client order ID generated before the send, recorded locally, and used to ask the venue what happened — an order status request, a mass status query, or a drop-copy feed. Retrying with a fresh ID converts uncertainty into a duplicate position.

After any disconnect, reconciliation against the venue's own view of your orders and positions is mandatory before resuming: your state is a cache of theirs, and theirs is authoritative.

Failover without double-firing

Redundancy for market data is easy — take both A and B feeds and de-duplicate. Redundancy for order entry is the hard one, because two active sessions can each place orders. The rule is the same as for validator keys: exactly one active signer. In practice that means an explicit handover — quiesce the primary, confirm it is no longer connected (not merely unreachable), then activate the standby — plus per-account limits enforced server-side by the venue where available. Automatic failover on a health check is how desks discover that "unreachable" and "stopped" are different words.

Cancel-on-disconnect, where the venue supports it, is what protects you when the decision is made for you: live orders are pulled when the session drops. Where it is not supported, you need an out-of-band cancel path and you must rehearse it.

The shapes venue outages take

Name them, because each needs a different response: degraded matching (acknowledgements slow, fills delayed — reduce rate, widen or pull quotes); stale market data with a live session (the most dangerous: your book is wrong but nothing looks broken — watch feed heartbeats and sequence progress, not just socket state); cancel-only or halt states (you may only reduce risk); partial venue (some symbols or gateways affected); and post-outage sequence reset (their counters restart and your session must reset cleanly rather than sitting confused). A runbook that says "the exchange is down" covers none of these.

Myths and facts

Myth: If the socket is up, the session is healthy.

Fact: Sequence progress and heartbeats are the health signals. A live socket with a stalled feed is the most expensive failure mode there is.

Myth: Retry the order with a new ID after a timeout.

Fact: That is how you get two positions. Reuse the client order ID and query status.

Myth: Run two order-entry sessions for redundancy.

Fact: Two active sessions can both fill. Exactly one active, with a verified handover.

Myth: Gap recovery can wait until the market is quieter.

Fact: A gapped book is wrong now. Recover before trusting it, or stop trading that symbol.

Myth: Rate limits are a suggestion.

Fact: They are enforced by throttling or disconnection, and breaching them during a busy open is a self-inflicted outage.

How pros do it

  • Track sequence numbers on both directions and alert on gaps, stalls and heartbeat misses — not on socket state.
  • Generate a stable client order ID before sending; reconcile against the venue after every disconnect.
  • Exactly one active order-entry session, with handover that confirms the old one is dead.
  • Enable cancel-on-disconnect where offered; where it is not, build and rehearse an out-of-band cancel-all.
  • Enforce venue rate and ratio limits in the gateway, and monitor how close you are running to them.

Questions people ask

How do I find out what happened to an in-flight order?

Ask the venue by client order ID — an order status request, a mass status request, or the drop-copy feed — and act on their answer. The acknowledgement can always be lost, so the ID has to exist before the send. Never resend under a fresh ID; that is how uncertainty becomes a duplicate position.

Resume the session or reset it after a disconnect?

Whatever the protocol and the venue prescribe, decided in advance and written per venue: resume with stored sequence numbers where supported, otherwise reset and take a fresh snapshot. The failure is not choosing — a session that logs in happily and is silently missing messages.

How do I test failover safely?

Out of session, against the venue's test environment, with the kill step actually exercised — confirm the primary is dead, not merely unreachable, before the standby logs in. Rehearse the human handover too; the risky part is the decision, not the script.

What monitors a market-data feed properly?

Per-stream sequence progress and gap counts, heartbeat age, message rate against the expected band for the time of day, and a staleness alert on last-message age. Socket state is not a health signal: the expensive failure is a live socket with a stalled feed.

Is a drop copy worth the effort?

Yes for anything sizeable. It is an independent record of your own orders and fills from the venue's side, which is what you reconcile against after a disconnect and what settles a dispute. Without it, your only view of your position is your own cache.

Further reading

Drills · 6

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

You send a new order and the connection drops before you get an acknowledgement. What do you do?

  1. Assume it was rejected, since you saw no acknowledgement. The order may well be live; assuming otherwise trades on a wrong position.
  2. Wait for the end-of-day reconciliation file. Far too slow — you may be carrying unhedged risk for hours.
  3. Resend the order with a new client order ID so it definitely lands. That is how you end up with two orders and an unintended position.
  4. Reconnect, then query the venue for that client order ID (order status, mass status or drop copy) and act on their answer — never resend as a new order with a fresh ID. The venue is authoritative; a stable client order ID is what lets you ask.
In short

Reconnect and ask the venue what happened to that client order ID; never resend it as a new order.

Why

This is the distributed-systems idempotency problem with money attached: the acknowledgement can always be lost, so the identity must exist before the effect and the peer must be queryable by it. Every serious desk has a reconcile-on-reconnect path.

The common mistake

Resending 'to be safe'. The acknowledgement can always be lost, the order may be live, and a fresh ID turns uncertainty into a duplicate position.

Read the docs

2 Pick the strongest answer

Someone proposes that when the primary order gateway misses two heartbeats, the standby logs in and takes over automatically. What is wrong with that?

  1. Standby sessions cannot log in while a primary is connected. Some venues limit sessions per account, many do not; you cannot rely on it.
  2. Missing heartbeats means unreachable, not stopped: the primary may still be connected to the venue and able to place orders, so an automatic takeover can produce two active sessions filling simultaneously. Same failure mode as a validator double-signing — availability automation against a safety constraint.
  3. Two heartbeats is too short a threshold; five would be safe. No threshold turns 'unreachable' into 'stopped'.
  4. It is fine if both sessions use the same client order ID sequence. Shared IDs cause rejects and confusion, and do not prevent both from trading.
In short

A missed heartbeat means the primary is unreachable, not stopped, so two sessions could both place orders at once.

Why

The safe pattern is a handover, not a race: quiesce the primary, confirm with the venue (or by killing the process/host) that it is no longer connected, then activate the standby. Cancel-on-disconnect and venue-side per-account limits are the belt and braces.

The common mistake

Tuning the threshold. No number of missed heartbeats turns 'unreachable' into 'stopped'.

Read the docs

3 Scenario: what do you do next?

10:02. A venue starts acknowledging orders 400 ms late (normally 2 ms), fills are arriving out of order, and your gateway is being throttled with a rate-limit reject on roughly one in five messages. Two strategies are quoting continuously. The desk head is standing behind you.

Step 1. First action?

  1. Open a ticket with the venue and wait for their status page. Necessary in parallel, useless as a first action while you carry exposure.
  2. Reduce risk before diagnosing: pull or widen quotes on that venue, throttle outbound message rate below their limit, and confirm what is actually live at the venue by client order ID. Position safety and knowing your true state come before understanding; a throttled gateway cannot be trusted to cancel promptly either.
  3. Increase the outbound rate to get cancels through faster. That deepens the throttling and can get the session disconnected with live orders in the market.
  4. Restart the gateway to clear the throttle. A restart loses in-flight state and may leave orders live with nothing watching them.

Step 2. Quotes are pulled and rate is under the limit. Reconciliation shows three orders live that your book thought were cancelled. What now?

  1. Flatten with market orders to be safe. Crossing the spread on a degraded venue with out-of-order fills can make the position worse; cancel first.
  2. Trust your own book — it is likelier to be right. It is a cache of theirs by definition.
  3. Resume quoting at reduced size while investigating. Adding orders while your state is known-wrong is how a bad morning becomes a bad quarter.
  4. Treat the venue as authoritative: cancel those three explicitly by client order ID, verify the cancels are acknowledged, and hold the strategies off that venue until your state matches theirs. Your book is a cache; the divergence must be resolved before resuming, not traded through.

Step 3. Venue recovers at 10:40. Follow-up?

  1. Postmortem with the money and regulatory sections: exposure carried, any erroneous fills, client impact if any; then mechanisms — gateway-side rate governor with headroom, staleness and reject-rate alerts, automated reconcile-on-degradation, and a rehearsed cancel-all. Names the specific mechanisms that would have shortened it, and treats the reportable dimension explicitly.
  2. Note that the venue was degraded and close it out. Their failure became your exposure; that gap is yours to fix.
  3. Add more gateway capacity. You were throttled by their limits, not short of capacity.
In short

First reduce risk: pull quotes, slow the message rate, and check what is really live at the venue before you look for the cause.

Why

Trading incidents invert the usual order: risk first, state truth second, cause last. Interviewers listen for "the venue is authoritative", for rate control as a gateway responsibility, and for a postmortem that includes P&L and reportability.

The common mistake

Restarting the gateway to clear the throttle. It loses in-flight state and can leave live orders in the market with nothing watching them.

Read the docs

4 Read the output

Here is the feed-handler log from this morning. What happened, and what should the system have done on its own?

09:31:02.114 md   stream=A seq=4,120,881 gap_detected=0 last_msg_age_ms=2
09:31:02.118 md   stream=B seq=4,120,881 gap_detected=0 last_msg_age_ms=3
09:31:44.902 md   stream=A seq=4,131,004 gap_detected=1 expected=4,130,996 last_msg_age_ms=1
09:31:44.903 md   stream=B seq=4,130,996 gap_detected=0 last_msg_age_ms=1
09:33:10.550 oe   session=UP heartbeat_age_ms=41 seq_out=88,214 seq_in=91,003
09:35:00.000 md   stream=A seq=4,131,004 gap_detected=1 last_msg_age_ms=195,098
09:35:00.000 md   stream=B seq=4,190,772 gap_detected=0 last_msg_age_ms=2
  1. Stream A dropped 8 messages at 09:31:44 and then stopped entirely — 195 seconds stale — while B stayed healthy. The receiver should have failed over to B for the gapped range, recovered the gap from B (or a snapshot), and alerted on A's staleness rather than leaving a dead stream in the set. That is what A/B redundancy is for; the failure is not detecting and acting on staleness.
  2. Both streams are fine because B has no gaps. B is fine; the system silently kept a dead A in service, which is the defect.
  3. The order-entry session is the problem — heartbeat_age 41 ms is too high. 41 ms is healthy for a heartbeat; the market-data stream is the issue.
  4. A sequence gap of 8 is small enough to ignore. Any gap means the book may be wrong; the size only affects how much you must recover.
In short

Stream A lost 8 messages and then went silent for 195 seconds while B stayed healthy; the system should have recovered from B and alerted on A.

Why

Two lessons: gaps are recovered from the redundant stream rather than tolerated, and staleness is its own alert — a stream can hold a live socket and stop delivering. Message age since last received is the metric that catches it.

Read the docs

5 Answer out loud

Walk me through how you would build the order-entry connectivity layer for a desk on eight venues — sessions, idempotency, failover, rate control, and what you watch. Five to seven sentences.

In short

A strong answer makes the venue the source of truth, allows only one active session per account, and puts rate limits in the gateway.

What a strong answer does
  • correctness: Per-venue session state machine with explicit resume/reset policy, intent persisted before send, reconcile-on-reconnect against venue or drop copy, single-active with verified handover, gateway-side rate governor with headroom, cancel-on-disconnect where available plus rehearsed out-of-band cancel.
  • safety bias: Explicitly biases to fail closed, treats the venue as authoritative, and never automates a takeover that could produce two active sessions.
  • monitoring: Sequence progress, last-message age, reject and throttle rates, ack latency percentiles, and open-order count divergence from the venue.
  • communication: Session → idempotency → failover → rate → monitoring, with failure modes named and the market-hours operating model stated.
Why

Strong answers make the venue authoritative, make single-active structural rather than procedural, and monitor the protocol instead of the socket.

6 Quick recall

Order-entry redundancy: how many sessions may be live on one account at a time?

In short

Exactly one active session per account.

Accepted

one · exactly one · 1

Why

Exactly one. Two active sessions can each place orders, so failover is a verified handover after confirming the primary is stopped — not merely unreachable.

Next lesson Market data: multicast feeds, book building, snapshots, and the arithmetic of a busy open
Drill · Exchange connectivity
0:00

Loading…