Two transports, two jobs
In a trading stack the split is consistent across venues:
- Order entry (sending, amending, cancelling orders) uses TCP. Every message must arrive exactly once and in order, and there is one counterparty.
- Market data (the stream of book updates and trades) uses UDP multicast. One exchange publishes to thousands of subscribers, a late update is worthless, and loss is handled at the application level.
Understanding why requires knowing what each protocol does on the wire.
TCP: a reliable byte stream, and its costs
TCP gives you a connection that delivers a byte stream reliably and in order, with flow control (the receiver advertises how much it can buffer) and congestion control (the sender backs off on loss). The guarantees have costs:
- Handshake. SYN, SYN-ACK, ACK: one round trip before the first byte of data (TLS adds at least one more). Trading connections are opened once at start of day and kept alive, so this matters mainly for reconnects.
- No message boundaries. Two
sends of 40 bytes may arrive as one 80-byterecv, or as 30 and 50. Protocols such as FIX or exchange binary protocols frame messages with a length field or delimiter, and the reader must loop until a full message is buffered. - Nagle's algorithm. To avoid flooding the network with tiny packets, the sender holds back a small segment while earlier data is still unacknowledged, and coalesces it with later writes. Meanwhile many receivers use delayed ACK, waiting up to tens of milliseconds (around 40 ms on Linux, up to 200 ms elsewhere) to piggy-back the ACK on a reply. Combined, a write-write-read pattern can stall for the whole delayed-ACK timer.
- Head-of-line blocking. Because the stream is ordered, a lost segment holds back every byte behind it until the retransmission arrives. That costs at least one round trip, and if the retransmission timer fires instead, at least the minimum RTO (200 ms on Linux by default).
TCP_NODELAY disables Nagle, so each write is sent immediately. Every latency-sensitive TCP connection sets it:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)) # 0: Nagle on by default
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) != 0) # True
With Nagle off, the application is responsible for not issuing many tiny writes: build the whole message in a buffer and send it with one call (or writev).
UDP: datagrams and nothing else
UDP adds 8 bytes of header (ports, length, checksum) to IP and gives datagrams: each send is one packet with its boundaries preserved, or it is lost. There is no connection, no retransmission, no ordering, no flow or congestion control. A datagram larger than the path MTU (about 1,500 bytes on Ethernet) is fragmented, and losing any fragment loses the whole datagram, so feeds keep packets under the MTU.
For market data this is a feature: the kernel never stalls new data waiting for old data, and the application decides what loss means.
Multicast market data
With IP multicast, the exchange sends each packet once to a group address (in 224.0.0.0/4); receivers join the group (IGMP), and switches replicate the packet only onto ports with subscribers. The publisher's cost is independent of the number of subscribers, and every subscriber in the colocation hall receives the packet at nearly the same time, which matters for fairness.
Every message carries a sequence number, per channel, increasing by one. That single integer gives the receiver:
- Gap detection. Expected 6, received 9: messages 6–8 are missing.
- Duplicate suppression. Exchanges usually publish two identical feeds, A and B, over separate networks. The receiver takes whichever copy of each sequence number arrives first and discards the other ("line arbitration"). Most single-feed losses are repaired this way with no extra delay.
- Ordering. Packets can be reordered in the network, so a message may arrive after a later one.
When both lines miss a message, the options are:
- Retransmission request: ask a recovery server (often over TCP or unicast UDP) for the missing range. Fast for small gaps.
- Snapshot and replay: for large gaps or a late start, take a full book snapshot from a snapshot channel tagged with the last sequence number it includes, then apply buffered incremental messages after that number.
Crucially, an order book must not apply later updates across a gap: a missing "delete order 42" would leave a phantom price level. The handler buffers messages behind the gap, marks the book as stale (strategies stop quoting on it), and resumes once the gap is filled.
Worked example
a sequencer with gap detection
A channel's packets each carry a starting sequence number and one or more messages. They arrive as: seq 1 (3 messages), seq 4 (2), seq 9 (1), seq 10 (2), seq 6 (3, late), then seq 10 again (the B-line duplicate). Write a sequencer that delivers messages strictly in order, reports the missing range, and drops duplicates.
Show solutionHide solution
Keep expected, the next sequence number to deliver, and a dictionary of messages that arrived early. On each packet, store every message whose number is at least expected (older ones are duplicates), then deliver from the dictionary while expected is present. Anything still pending means there is a hole from expected to the smallest pending number minus one.
class Sequencer:
"""Delivers one channel's messages strictly in sequence order."""
def __init__(self, first_seq: int = 1):
self.expected = first_seq # next sequence number to deliver
self.pending: dict[int, str] = {} # arrived early, waiting for a gap to fill
def on_packet(self, seq: int, msgs: list[str]) -> list[str]:
for i, m in enumerate(msgs): # message i carries sequence number seq + i
if seq + i >= self.expected: # older ones are duplicates: drop them
self.pending.setdefault(seq + i, m)
delivered = []
while self.expected in self.pending:
delivered.append(self.pending.pop(self.expected))
self.expected += 1
return delivered
def gap(self) -> tuple[int, int] | None:
"""The missing range to request, if anything is waiting behind a hole."""
if not self.pending:
return None
return (self.expected, min(self.pending) - 1)
s = Sequencer()
packets = [(1, ["a", "b", "c"]), (4, ["d", "e"]), (9, ["i"]), (10, ["j", "k"]),
(6, ["f", "g", "h"]), (10, ["j", "k"])]
for seq, msgs in packets:
out = s.on_packet(seq, msgs)
print(f"seq={seq:<2} gap={s.gap()!s:<6} delivered={out}")
print("next expected:", s.expected)
Output:
seq=1 gap=None delivered=['a', 'b', 'c']
seq=4 gap=None delivered=['d', 'e']
seq=9 gap=(6, 8) delivered=[]
seq=10 gap=(6, 8) delivered=[]
seq=6 gap=None delivered=['f', 'g', 'h', 'i', 'j', 'k']
seq=10 gap=None delivered=[]
next expected: 12
Messages 1–5 flow straight through. Packet 9 opens the gap 6–8, so "i" and then "j", "k" are held rather than applied. When the late packet 6 arrives it fills the hole and six messages are delivered in order. The second copy of packet 10 is entirely below expected and is dropped. In production the handler would also start a timer when a gap opens: if the B line has not filled it within a short window, it sends a retransmission request for gap(), and if the gap is large it switches to snapshot recovery. Note the design choice: one message per sequence number, so the dictionary handles partial overlaps for free.
Worked example
where the microseconds go
An order gateway and the exchange are in the same data centre, 50 µs round trip. (a) How long does a 1,500-byte frame take to serialise onto a 10 Gb/s link? (b) What is the one-way propagation delay over 100 km of fibre? (c) The gateway writes a 20-byte header and then a 60-byte body with two send calls on a socket without TCP_NODELAY, and the peer uses a 40 ms delayed ACK. What is the worst-case extra delay on the body?
Show solutionHide solution
(a) bits; . Every switch hop that stores and forwards a full frame pays this again, which is why low-latency switches use cut-through forwarding.
(b) Light in fibre travels at about m/s, so 1 km takes about and 100 km about one way. This is the floor no software can beat, and why firms pay for microwave links (closer to through air) between exchanges.
(c) The header goes out immediately. The body is small and there is now unacknowledged data in flight, so Nagle holds it until the header's ACK arrives. The peer has nothing to reply with yet (it is waiting for the rest of the message), so it delays the ACK for up to 40 ms. Worst case the body leaves about 40 ms late: some 800 times the 50 µs round trip. Fixes: set TCP_NODELAY and send header and body in one write.
Knowledge check
Why do exchanges distribute market data over multicast UDP rather than TCP?
Knowledge check
Your book builder expects sequence number 5,001 and receives 5,004. Neither feed line has 5,001–5,003 yet. What should it do?
Knowledge check
What does setting TCP_NODELAY on an order-entry socket change?
Key takeaways
- TCP: reliable ordered byte stream; costs are a handshake round trip, no message framing, Nagle plus delayed ACK stalls, and head-of-line blocking on loss.
- Always set
TCP_NODELAYon latency-sensitive sockets and send each message in one write. - UDP: unreliable datagrams with boundaries preserved; keep them under the MTU.
- Market data is multicast UDP with per-channel sequence numbers: detect gaps, discard duplicates (A/B arbitration), and never apply updates across a gap.
- Recovery is retransmission for small gaps and snapshot plus replay for large ones.
- Physics sets the floor: about 4.9 µs per km of fibre and 1.2 µs to serialise 1,500 bytes at 10 Gb/s.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).