Chapters

UDP: the fast protocol

Chapters 12 and 13 got a packet to the right machine. The Transport layer gets it to the right program. There are two main choices: UDP, which just sends, and TCP, which guarantees delivery. This chapter is about the first.

Layers, routing and transport · chapter 14 of 34 · 7 min read

What UDP is

UDP (User Datagram Protocol) is the "just send it" transport. No connection setup, no tracking, no acknowledgements. You hand it a message and it fires it off. Its unit of data is called a datagram.

You have already used UDP many times in this course without seeing it:

WherePortWhat was sent over UDP
DNS (chapter 1)53"What is the IP of api.kade.lk?" and the answer
DHCP (chapter 3)67, 68The four DORA messages, including the broadcast Discover
traceroute (chapter 13)33434+The probes on macOS and Linux
STUN (chapter 10)3478"What is my public ip:port?" for hole punching

Connectionless

UDP is connectionless: no handshake happens before data flows, and neither side keeps any state about "a conversation". Each datagram stands alone. If one is lost, UDP does not notice and does not resend it. That is the application's problem to handle, or to ignore.

LaptopDNS resolver :53datagram 1 · "A record for api.kade.lk?"datagram 2 · "34.87.120.15"Done. Two datagrams, no setup, no goodbye.With TCP, three setup messages would have to finish before the questioncould even be sent (see the TCP chapters).

Wide by design - scroll it sideways.

What UDP promises (almost nothing)

Datagrams may be lost, duplicated or arrive out of order, and UDP fixes none of it:

FeatureUDPMeaning
Guaranteed deliveryNoA lost datagram is simply gone
OrderingNoThey arrive in whatever order the network delivers them
RetransmissionNoNobody resends anything
Duplicate removalNoIf the network delivers one twice, the app gets it twice
Flow and congestion controlNoUDP sends as fast as the app asks, even if the receiver or the network cannot keep up (section 6)
Error detectionYesA checksum lets the receiver throw away damaged datagrams (chapter 15)
Message boundariesYesOne send = one datagram = one receive (section 5)
Speed and low overheadYesThe whole point

Try it. The simulator sends 12 numbered datagrams across a network that loses some, delays some and occasionally duplicates one. Watch what arrives:

Press Send.

Why it is fast

A UDP header is just 8 bytes. TCP's is at least 20, and TCP also needs a handshake before the first byte of data, plus acknowledgements and state on both sides. Less bookkeeping means less waiting:

UDPTCP
Header size8 bytes20-60 bytes
Before the first data can be sentnothing1 full round trip for the handshake (~41 ms from home to kade-api)
When one piece is lostthe rest keep flowinglater data waits until the lost piece is resent
State kept per conversationnonesequence numbers, buffers, timers on both sides
The third row matters most for live audio and video. TCP must deliver bytes in order, so one lost packet holds up everything behind it until it is resent. This is called head-of-line blocking. UDP never waits.

Messages keep their shape

A detail that changes how you write code: UDP keeps message boundaries. If the app sends a 100-byte message and then a 50-byte one, the receiver gets exactly two reads: 100 bytes, then 50. TCP is a byte stream: it may deliver the same 150 bytes as one read of 150, or 3 reads of 50. With TCP, the app must mark where each message ends (for example with a length prefix or a newline). With UDP, each datagram is one message.

UDP: datagrams

send(100) send(50)
→ recv 100 · recv 50

TCP: byte stream

send(100) send(50)
→ recv 150, or 60 + 90, or …

When to use UDP

UDP is the right choice when speed matters more than perfection, or when the application handles reliability itself. In the Kadé world:

#UseWhy UDP fitsKadé example
1Voice and video callsA dropped frame is better than a laggy oneA support call between a shopper and Kadé's help desk
2Live position updatesOnly the latest position matters; an old lost one is uselessThe delivery rider's app sending GPS every 2 seconds
3Online gamesSame: the current state beats a late old one-
4DNSOne small question, one small answer; just ask again if lostEvery lookup of api.kade.lk
5Live streamingKeep playing; do not stall to resendA live product launch video
6Broadcast and multicastOnly UDP can send to many at once; TCP is always one-to-oneDHCP Discover (chapter 3)
7Small, frequent reportsLosing one metric point does not matterkade-api sending metrics (StatsD), syslog, NTP time sync

Building reliability on top of UDP

"Unreliable" does not mean "useless". Many protocols add just the reliability they need on top of UDP, and nothing more:

DNSNo answer within a timeout (often 1-5 s)? Ask again, or ask another server. That is all it needs.
RTP (voice/video)Adds a sequence number and a timestamp to each packet. The receiver's jitter buffer holds packets for a few tens of milliseconds to put them back in order and smooth out uneven arrival, then plays them. Late or missing packets are skipped.
GamesSend the full current state often, so a lost update is replaced by the next one.
QUIC (HTTP/3)A complete reliable, encrypted transport built on UDP. It fixes TCP's head-of-line blocking by keeping separate streams independent. Modern browsers already use it with Google and Cloudflare, often on UDP port 443.

Size limits and fragmentation

The UDP length field (chapter 15) allows datagrams up to 65,535 bytes, so the most data one can carry over IPv4 is 65,507 bytes (65,535 minus 8 bytes UDP header, minus 20 bytes IP header). But anything bigger than the path MTU (chapter 13) gets split by IP into fragments, and if one fragment is lost, the whole datagram is lost. So real UDP apps keep datagrams small:

Largest that fits a 1,500 MTU1,500 − 20 (IP) − 8 (UDP) = 1,472 bytes of data
Inside GCP (MTU 1,460)1,432 bytes of data
Safe DNS answer size todayabout 1,232 bytes; bigger answers are marked "truncated" and the client asks again over TCP

UDP, NAT, firewalls and attacks

#TopicWhat happens with UDP
1NAT timeoutsThere is no "connection closed" signal, so NAT rows for UDP just time out, often after 30 seconds (chapter 10). Long-lived UDP apps send a small keepalive every 15-25 seconds, or the reply path disappears.
2FirewallsA stateful firewall treats "a datagram out, then one back on the same 5 values, soon after" as a reply. Anything else inbound needs a rule. In GCP, rules name the protocol: --allow=udp:53.
3Spoofed sourcesWith no handshake, nothing proves the source IP is real. An attacker can send a datagram with a fake source.
4Amplification attacksSend a small request to an open DNS or NTP server with the victim's IP as the fake source. The server sends a much bigger answer to the victim. Thousands of servers doing this at once is a common DDoS. Never run open resolvers.

UDP or TCP?

QuestionLeans to
Must every byte arrive, in order? (payments, orders, files, web pages)TCP
Is late data worthless? (live audio, video, positions)UDP
One tiny question and answer? (DNS, NTP)UDP
Sending to many devices at once?UDP only option
Need reliability without head-of-line blocking?QUIC on UDP
kade-api's REST API, the PayGate calls and the PostgreSQL connection to kade-db all use TCP: an order must never arrive "mostly".

Summary

#IdeaIn one lineNew terms
1UDPTransport that just sends; unit is a datagramUDP, datagram
2ConnectionlessNo handshake, no state, no resendconnectionless
3PromisesNo delivery, order, dedupe or flow control; only a checksum
4Speed8-byte header, no setup, never waits for lost datahead-of-line blocking
5BoundariesOne send = one datagram = one receivemessage boundaries, byte stream
6UsesCalls, positions, games, DNS, streaming, broadcast, metricsmulticast
7Reliability on topApps add only what they need: retries, sequence numbers, QUICRTP, jitter buffer, QUIC
8SizeStay under the MTU: ~1,472 bytes of datafragmentation
9RisksNAT timeouts, spoofing, amplificationamplification attack

Try it yourself

A DNS query over UDP

  • What to look for: The footer line SERVER: …#53(…) (UDP).
  • From section: 1. What UDP is
dig example.com

The same query over TCP

dig +tcp example.com

Your own UDP sender and receiver

  • Steps: nc -u -l 9999 in one terminal, nc -u 127.0.0.1 9999 in another
  • What to look for: Type lines: each one arrives as a datagram. Stop the listener and keep typing: no error, the data just vanishes.
  • Runs on: some Linux versions: nc -u -l -p 9999
  • From section: 2. Connectionless
nc -u -l 9999nc -u 127.0.0.1 9999

Programs listening on UDP

  • What to look for: Ports like 53, 68, 123, 5353.
  • Runs on: Linux · macOS: lsof -iUDP -n -P
  • From section: 6. When to use UDP
ss -ulnp

UDP counters

  • What to look for: "no socket" (sent to a port nobody listens on), "bad checksum", "buffer full" drops.
  • Runs on: macOS · Linux: netstat -su
  • From section: 3. What UDP promises (almost nothing)
netstat -s -p udp

Spotted a mistake, or something unclear? Suggest an edit on GitHub