TCP and UDP: every byte in order, or send and move on
Six pieces of data, and one of them goes missing. Watch TCP notice, send it again and hold everything behind it, and watch UDP carry on without it.
What you'll take away
- Explain TCP's SYN, SYN-ACK and ACK, and the round trip they cost before any data
- Know how TCP spots a lost piece and resends it, and why the pieces behind it wait
- Pick TCP or UDP for a job, and say why DNS, video calls and QUIC ride UDP
- Mark message edges yourself on TCP, since three send() calls can arrive as one recv()
The 1-minute version
Tap a point and the picture below plays that step.
UDP + own resend: the app answers ok for each piece itself and sends again whatever has no answer after 120 ms. Try it with a late piece and see which one the app gets twice
A voice-call app sends audio every 20 ms. If one packet is lost on the way, what should the audio go over?
The picture: a laptop at the front of the street sends six pieces to a server at the far end; replies come back on the other lane. A light is one packet, and a red ✗ marks one the network lost. The crates by the server are its app: blue for a piece it has read, gold for one TCP is still holding back. Pieces are numbered here, where real TCP numbers bytes.
Compare them all: TCP · UDP
The same network loses piece 3. See what each one ends up with, and when.
Use it when Every byte, in order: the web over HTTP/1.1 and HTTP/2, databases, SSH, files
Skip it when Live things that are useless late: a voice call. Waiting for one lost piece delays everything after it
A model: 30 ms each way is a round number, not measured. The code below sends real TCP and UDP on this machine. Press any tile to see it large above, with when it fits.
Who uses which
| What | Over | Why |
|---|---|---|
| Web pages over HTTP/1.1 and HTTP/2 | TCP | a page needs every byte, in order |
| Web pages over HTTP/3 | QUIC, on UDP | its own resends, per stream, with TLS 1.3 built in |
| DNS lookups | UDP (TCP for big answers) | one small question; ask again if it's lost |
| Voice and video calls | UDP (RTP) | audio that arrives late is no use |
| Game positions | UDP | the next update replaces a lost one |
| Databases, SSH, email (SMTP) | TCP | a missing byte would corrupt the rest |
A port belongs to one of the two: TCP port 53 and UDP port 53 are different doors. A TCP connection is known by both addresses and both ports, so one server port takes thousands of connections at once.
TCP is a stream of bytes, not messages
TCP keeps the order of bytes, not the edges between your writes: three sends can arrive in one read, and one send can arrive in two. Every protocol on TCP marks its own edges. HTTP/1.1 uses Content-Length or chunks, HTTP/2 puts a 9-byte header with a length before each frame, and a WebSocket frame carries its length in its header. UDP is the other way round: each datagram arrives whole or not at all.
QUIC: TCP's promises, built on UDP
QUIC (RFC 9000) runs over UDP and does the resending and ordering itself, but per stream: a lost packet holds only the streams whose data it carried, where with HTTP/2 over TCP every request waits. TLS 1.3 is part of its handshake (RFC 9001), so a new connection is ready in one round trip instead of TCP's plus TLS's. It sits on UDP because firewalls and NATs pass UDP and drop protocols they don't know, and because a browser can ship a new QUIC without waiting for operating systems. HTTP/3 (RFC 9114) is HTTP over QUIC.
What the picture leaves out
Real TCP numbers bytes, and starts from a random number agreed in the handshake (RFC 9293). With SACK (RFC 2018) the receiver also says which later pieces it already has, so only the gap is sent again. When no ACKs come back at all, TCP waits for its retransmission timer: RFC 6298 asks for at least one second, Linux uses 200 ms. And TCP paces itself: it starts slowly, speeds up while ACKs come back, and slows down after a loss so a busy network isn't flooded.
In real code
# TCP and UDP side by side on 127.0.0.1, with Python's standard library only: no internet needed.
# TCP is one stream of bytes (three sends come out as one run of bytes, the edges gone), UDP keeps each datagram
# whole. A closed port: TCP's connect is refused, UDP's sendto says nothing. Run: python3 sockets.py
import socket
import struct
import threading
HOST = "127.0.0.1"
WORDS = [b"one", b"two", b"three"]
def tcp_server(handle):
srv = socket.create_server((HOST, 0)) # port 0: the OS picks a free one
def serve():
conn, _ = srv.accept()
with conn:
handle(conn)
srv.close()
t = threading.Thread(target=serve)
t.start()
return srv.getsockname()[1], t
def read_all(conn, out):
while chunk := conn.recv(4096):
out.append(chunk)
# 1. TCP: three send() calls, read back to the end: one run of bytes, no edges between the words.
got: list[bytes] = []
port, t = tcp_server(lambda c: read_all(c, got))
with socket.create_connection((HOST, port)) as c:
for w in WORDS:
c.sendall(w)
t.join()
stream = b"".join(got)
assert stream == b"onetwothree"
print(f"TCP, three sends: the server reads {stream!r}")
# 2. TCP with edges we add ourselves: two bytes of length in front of each message.
def read_exact(conn, n):
buf = b""
while len(buf) < n:
chunk = conn.recv(n - len(buf))
if not chunk:
raise ConnectionError("closed part-way")
buf += chunk
return buf
framed: list[bytes] = []
def read_framed(conn):
while head := conn.recv(2, socket.MSG_WAITALL):
(n,) = struct.unpack("!H", head)
framed.append(read_exact(conn, n))
port, t = tcp_server(read_framed)
with socket.create_connection((HOST, port)) as c:
for w in WORDS:
c.sendall(struct.pack("!H", len(w)) + w)
t.join()
assert framed == WORDS
print(f"TCP with a length in front: {[w.decode() for w in framed]}")
# 3. UDP: three datagrams, three reads, each one whole. No connection, no handshake.
rx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx.bind((HOST, 0))
rx.settimeout(2)
tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for w in WORDS:
tx.sendto(w, rx.getsockname())
dgrams = [rx.recvfrom(4096)[0] for _ in WORDS]
assert sorted(dgrams) == sorted(WORDS)
print(f"UDP, three sendto: {len(dgrams)} reads, {[d.decode() for d in dgrams]}")
# 4. A port nobody listens on. TCP: the connect is refused at once (the other side answers with RST).
# UDP: sendto just sends; nothing comes back to say no one was there.
gone = socket.create_server((HOST, 0))
closed_tcp = gone.getsockname()
gone.close() # nothing listens there any more: the OS answers a SYN with RST
try:
socket.create_connection(closed_tcp, timeout=2).close()
raise AssertionError("connected to a closed port")
except ConnectionRefusedError:
print("TCP connect to a closed port: ConnectionRefusedError")
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
probe.bind((HOST, 0))
closed = probe.getsockname()
probe.close() # now nothing listens on that UDP port
sent = tx.sendto(b"hello?", closed)
assert sent == 6
print(f"UDP sendto to a closed port: sent {sent} bytes, no error")
tx.close()
rx.close()
python3 sockets.pyIt printed:TCP, three sends: the server reads b'onetwothree' TCP with a length in front: ['one', 'two', 'three'] UDP, three sendto: 3 reads, ['one', 'two', 'three'] TCP connect to a closed port: ConnectionRefusedError UDP sendto to a closed port: sent 6 bytes, no error
Real sockets on 127.0.0.1 with Python's standard library. Three sends over TCP come out as one run of bytes; a length in front of each message puts the edges back. Three datagrams over UDP are three reads. A closed port refuses a TCP connect, while a UDP sendto there reports nothing. Really run; below is what it printed.
Common questions
What's the difference between TCP and UDP?
TCP opens a connection first, then promises every byte arrives once and in order, or tells you it broke. UDP sends each datagram once: it may be lost, duplicated or reordered, but nothing waits for a handshake and no piece waits for another.
What is TCP's three-way handshake?
The laptop sends SYN with its starting number, the server answers SYN-ACK with its own, and the laptop sends ACK. Now each side knows the other's numbering. It costs one round trip before the first data; the last ACK can travel with the data.
What happens when a TCP packet is lost?
The receiver repeats an ACK for what's missing each time a later piece arrives. Three duplicate ACKs and the sender resends that piece at once (fast retransmit). If no ACKs come at all, it resends when a timer runs out, and slows down, taking the loss as a sign the network is busy.
What's head-of-line blocking?
TCP gives the app only bytes with no gap before them, so after one lost piece everything behind it waits, even what already arrived. HTTP/2 runs many requests over one TCP connection, so one lost packet holds them all; HTTP/3 over QUIC holds only the stream with the gap.
Why does DNS use UDP?
Most DNS questions and answers fit in one packet, and TCP would spend a round trip on its handshake first. If one is lost, the resolver just asks again after a timeout; asking twice does no harm. Only answers too big to fit, and zone transfers, go over TCP.
Why does HTTP/3 (QUIC) use UDP when the web needs every byte?
QUIC does all the resending and ordering itself, but per stream, and it folds TLS 1.3 into a single round-trip handshake. A brand-new protocol on IP would be dropped by firewalls and NATs and wait for every OS kernel; UDP gets through almost everywhere.
I sent three messages over TCP. Why did they arrive stuck together?
TCP is a stream of bytes with no message edges: three send() calls may come out as one recv(), or one word may arrive in two. Mark the edges yourself, with a length up front or a newline at the end. UDP keeps each datagram whole.
Next lesson
TLS and HTTPSLevel: Deep
After TCP's handshake, HTTPS spends one more round trip on TLS; next, how the two ends agree on a secret and what the path still sees.