Sub topic 14
Choosing between TCP and UDP
This chapter assumes you know the layered network model, what an IP address and a packet are, and the basics of the sockets API from the earlier chapters. It also assumes you have seen the TCP handshake, sequence numbers, flow control and congestion control. Here you use that knowledge to make a decision: given an application, which transport protocol should it use, and why?
Start from what the application needs
IP delivers packets on a best-effort basis. It may drop, duplicate, delay or reorder them. TCP and UDP differ in how much of that damage they hide from the application.
- TCP gives a reliable, ordered byte stream between two endpoints. It retransmits lost data, delivers bytes in order, limits the sender to what the receiver can hold (flow control), and slows down when the network is congested (congestion control).
- UDP gives independent datagrams. It adds ports and a checksum to IP and little else. Datagrams may be lost, duplicated or reordered, and UDP never tells you.
Neither protocol is better in general. The right question is which guarantees the application needs, and what it costs to get them.
What each guarantee costs
Every guarantee in TCP has a price. The price is often worth paying, but you should know what it is.
| Feature | What TCP does | Cost |
|---|---|---|
| Connection setup | Three-way handshake before data | One round trip before the client can send data |
| Reliability | Retransmits until acknowledged | Delay when a segment is lost |
| Ordering | Delivers bytes strictly in order | Head-of-line blocking |
| Flow control | Honors the receive window | Sender may be held back by a slow reader |
| Congestion control | Slow start, congestion avoidance | Throughput ramps up gradually, drops after loss |
| State | Connection tracked in both hosts | Memory per connection, teardown states |
UDP has none of these costs, and it also has none of the benefits. If the application needs reliability or ordering over UDP, the application must build it.
Head-of-line blocking
Suppose segments 1 through 5 are sent and segment 2 is lost. Segments 3, 4 and 5 arrive. TCP holds them in the receive buffer and does not give them to the application until segment 2 is retransmitted and received. The application sees a pause even though most of the data is already on the host.
For a file download this is harmless. The file is only useful when complete. For a live voice call, a 300 ms stall to recover one lost 20 ms audio frame is worse than a small glitch, because the late frame is no longer useful when it arrives.
Decision criteria
Work through these questions in order. Each one points toward TCP or UDP.
- Must every byte arrive, exactly once, in order? If losing or reordering data breaks correctness, you need TCP, or you need to build equivalent behavior yourself. Examples: web pages, file transfer, email, database queries, remote shells.
- Is old data worthless once newer data exists? If yes, retransmission wastes time. Examples: live video and audio, game position updates, sensor readings that are sampled every second. UDP fits well.
- Are the messages small and independent, and is one request answered by one reply? UDP avoids the handshake round trip. DNS is the standard example: a query and a response each fit in a single datagram.
- Do you need to send to many receivers at once? TCP is strictly point to point. Broadcast and multicast work with UDP only.
- Do you need your own control of timing and loss recovery? Some applications want to decide per message whether to retransmit. UDP lets you do that.
- Do you need to be a good citizen on a shared network? TCP congestion control is built in. A UDP application that sends at a fixed rate regardless of loss can crowd out TCP flows.
Typical applications
| Application | Usual transport | Reason |
|---|---|---|
| Web browsing (HTTP/1.1, HTTP/2) | TCP | Complete, ordered responses |
| Email (SMTP, IMAP) | TCP | No loss tolerated |
| SSH | TCP | Ordered interactive stream |
| DNS lookups | UDP (TCP for large answers and zone transfers) | Small request and reply, no setup delay |
| DHCP | UDP | Client has no IP address yet, uses broadcast |
| NTP | UDP | Small timestamped exchanges |
| Live voice and video | UDP | Late data is useless |
| Online games | UDP | Fresh state beats old state |
| HTTP/3 | UDP (via QUIC) | Reliability built above UDP |
Building on UDP: when reliability is your problem
Choosing UDP does not mean giving up reliability. It means you decide how much of it you need and where it lives. A protocol built on UDP might add:
- sequence numbers, so the receiver can detect loss, duplication and reordering;
- acknowledgments and a retransmission timer, for messages that must arrive;
- its own congestion control, so it does not overload the path;
- message framing, which UDP already gives you for free, since each datagram is one message.
QUIC is the best-known result. It runs over UDP and provides reliable streams, encryption and congestion control. Because each stream is recovered independently, a loss on one stream does not block the others. This removes the head-of-line blocking that affects multiple requests sharing one TCP connection. It also lives in user space, so it can be updated without changing the operating system kernel.
Writing your own reliability layer is hard to get right. Unless you have a clear reason, use TCP, or use an existing library such as QUIC, rather than inventing a protocol.
Practical gotchas
Message boundaries change your code
With UDP, one sendto is one datagram and one recvfrom returns it whole. With TCP, two sendall calls may arrive in one recv, and one sendall may need several recv calls. If you pick TCP for a message-oriented protocol, you must add framing: a length prefix or a delimiter. The helper below reads exactly one length-prefixed message.
import socket
import struct
def recv_exact(sock: socket.socket, n: int) -> bytes:
"""Read exactly n bytes, or raise if the peer closes early."""
buf = bytearray()
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("peer closed mid-message")
buf.extend(chunk)
return bytes(buf)
def send_message(sock: socket.socket, payload: bytes) -> None:
sock.sendall(struct.pack("!I", len(payload)) + payload)
def recv_message(sock: socket.socket) -> bytes:
(length,) = struct.unpack("!I", recv_exact(sock, 4))
return recv_exact(sock, length)UDP datagram size
A UDP datagram larger than the path MTU (often about 1500 bytes on Ethernet) is fragmented by IP. If any fragment is lost, the whole datagram is lost. To avoid this, keep datagrams below roughly 1200 to 1400 bytes unless you know the path.
Silent loss
A UDP sender gets no error when a datagram is dropped. Always use a receive timeout, as in the UDP example from the sockets chapter, and decide what to do when nothing arrives: retry, give up, or move on.
Firewalls and NAT
Many networks treat UDP more strictly than TCP. NAT devices keep UDP mappings for a short time, so a long-idle UDP "session" may stop working unless you send keepalives. Some corporate networks block UDP other than DNS. A service that must work everywhere often needs a TCP fallback.
Connection overhead for short exchanges
For a single small request, TCP costs a handshake round trip plus teardown. If you make many short requests to the same server, reuse one connection rather than opening a new one each time. This recovers most of the cost without leaving TCP.
A worked decision
Consider a multiplayer game that sends each player's position 30 times per second.
- Must every update arrive? No. If the update for tick 100 is lost, the update for tick 101 replaces it.
- Is old data useful? No. A retransmitted position from 200 ms ago is stale.
- Are messages small? Yes, a few dozen bytes.
This points to UDP. But the same game also has a login step and a chat window. Login must be reliable and ordered, and chat messages must not vanish. Many games therefore use two channels: TCP for login, chat and purchases, and UDP for position updates. Using both protocols in one application is common and reasonable.
Exercise
A monitoring agent sends one 200-byte metrics sample every second to a collector. Occasional lost samples are acceptable, and the collector only cares about the latest value per host. Which protocol fits better, and what is one thing the agent's author should still do?
Show answer
UDP fits better. Each sample is small and independent, a lost sample is replaced by the next one a second later, and UDP avoids connection state and retransmission delay. The author should still handle silent loss sensibly, for example by including a sequence number or timestamp so the collector can detect gaps and ignore reordered old samples, and by keeping the datagram well under the path MTU. If samples were billing events that must never be lost, TCP would be the right choice.
Exercise
A team wants to send 5 MB reports from a server to clients and proposes UDP "because it is faster". Give two reasons this is likely a poor choice.
Show answer
First, the report is only useful if complete and in order, so the team would have to build sequence numbers, acknowledgments and retransmission, which duplicates TCP and is easy to get wrong. Second, a fast UDP sender with no congestion control can overload the network and cause loss, which lowers real throughput and harms other traffic. TCP's flow control and congestion control prevent both problems. The handshake cost is a single round trip, which is small compared with the transfer.
Exercise
Why does QUIC run over UDP instead of being a new transport protocol alongside TCP?
Show answer
A new IP protocol number would not pass through many NATs, firewalls and middleboxes, which only understand TCP and UDP. Using UDP lets QUIC work on existing networks. It also allows QUIC to be implemented in user space, so it can be updated without operating system changes, and it can provide independent streams that avoid TCP's head-of-line blocking.