Sub topic 14
Choosing between TCP and UDP
This chapter assumes you know the layered network model, what an IP address and packet are, and the basics of the TCP handshake, sequence numbers, flow control and congestion control from earlier chapters. Here you turn that knowledge into a decision you can defend.
Start from what the application needs
IP is best-effort. It can drop, duplicate, delay or reorder packets. TCP and UDP differ in how much of that damage they hide from your program.
| Property | TCP | UDP |
|---|---|---|
| Connection setup | Three-way handshake | None |
| Delivery | Reliable, retransmitted | Best effort, no retransmission |
| Ordering | In order | Not guaranteed |
| Message boundaries | None (byte stream) | Preserved (one datagram per read) |
| Flow and congestion control | Built in | None |
| Header size | 20 bytes or more | 8 bytes |
Ask these questions in order:
- Must every byte arrive, in order? If yes, TCP is the default.
- Is a late answer worse than a missing one? If yes, consider UDP.
- Are messages tiny and independent, so a handshake would cost more than the exchange itself? Consider UDP.
- Do you need to send to many receivers at once? UDP supports multicast and broadcast. TCP does not.
Typical choices and the reasons
- Web pages, file transfer, email, SSH, databases: TCP. A missing byte corrupts the result, and these tasks tolerate the handshake and retransmission delay.
- DNS queries: UDP. A query and its answer each fit in one datagram, and the client can simply retry after a timeout.
- Live voice and video: UDP. A retransmitted audio packet arrives too late to play, so waiting for it only adds delay.
- Online games: UDP for position updates, where the newest state replaces the old one.
The cost of each choice
TCP gives you reliability, but it can add delay. When one segment is lost, the receiver holds back all later data until the retransmission arrives. This is called head-of-line blocking. Congestion control can also slow a sender that has done nothing wrong.
UDP gives you control, but you pay for it in code. If you need reliability on top of UDP, you must write sequence numbers, acknowledgments and timers yourself, and you must avoid flooding the network, since UDP has no congestion control. Protocols such as QUIC do exactly this on top of UDP, and they are complex.
Common errors
- Assuming one
sendequals onerecvon TCP. TCP has no message boundaries. Add your own framing, such as a length prefix. - Assuming UDP delivers. A UDP
sendtothat returns successfully says nothing about arrival. Always use a timeout on the receiver. - Using UDP only to avoid the handshake. For a long exchange, the one-time setup cost is small. For a request-response that happens once, it can matter.
- Sending large UDP datagrams. A datagram bigger than the path MTU is fragmented at the IP layer, and losing any fragment loses the whole datagram. Keep payloads under about 1,200 bytes for safety.
A small checklist
def choose_transport(must_be_complete: bool,
stale_data_useless: bool,
tiny_independent_messages: bool) -> str:
if must_be_complete and not stale_data_useless:
return "TCP"
if stale_data_useless or tiny_independent_messages:
return "UDP"
return "TCP"
print(choose_transport(True, False, False)) # file transfer -> TCP
print(choose_transport(False, True, False)) # live voice -> UDP
print(choose_transport(False, False, True)) # DNS lookup -> UDPThis function is a teaching aid, not a rule. Real decisions also weigh firewalls (some networks block UDP), library support, and whether an existing protocol such as HTTP/3 already solves your problem.
Exercise
A multiplayer game sends each player's position 30 times per second. One update is lost in transit. Why is UDP usually a better fit than TCP here, and what must the game still do?
Show answer
The next update, sent about 33 ms later, replaces the lost one, so retransmitting old positions is wasted effort. With TCP, the lost segment would block all later updates until it was retransmitted (head-of-line blocking), making the game stutter. The game must still handle loss and reordering itself, for example by tagging each update with a sequence number and ignoring any update older than the latest one it has seen.
Exercise
You are designing a service that sends 500-byte sensor readings once per minute, and every reading must be stored. Which protocol would you pick, and why?
Show answer
TCP is the safer choice. Every reading must be stored, so reliability matters, and one connection per minute costs little. UDP would also work only if you added acknowledgments and retransmission yourself, which duplicates what TCP already provides.