Lesson 2 of 9 · 20m
UDP Datagrams: Small, Fast, and Honestly Lossy
UDP preserves datagram boundaries but not delivery, order, or duplication — use it when latency and independence beat reliability.
UDP is the protocol you choose when every packet should stand alone and a late answer is worthless: DNS lookups, discovery beacons, game state snapshots, metrics, voice media. It gives you datagram boundaries and very little else. No connection, no retransmission, no ordering, no congestion-controlled byte stream.
One send means one datagram
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1.0)
sock.sendto(b"hello", ("127.0.0.1", 5353))
data, addr = sock.recvfrom(2048)Unlike TCP, recvfrom returns one datagram. If your buffer is smaller than the datagram, the excess is discarded silently on many platforms. That makes buffer sizing a protocol decision. A DNS parser using recvfrom(512) is not "being efficient"; it is implementing a truncation rule from the DNS specification.
Loss is normal behavior
Packets can be dropped by congestion, firewall policy, rate limiting, corruption, or a full socket receive buffer. They can also arrive out of order or twice. If your design cannot tolerate that, the missing reliability must live in your application.
seq = 42
payload = seq.to_bytes(4, "big") + b"temperature=19.8"
sock.sendto(payload, sensor_hub)A sequence number lets the receiver detect gaps and duplicates. It does not magically recover missing data — it makes loss observable.
UDP connected mode is a filtering convenience
Calling connect() on a UDP socket does not create a connection in the TCP sense. It pins the remote address, lets you use send/recv, and causes the kernel to reject packets from other sources. It can also surface ICMP errors locally on some platforms. Useful, but still lossy UDP.
Size limits matter
The theoretical UDP payload limit is 65,507 bytes over IPv4, but the practical safe size is often below the path MTU — roughly 1,472 bytes for UDP over a 1,500-byte Ethernet path after IPv4 and UDP headers. Larger datagrams may fragment, and fragmentation multiplies loss: losing one fragment loses the whole datagram. DNS, QUIC, and game protocols deliberately keep packets small for this reason.
Field notes
- Add a monotonic sequence number even in toy protocols; debugging UDP without one is guesswork.
- Treat every response as optional. Retry with jittered backoff or accept the miss — never loop tightly.
- Check firewall and security-group rules separately for UDP; TCP success proves nothing.
- Prefer timestamps over wall-clock strings inside telemetry datagrams; they compress and compare better.
nc -ucan mislead because shell tools buffer oddly. Validate receive behavior in Python too.
Was this lesson helpful?