| |

Internet Backend 04 ๐ŸŒ TCP vs UDP Protocols

โฑ๏ธ Estimated read: 12 min | |

TCP and UDP are the two transport-layer protocols that carry almost all of the Internet’s traffic, and they make opposite bets about what the network should guarantee. TCP bets that the application wants a reliable, ordered byte stream and will pay the cost of the handshake, the acknowledgments, and the retransmissions to get it. UDP bets that the application wants the datagrams as fast as possible and will handle the loss, the duplication, and the ordering itself if it cares about them at all. The bet is the design decision, and the decision is the reason the two protocols coexist rather than one replacing the other.

The IETF specifications make the trade-off explicit. RFC 9293 defines TCP as providing a “reliable, in-order, byte-stream service to applications,” with the reliability implemented through the sequence numbers, the checksums, and the retransmissions . RFC 768 defines UDP as providing a “datagram mode of packet-switched computer communication” with “a minimum of protocol mechanism,” and it states plainly that “delivery and duplicate protection are not guaranteed” and that applications requiring ordered reliable delivery “should use the Transmission Control Protocol (TCP)” . The two specifications are not competitors. They are the two answers to the same question, and the question is what the application needs.

Key point: TCP is connection-oriented, reliable, and ordered, with flow control and congestion control. UDP is connectionless, unreliable, and unordered, with an 8-byte header and no flow or congestion control. The choice is the application’s tolerance for loss and its need for ordering. HTTP, email, and SSH use TCP. DNS, DHCP, VoIP, and streaming use UDP. QUIC is the modern case that runs over UDP and implements the reliability in the application.


Why the two protocols exist

The reliability problem. The network layerโ€”IPโ€”is connectionless and best-effort. It forwards the packets, and it does not guarantee the delivery, the ordering, or the duplication protection. The transport layer is where the reliability can be added, and TCP is the protocol that adds it. The sequence numbers detect the loss and the reordering, the acknowledgments confirm the receipt, and the retransmissions recover the lost segments . The application that needs the reliable stream uses TCP, and the application does not have to implement the sequence numbers and the retransmissions itself.

The latency problem. The reliability has a cost. The three-way handshake adds a round trip before any data is sent. The acknowledgments add the overhead, and the retransmissions add the delay when a packet is lost. For an application that prefers the low latency over the reliabilityโ€”a VoIP call, a live video stream, an online gameโ€”the TCP reliability is not a benefit but a liability. A retransmitted voice packet arrives too late to be useful, and the retransmission delays the packets that come after it. UDP avoids the cost by not providing the guarantees, and the application decides what to do with the loss .

The overhead problem. The TCP header is 20 bytes minimum, and the UDP header is 8 bytes. For a small messageโ€”a DNS query, an NTP request, a DHCP discoveryโ€”the TCP header and the handshake are a large fraction of the total traffic. The UDP header is small, and the transaction is a single request and a single response. The overhead is the reason the DNS uses UDP for the common queries and TCP only for the zone transfers and the large responses .

The trade-off. The TCP reliability is the right choice when the application cannot tolerate the loss. A file transfer, an HTTP response, an email message, or an SSH session that loses a byte is a corrupted result. The UDP low latency is the right choice when the application can tolerate the loss and the latency matters more. A video frame that is lost is a brief glitch, and a VoIP packet that is lost is a brief silence. The trade-off is the reliability against the latency, and the protocol is the declaration of which one the application prefers.


a. The TCP mechanism and the reliable stream

TCP is connection-oriented. The connection is established with the three-way handshake: the client sends a SYN, the server responds with a SYN-ACK, and the client sends an ACK. The handshake synchronizes the sequence numbers and confirms that both sides are ready. The connection is terminated with the four-way handshake: a FIN from one side, an ACK from the other, a FIN from the other, and an ACK from the first .

The reliability is implemented with the sequence numbers and the acknowledgments. Each byte in the stream has a sequence number, and the receiver acknowledges the next byte it expects. If the sender does not receive the acknowledgment within the timeout, it retransmits the segment. The sequence numbers also detect the reordering and the duplication, and the receiver reassembles the stream in the correct order .

The flow control is the sliding window. The receiver advertises a window size, which is the number of bytes it is willing to accept. The sender can send up to the window size without waiting for an acknowledgment. The window slides forward as the acknowledgments arrive. The flow control prevents the sender from overwhelming the receiver, and it is the mechanism that adapts the sending rate to the receiver’s capacity .

The congestion control is the mechanism that adapts the sending rate to the network’s capacity. The classic algorithmsโ€”slow start, congestion avoidance, fast retransmit, and fast recoveryโ€”interpret the packet loss as a sign of congestion and reduce the sending rate. The congestion control is the reason TCP is fair to the other flows on the network, and it is the reason the Internet does not collapse under the load .

The TCP header:
[Source Port (16 bits)][Destination Port (16 bits)]
[Sequence Number (32 bits)][Acknowledgment Number (32 bits)]
[Data Offset (4 bits)][Reserved (3 bits)][Flags (9 bits)][Window Size (16 bits)]
[Checksum (16 bits)][Urgent Pointer (16 bits)]
[Options (variable)][Padding (variable)]
[Payload]

The TCP header is 20 bytes minimum. The source and destination ports identify the applications. The sequence and acknowledgment numbers implement the reliability. The flags (SYN, ACK, FIN, RST, PSH, URG) control the connection. The window size implements the flow control. The checksum detects the errors in the header and the payload.


b. The UDP mechanism and the datagram service

UDP is connectionless. It does not establish a connection, does not acknowledge the receipt, and does not retransmit the lost datagrams. It takes the application’s message, adds the 8-byte header, and passes the datagram to IP. The delivery, the ordering, and the duplication protection are the application’s responsibility .

The UDP header is 8 bytes: the source port, the destination port, the length, and the checksum. The checksum is optional in IPv4 and mandatory in IPv6. The checksum covers the header, the payload, and a pseudo-header that includes the source and destination IP addresses, which gives the protection against the misrouted datagrams .

The UDP is transaction-oriented. The DNS query is a single datagram from the client to the server, and the response is a single datagram from the server to the client. The NTP request is a single datagram, and the response is a single datagram. The DHCP discovery is a broadcast datagram, and the offer is a unicast datagram. The transaction model is the reason the UDP is the right choice for the simple query-response protocols .

The UDP header:
[Source Port (16 bits)][Destination Port (16 bits)]
[Length (16 bits)][Checksum (16 bits)]
[Payload]

The UDP header is 8 bytes. The source and destination ports identify the applications. The length is the length of the datagram, including the header and the payload. The checksum is the error detection mechanism, and it can be zero if the application does not need it.


Complete Example Session

// ============================================
// PART 1: THE TCP HANDSHAKE
// ============================================

// The client sends a SYN with the initial sequence number.
// The server responds with a SYN-ACK.
// The client sends an ACK.
// The connection is established.

// ============================================
// PART 2: THE TCP RELIABILITY
// ============================================

// The sequence numbers order the bytes.
// The acknowledgments confirm the receipt.
// The retransmissions recover the lost segments.
// The receiver reassembles the stream in order.

// ============================================
// PART 3: THE TCP FLOW CONTROL
// ============================================

// The receiver advertises a window size.
// The sender can send up to the window without an acknowledgment.
// The window slides forward as the acknowledgments arrive.

// ============================================
// PART 4: THE TCP CONGESTION CONTROL
// ============================================

// The slow start increases the window exponentially.
// The congestion avoidance increases it linearly.
// The packet loss reduces the window.
// The congestion control adapts to the network capacity.

// ============================================
// PART 5: THE UDP DATAGRAM
// ============================================

// The UDP header is 8 bytes.
// The source port, destination port, length, checksum.
// The delivery is not guaranteed.
// The ordering is not guaranteed.
// The application handles the loss and the ordering.

// ============================================
// PART 6: THE DNS USE CASE
// ============================================

// The DNS query is a single UDP datagram.
// The response is a single UDP datagram.
// The transaction is a request and a response.
// The TCP is used for the zone transfers and the large responses.

// ============================================
// PART 7: THE VOIP USE CASE
// ============================================

// The voice packets are small and frequent.
// A lost packet is a brief silence.
// The retransmission would arrive too late.
// The UDP is the correct choice.

// ============================================
// PART 8: THE VIDEO STREAMING USE CASE
// ============================================

// The live streaming: the UDP is the choice.
// The packet loss is a brief glitch.
// The retransmission would stall the stream.
// The VoD: the TCP is the choice because the integrity matters more than the latency.

// ============================================
// PART 9: THE QUIC CASE
// ============================================

// QUIC runs over UDP.
// It implements the streams, the reliability, the congestion control.
// It avoids the TCP head-of-line blocking.
// It is the transport for HTTP/3.

// ============================================
// PART 10: THE CHECKLIST
// ============================================

// [ ] The application needs the reliable, ordered delivery โ†’ TCP.
// [ ] The application needs the low latency and can tolerate the loss โ†’ UDP.
// [ ] The application is a simple query-response โ†’ UDP.
// [ ] The application is a file transfer or a web request โ†’ TCP.
// [ ] The application implements its own reliability โ†’ UDP (QUIC).

The ten parts covered the TCP handshake, the TCP reliability, the flow control, the congestion control, the UDP datagram, the DNS use case, the VoIP use case, the video streaming use case, the QUIC case, and the checklist. The through-line is that the protocol is the declaration of the application’s tolerance for loss.


Quick Reference

The TCP vs UDP comparison

AspectTCPUDP
ConnectionConnection-oriented (handshake)Connectionless
ReliabilityReliable (acknowledgments, retransmissions)Unreliable
OrderingOrderedUnordered
Header size20 bytes minimum8 bytes
Flow controlSliding windowNone
Congestion controlYesNo
SpeedSlowerFaster
Use casesHTTP, email, SSH, file transferDNS, DHCP, VoIP, streaming, gaming

The protocol use cases

ProtocolTransportReason
HTTP/1.1, HTTP/2TCPThe web needs the reliable, ordered delivery
HTTP/3QUIC (UDP)The streams and the low latency
DNSUDP (TCP for large)The single request-response transaction
DHCPUDPThe broadcast and the simple transaction
SMTPTCPThe email needs the reliable delivery
VoIPUDPThe latency matters more than the loss
Live streamingUDPThe loss is a glitch; the retransmission would stall
Video on DemandTCPThe integrity matters more than the latency
Online gamingUDPThe latency matters more than the loss
SSHTCPThe reliable, ordered terminal session

The header fields

TCP fieldPurpose
Source/Destination PortThe application identification
Sequence NumberThe byte position
Acknowledgment NumberThe next expected byte
FlagsThe connection control (SYN, ACK, FIN, RST)
Window SizeThe flow control
ChecksumThe error detection
UDP fieldPurpose
Source/Destination PortThe application identification
LengthThe datagram length
ChecksumThe error detection (optional in IPv4)

Best Practices

โœ… Do This:

// Use TCP for the reliable, ordered communication.
// Use UDP for the low-latency communication.
// Use UDP for the simple query-response protocols.
// Implement the reliability in the application if UDP is used and the reliability is needed (QUIC).

โŒ Don’t Do This:

// Use TCP for the real-time voice or video.
// The retransmission and the congestion control add the latency.

// Use UDP for the file transfer or the web request.
// The loss would corrupt the result.

Common Pitfalls

PitfallWhy It HappensFix
The TCP is slow for the small messagesThe handshake and the congestion controlUse UDP or a persistent connection
The UDP packet is lostThe UDP does not retransmitImplement the reliability in the application
The DNS is slowThe UDP query is retriedUse the TCP for the large responses
The VoIP is choppyThe network is congestedUse the UDP with the codec’s loss concealment

Summary

ItemValue
TCPConnection-oriented, reliable, ordered, flow control, congestion control
UDPConnectionless, unreliable, unordered, 8-byte header
TCP header20 bytes minimum
UDP header8 bytes
TCP use casesHTTP, email, SSH, file transfer
UDP use casesDNS, DHCP, VoIP, streaming, gaming
QUICThe reliability over UDP, the transport for HTTP/3

Key takeaways:

  • TCP provides a reliable, in-order, byte-stream service. The reliability is implemented through the sequence numbers, the checksums, and the retransmissions. The flow control is the sliding window, and the congestion control adapts the sending rate to the network’s capacity .
  • UDP provides a connectionless, unreliable datagram service. The header is 8 bytes, and the delivery, the ordering, and the duplication protection are not guaranteed. The application decides what to do with the loss .
  • The choice is the application’s tolerance for loss and its need for ordering. The web, the email, and the SSH need the reliability and use TCP. The DNS, the DHCP, the VoIP, and the streaming need the low latency and use UDP .
  • The QUIC protocol runs over UDP and implements the reliability in the application. It provides the streams, the congestion control, and the encryption without the TCP head-of-line blocking, and it is the transport for HTTP/3 .
  • The TCP congestion control is the reason the Internet does not collapse. The slow start and the congestion avoidance interpret the packet loss as a sign of congestion and reduce the sending rate, which keeps the network fair and stable .

Remember: TCP and UDP are the two answers to the same question: what should the transport layer guarantee? TCP guarantees the reliable, ordered delivery and pays for it with the latency and the overhead. UDP guarantees nothing and leaves the decisions to the application. The choice is the application’s tolerance for loss and its need for ordering. The web uses TCP, the DNS uses UDP, the streaming uses UDP, and the QUIC uses UDP with the reliability implemented on top.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!