Skip to content

Computing foundations · Part 4 of 10

TCP vs UDP: reliability versus latency

TCP delivers bytes in order and retransmits losses, UDP sends independent datagrams with no promises. Why each exists and when to choose it.

· 2 min read

networkingprotocols

Both protocols carry data between programs on different machines, on top of IP. They make opposite trade-offs.

TCP

Transmission Control Protocol gives you a reliable, ordered stream of bytes.

  • A handshake establishes a connection before data flows.
  • Every byte is numbered. The receiver acknowledges what it got and the sender retransmits what was lost.
  • Data arrives in order, with duplicates removed.
  • Flow control stops a fast sender from overwhelming a slow receiver, and congestion control slows down when the network is overloaded.

The price is latency: setup round trips, waiting for retransmissions and a stalled stream when one packet is missing.

UDP

User Datagram Protocol sends independent messages called datagrams. It adds only ports and a checksum.

  • No connection and no handshake.
  • No guarantee of delivery, ordering or duplicate protection.
  • No built-in congestion control, so the application must behave responsibly.

The price is that the application handles loss itself, but in exchange it controls timing precisely.

When each fits

  • TCP: web pages, APIs, email, file transfer, database connections, anything where every byte must arrive correctly.
  • UDP: DNS queries, real-time voice and video, online games, telemetry, where a late packet is worthless and a lost one is better ignored than waited for.
  • QUIC builds reliable, encrypted streams on top of UDP, which is how HTTP/3 gets TCP-like reliability without TCP's blocking.
Python
import socket

receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receiver.bind(("127.0.0.1", 0))           # let the OS pick a free port
port = receiver.getsockname()[1]

sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sender.sendto(b"hello", ("127.0.0.1", port))   # no connection, just a datagram

data, _address = receiver.recvfrom(1024)
print(data)

Practical notes

  • Do not assume one send equals one receive on TCP. It is a stream with no message boundaries, so protocols add lengths or delimiters.
  • Many UDP packets are blocked or rate-limited on some networks, so real-time apps often need a fallback.

Takeaway

Choose TCP when correctness matters most, UDP when freshness matters most, and remember that higher-level protocols can mix both ideas.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.