Sub topic 9
Byte stream versus message boundaries
This chapter assumes you know the layered network model, what an IP packet is, and how ports identify sockets. It also assumes you have read the earlier chapters on UDP datagrams and on TCP sequence numbers, acknowledgments and retransmission. You should be able to read short Python socket programs.
The central fact is simple. UDP keeps message boundaries. TCP does not. Many bugs in network code come from forgetting this, so this chapter explains the mechanism and the usual fix.
Two different contracts
A UDP socket works with datagrams. Each sendto call produces one datagram. Each recvfrom call returns exactly one datagram, or fails. The receiver never sees half a datagram or two datagrams merged together. If the receive buffer is smaller than the datagram, the extra bytes are discarded.
A TCP socket works with a byte stream. TCP promises that the bytes arrive in the order they were sent, without gaps or duplicates. It makes no promise about how those bytes are grouped into recv calls. The sender's send calls are not recorded anywhere in the protocol.
| Property | UDP | TCP |
|---|---|---|
| Unit the application sees | Datagram | Byte stream |
| One `send` equals one `recv` | Yes, if the datagram arrives | No |
| Message boundaries preserved | Yes | No |
| Ordering | Not guaranteed | Guaranteed |
| Loss | Silent | Repaired by retransmission |
| Maximum single message | About 65,507 bytes of payload over IPv4 | No limit, since it is a stream |
Why TCP loses the boundaries
The TCP header carries a sequence number that counts bytes, not messages. When your program calls sendall(b"hello ") and then sendall(b"world"), the kernel copies those bytes into a send buffer. TCP then cuts the buffer into segments when it decides to transmit. That decision depends on several things:
- The maximum segment size (MSS), which is usually about 1460 bytes on Ethernet.
- The receiver's advertised window, covered in the flow control chapter.
- The congestion window, covered in the congestion control chapter.
- Algorithms such as Nagle's algorithm, which may hold small writes back so they can be combined with later ones.
The receiver's kernel does the reverse. It places arriving bytes into a receive buffer in sequence order. A call to recv(n) returns whatever is available, up to n bytes. It returns as soon as at least one byte is available, so it can return fewer bytes than you asked for.
Segment boundaries on the wire and send boundaries in your program are therefore unrelated. Two writes can arrive as one read. One write can arrive as several reads. A read can also end in the middle of a write.
The example above is one possible outcome. On a quiet loopback connection the same program usually returns b"hello world" in a single read. That makes the bug hard to find in testing. The code appears to work until the network adds delay, loss or load.
Observing the behavior
The echo server and client from the sockets chapter show this. The client sends two writes, half-closes its sending side with shutdown(SHUT_WR), and reads until the server closes. It joins the chunks, so the result is correct whatever the chunk sizes.
import socket
with socket.create_connection(("127.0.0.1", 9000)) as s:
s.sendall(b"hello ")
s.sendall(b"world")
s.shutdown(socket.SHUT_WR)
chunks = []
while True:
data = s.recv(1024)
if not data:
break
chunks.append(data)
print(b"\".join(chunks) if False else b"".join(chunks))The client never assumes that one recv returns b"hello " and a second returns b"world". It collects bytes until the server signals the end of the stream. The end of the stream is the empty result from recv, which means the peer has closed its sending direction.
For UDP the opposite holds. The exchange below sends one datagram and gets back the same datagram whole.
import socket
# Server (run in one process)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
srv.bind(("127.0.0.1", 9001))
data, addr = srv.recvfrom(2048)
srv.sendto(data, addr)
# Client (run in another process)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as cli:
cli.settimeout(2)
cli.sendto(b"ping", ("127.0.0.1", 9001))
try:
reply, _ = cli.recvfrom(2048)
print(reply)
except socket.timeout:
print("no reply")If the datagram arrives, reply is exactly b"ping". The server needs no loop to reassemble it. The cost is that nothing tells the client if the datagram was lost, so it needs a timeout.
Framing: putting boundaries back
Applications on TCP almost always need messages. The solution is framing, which means defining inside the byte stream where each message starts and ends. Three methods are common.
Delimiters
The sender ends each message with a special byte sequence, such as a newline. HTTP/1.1 headers use CRLF (\r\n) and end with an empty line. The receiver buffers bytes and splits on the delimiter.
Gotchas:
- The delimiter must never appear inside the data, or it must be escaped. This is hard for binary data.
- The receiver must keep leftover bytes after the last delimiter for the next read.
- A malicious peer can send data without ever sending a delimiter, so you need a maximum message size.
Length prefix
The sender writes a fixed-size length field and then that many bytes. The receiver reads the length, then reads exactly that many bytes. Many binary protocols work this way. Use a fixed byte order, usually big-endian ("network byte order").
Gotchas:
- You must read the length field itself in a loop, because even 4 bytes can arrive in two pieces.
- Check the length against a limit before allocating memory. Otherwise a peer can claim a 4 GB message.
- Choose the field width deliberately. Two bytes limit messages to 65,535 bytes.
Fixed-size messages
Every message has the same length. This is the simplest method and works for small fixed records. It wastes space and is hard to change later.
A length-prefixed implementation
The helper below reads exactly n bytes from a TCP socket. It is the building block for length-prefixed framing.
import socket
import struct
MAX_MESSAGE = 1_000_000
def recv_exact(sock: socket.socket, n: int) -> bytes:
buf = bytearray()
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("peer closed before message was complete")
buf.extend(chunk)
return bytes(buf)
def send_message(sock: socket.socket, payload: bytes) -> None:
if len(payload) > MAX_MESSAGE:
raise ValueError("message too large")
sock.sendall(struct.pack("!I", len(payload)) + payload)
def recv_message(sock: socket.socket) -> bytes:
header = recv_exact(sock, 4)
(length,) = struct.unpack("!I", header)
if length > MAX_MESSAGE:
raise ValueError("peer announced an oversized message")
return recv_exact(sock, length)The "!I" format means network byte order and an unsigned 4-byte integer. recv_exact treats an empty recv result in the middle of a message as an error. At a clean message boundary, a closed connection is a normal end, so a production reader would check for that case before reading the header.
Common errors
- Assuming one
recvpersend. It passes on loopback and fails in production. Fix it with framing. - Ignoring the return value of
send. On a socket,sendmay accept fewer bytes than you gave it.sendallloops until everything is queued, or raises an error. - Treating
recv(n)as "read exactly n". It returns up tonbytes. Use a loop such asrecv_exact. - Using a too-small UDP receive buffer.
recvfrom(10)on a 100-byte datagram returns 10 bytes and silently drops the other 90. - Sending UDP datagrams larger than the path MTU. The IP layer fragments them, and losing any one fragment loses the whole datagram. Keep payloads under about 1200 to 1400 bytes unless you control the path.
- Mistaking an empty
recvfor an empty message. On TCP, an empty result means end of stream. It is not a zero-length message, because TCP cannot represent one. On UDP, a zero-length datagram is legal andrecvfromreturnsb"".
Edge cases
- Partial
sendon non-blocking sockets. A non-blockingsendmay queue only part of your data, andsendallmay raise an error after queuing some bytes. You then cannot tell how much was sent. Event-driven code should track its own output buffer. - Half-close. After
shutdown(SHUT_WR), the peer'srecvreturns an empty result, but the peer can still send data back. This lets one direction end without the other. - TCP urgent data. The header has an urgent pointer, but it does not create message boundaries and is rarely used.
- Protocols layered on UDP. QUIC and other protocols add their own reliability and framing on top of datagrams. They show that boundaries and reliability are separate properties.
Choosing based on boundaries
If your data is naturally a series of small, independent messages, and losing one is acceptable or handled by the application, UDP matches that shape. DNS queries and game state updates are examples. If your data is a continuous flow or a large transfer where every byte matters, TCP matches that shape, and you add framing only if you need messages inside it.
Exercise
A client calls sendall three times with 100 bytes each over TCP. The server calls recv(1024) in a loop. List two different sequences of results the server could see, and say which part of the design makes the server correct either way.
Show answer
One possible sequence is a single read of 300 bytes. Another is reads of 100, 150 and 50 bytes. Any split is possible, because TCP delivers bytes in order but does not keep the sender's write boundaries. The server is correct either way only if it does not depend on read sizes, for example by using length-prefixed or delimited framing and a buffer that accumulates bytes until a full message is present.
Exercise
A UDP server calls recvfrom(512). A client sends a 700-byte datagram. What does the server receive, and why is this different from TCP?
Show answer
The server receives the first 512 bytes, and the remaining 188 bytes are discarded without an error on most systems. UDP delivers each datagram as a unit, so the leftover bytes are not kept for a later recvfrom. In TCP, bytes not read stay in the receive buffer and are returned by the next recv.
Exercise
Why does recv_exact raise an error when recv returns an empty result, instead of returning what it has collected so far?
Show answer
An empty result means the peer closed its sending side. If that happens before n bytes have arrived, the message is incomplete, and returning partial data would let the caller parse a truncated message as if it were whole.