Skip to main content
🌐Networking

TCP vs UDP: Understanding Transport Layer Protocols

TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are the two primary transport layer protocols that power internet communication. Every...

📖 8 min read

TCP vs UDP: Understanding Transport Layer Protocols

TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are the two primary transport layer protocols that power internet communication. Every network application relies on one of these protocols to transmit data between hosts. Choosing the right protocol for your application is a fundamental architectural decision that impacts reliability, performance, and user experience. This comprehensive guide explores both protocols in depth, their differences, and when to use each one.

What is TCP?

TCP is a connection-oriented, reliable transport protocol defined in RFC 793. It provides guaranteed, ordered delivery of data between applications. TCP establishes a connection before data transfer begins and ensures every byte sent is received by the destination in the correct order.

Key Characteristics of TCP

Connection-Oriented: Before any data is exchanged, TCP establishes a connection through a three-way handshake. This creates a logical connection between the two endpoints.

Reliable Delivery: TCP guarantees that all data reaches the destination. It uses acknowledgments (ACKs), retransmissions, and sequence numbers to ensure no data is lost.

Ordered Delivery: TCP ensures data arrives in the same order it was sent. Sequence numbers track the position of each byte in the stream.

Flow Control: TCP uses a sliding window mechanism to prevent the sender from overwhelming the receiver. The receiver advertises its available buffer space (window size).

Congestion Control: TCP algorithms (slow start, congestion avoidance, fast retransmit, fast recovery) prevent the sender from overwhelming the network.

The TCP Three-Way Handshake

The three-way handshake establishes a TCP connection and synchronizes sequence numbers between client and server:

Step 1 - SYN: The client sends a SYN (synchronize) packet with an initial sequence number (ISN). This indicates the client wants to establish a connection.

Step 2 - SYN-ACK: The server responds with a SYN-ACK packet. It acknowledges the client's SYN and sends its own ISN.

Step 3 - ACK: The client sends an ACK acknowledging the server's SYN. The connection is now established and data transfer can begin.

Client                              Server
  |                                    |
  |--- SYN (seq=100) --------------->|
  |                                    |
  |<-- SYN-ACK (seq=300, ack=101) ---|
  |                                    |
  |--- ACK (seq=101, ack=301) ------>|
  |                                    |
  |    Connection Established          |
  |                                    |
  |--- Data (seq=101) -------------> |
  |<-- ACK (ack=201) ---------------- |
  |                                    |

TCP Connection Termination (Four-Way Handshake)

TCP connection termination uses a four-way handshake. Either side can initiate the close. The initiator sends a FIN, the other side ACKs it, then sends its own FIN, which is ACKed by the initiator. The TIME_WAIT state ensures all packets from the connection have been fully processed before the port is reused.

# Capture TCP handshake with tcpdump
sudo tcpdump -i eth0 -n "tcp[tcpflags] & (tcp-syn|tcp-fin) != 0" -c 10

# View active TCP connections
ss -tn state established

# Check TCP connection states
ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn

# Monitor TCP retransmissions (indicates network issues)
ss -ti | grep -E "retrans|rto"

What is UDP?

UDP is a connectionless, lightweight transport protocol defined in RFC 768. Unlike TCP, UDP does not establish a connection before sending data, does not guarantee delivery, and does not ensure ordering. UDP simply sends datagrams (packets) to the destination with minimal overhead.

Key Characteristics of UDP

Connectionless: No handshake is required. The sender simply sends datagrams to the destination address and port.

Unreliable: UDP does not guarantee delivery. Packets may be lost, duplicated, or arrive out of order. The application must handle these scenarios if needed.

No Ordering: Datagrams may arrive in any order. If ordering matters, the application must implement it.

No Congestion Control: UDP does not throttle its sending rate, which can be both an advantage (consistent sending rate) and a disadvantage (can overwhelm the network).

Low Overhead: The UDP header is only 8 bytes compared to TCP's minimum 20 bytes. There is no connection setup, teardown, or state maintenance.

TCP vs UDP: Detailed Comparison

Feature TCP UDP
Connection Connection-oriented (handshake required) Connectionless (no handshake)
Reliability Guaranteed delivery with ACKs Best-effort, no guarantees
Ordering Ordered delivery via sequence numbers No ordering guarantees
Header Size 20-60 bytes 8 bytes
Speed Slower due to overhead Faster, minimal overhead
Flow Control Yes (sliding window) No
Congestion Control Yes (slow start, AIMD) No
Data Unit Byte stream Datagrams (message boundaries preserved)
Broadcasting Not supported Supports broadcast and multicast

TCP Header Structure

TCP Header (20-60 bytes):
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Acknowledgment Number                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |       |C|E|U|A|P|R|S|F|                               |
| Offset| Rsrvd |W|C|R|C|S|S|Y|I|            Window             |
|       |       |R|E|G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Checksum            |         Urgent Pointer        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

UDP Header (8 bytes):
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|            Length              |           Checksum            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

When to Use TCP

TCP is the right choice when data integrity and complete delivery are essential:

Web Traffic (HTTP/HTTPS): Web pages, API calls, and file downloads require every byte to arrive correctly. A missing packet could corrupt a file or break a web page.

Email (SMTP, IMAP, POP3): Email messages must be delivered completely and accurately.

File Transfer (FTP, SFTP): Files must arrive intact without corruption.

Database Connections: Database queries and responses must be reliable and ordered.

SSH and Remote Administration: Command execution and terminal sessions require reliable, ordered delivery.

When to Use UDP

UDP is preferred when speed matters more than reliability, or when the application can handle packet loss:

Video Streaming and VoIP: Real-time media tolerates some packet loss (a few dropped frames are barely noticeable) but cannot tolerate the latency of TCP retransmissions.

Online Gaming: Game state updates need to arrive quickly. A delayed update is worse than a missing one because the next update will contain the latest state anyway.

DNS Queries: Simple request-response queries fit naturally into a single datagram. If the response is lost, the client simply retries.

IoT and Sensor Data: Lightweight devices sending periodic sensor readings benefit from UDP's low overhead. Missing a single reading is acceptable.

Live Broadcasting: Multicast and broadcast are only supported on UDP, making it essential for applications like IPTV and live event streaming.

Code Examples

# Python TCP Server
import socket

def tcp_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('0.0.0.0', 8080))
    server.listen(5)
    print("TCP Server listening on port 8080")

    while True:
        client, addr = server.accept()
        print(f"Connection from {addr}")
        data = client.recv(1024)
        print(f"Received: {data.decode()}")
        client.send(b"ACK: Message received")
        client.close()

# Python TCP Client
def tcp_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('localhost', 8080))
    client.send(b"Hello from TCP client")
    response = client.recv(1024)
    print(f"Server response: {response.decode()}")
    client.close()
# Python UDP Server
import socket

def udp_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server.bind(('0.0.0.0', 8081))
    print("UDP Server listening on port 8081")

    while True:
        data, addr = server.recvfrom(1024)
        print(f"Received from {addr}: {data.decode()}")
        server.sendto(b"ACK: Datagram received", addr)

# Python UDP Client
def udp_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client.sendto(b"Hello from UDP client", ('localhost', 8081))
    response, _ = client.recvfrom(1024)
    print(f"Server response: {response.decode()}")
    client.close()

TCP and UDP in Modern Protocols

Modern protocols often build on top of TCP and UDP to get the best of both worlds:

QUIC: Used by HTTP/3, QUIC is built on UDP but adds reliability, ordering, and congestion control at the application level, per-stream. This eliminates TCP's head-of-line blocking while maintaining reliability.

WebRTC: Uses both TCP (for signaling via WebSocket) and UDP (for media streams via SRTP). This combines reliable signaling with low-latency media delivery.

DTLS: Datagram Transport Layer Security provides TLS-like security for UDP applications. Used by WebRTC and VPN protocols.

Understanding transport protocols is essential when working with WebSockets and real-time communication, designing APIs, or configuring load balancers. Use our API and Network Tools to test connections and analyze network behavior.

Frequently Asked Questions

Can UDP be made reliable?

Yes, reliability can be built on top of UDP at the application layer. QUIC (used by HTTP/3) is the most prominent example. It adds sequence numbers, acknowledgments, retransmissions, and congestion control on top of UDP. Game networking libraries often implement their own reliability layer over UDP to get the benefits of UDP's speed while selectively ensuring delivery of important messages.

Why does DNS use UDP instead of TCP?

DNS primarily uses UDP because DNS queries are typically small (fitting in a single datagram), the request-response pattern is simple, and the overhead of TCP's three-way handshake would significantly slow down the billions of DNS queries that happen every second. However, DNS does fall back to TCP for responses larger than 512 bytes and for zone transfers between DNS servers.

What is TCP head-of-line blocking?

TCP guarantees ordered delivery, so if a packet is lost, all subsequent packets in the stream must wait for the lost packet to be retransmitted and received, even if they arrived successfully. This is called head-of-line blocking. In HTTP/2, which multiplexes multiple streams over a single TCP connection, a lost packet in one stream blocks all other streams. HTTP/3 solves this by using QUIC (over UDP), where each stream is independently ordered.

How do I choose between TCP and UDP for my application?

Ask these questions: Does your application need every byte delivered correctly? Use TCP. Can your application tolerate some data loss but needs low latency? Use UDP. Do you need both reliability and low latency? Consider building on UDP with selective reliability (like QUIC). For most web applications, APIs, and database connections, TCP is the standard choice. For real-time media, gaming, and IoT, UDP is often better.

Related Articles