TCP vs UDP0%

TCP vs UDP

Beginner12 min readUpdated: Jul 11, 2026
Study Materials

TCP vs UDP: Deep Architectural Comparison

At the transport layer of the internet protocol suite, two primary protocols govern how bytes are moved between computers: Transmission Control Protocol (TCP) and User Datagram Protocol (UDP).

Choosing between TCP and UDP requires evaluating trade-offs between reliability and delivery guarantees versus latency and protocol overhead.


1. Protocol Architecture & Characteristics

Output
TCP (Connection-Oriented & Heavyweight)
Client ══════► [ 3-Way Handshake: SYN, SYN-ACK, ACK ] ══════► Server
Data ────────► [ ACK Received ] ──► [ In-Order Delivery ] ──► Verified Data
Overhead: 20-60 byte header, congestion control, windowing buffers.
 
UDP (Connectionless & Lightweight)
Sender ═════════════════════════════════════════════════════► Receiver
Data Packet ─► [ Fire-and-Forget (No ACK, No Handshake) ] ──► May Drop or Reorder
Overhead: Minimal 8-byte header, zero state, zero handshake delay.

Direct Technical Comparison

MetricTCP (SOCK_STREAM)UDP (SOCK_DGRAM)
Connection ModelConnection-oriented (Requires 3-way handshake)Connectionless (No handshake, no teardown)
Delivery GuaranteeGuaranteed: Lost packets are retransmittedUnreliable: Packets may drop silently
OrderingStrictly In-Order: Packets reassembled sequentiallyUnordered: Packets may arrive out of sequence
Data BoundariesContinuous byte stream (No message boundaries)Discrete Datagrams (Preserves packet boundaries)
Flow & CongestionImplements sliding window flow & congestion controlNo congestion or rate control
Header Overhead20 to 60 bytesExactly 8 bytes
Speed / LatencyHigher latency (handshakes, ACK round-trips)Lowest possible latency (immediate dispatch)

2. The Framing Problem: Stream vs Datagram

Critical Trap: TCP is a continuous byte stream without built-in message boundaries. If a client sends three separate messages "A", "B", and "C", the server may receive them merged into a single chunk "ABC" or split across arbitrary fragments like "AB" and "C". Application protocols over TCP must implement framing (such as newline delimiters \n or length prefixes).

UDP, by contrast, preserves message boundaries: one sendto() call corresponds directly to exactly one recvfrom() call on the receiving socket.


3. Implementing UDP in Python (sendto and recvfrom)

Because UDP is connectionless, a UDP server does not call listen() or accept(). It simply binds to a port and reads datagrams directly, identifying the sender via recvfrom():

The UDP Server

Visual Architecture & Process Flow

How data and code flow step-by-step

Flowchart
Step 1
def run_udp_server
host: str = "127.0.0.1", port: int = 9999
Step 2
None:

The UDP Client

Visual Architecture & Process Flow

How data and code flow step-by-step

Flowchart
Step 1
def run_udp_client
host: str = "127.0.0.1", port: int = 9999
Step 2
None:

4. Industry Decision Matrix

Output
Do you require 100% complete data accuracy?
┌───────────────────────┴───────────────────────┐
▼ ▼
YES NO
(Financial transactions, (Real-time gaming,
web browsing, files) voice/video calls)
│ │
▼ ▼
TCP UDP
HTTP/HTTPS, SSH, VoIP (Zoom, Discord),
PostgreSQL, SMTP DNS, NTP, WebRTC

5. Architectural Summary Table

RequirementPreferred ProtocolRationale
Web APIs & HTTPTCPDropped bytes mean corrupted JSON payloads or missing files
Live Audio / Video StreamingUDPA dropped audio packet for 10ms is unnoticeable; waiting for retransmission causes lag
Multiplayer Game Position SyncUDPStale coordinate data is useless; fresh positions arrive immediately
DNS LookupsUDPQuery and response fit in single datagrams; faster than 3-way handshake
File Transfer (FTP / SFTP)TCPEven a single flipped or missing bit corrupts the executable or archive

Multiple Choice Questions

1.

What type of socket is created using socket.socket(socket.AF_INET, socket.SOCK_DGRAM)? A. TCP Stream Socket B. UDP Datagram Socket C. Raw ICMP Socket D. Unix Domain Socket

Answer: B
Explanation:SOCK_DGRAM creates a datagram-oriented socket, which utilizes the User Datagram Protocol (UDP).

2.

Why does a UDP server NOT need to invoke .listen() or .accept() methods? A. UDP is connectionless; packets are addressed and routed individually without negotiating a persistent session handshake. B. UDP only works on client machines. C. .accept() is deprecated in Python 3. D. The operating system kernel accepts UDP connections automatically.

Answer: A
Explanation:UDP does not establish persistent client-server connections. The server simply binds to a port and listens for incoming discrete datagrams using recvfrom().

3.

What is the "framing problem" inherent in TCP that does not exist in UDP? A. TCP packets cannot exceed 64 bytes. B. TCP is a continuous byte stream without message delimiters, meaning distinct send() calls can arrive coalesced together or fragmented arbitrarily. C. TCP cannot transmit text files. D. TCP does not support Unicode.

Answer: B
Explanation:TCP provides an unstructured stream of bytes. Applications must implement their own message delimiters (like newlines or byte-length prefixes) to distinguish individual messages, whereas UDP preserves message boundaries.

4.

What method on a UDP socket is used to transmit data to a specific remote destination? A. sock.connect() B. sock.sendall() C. sock.sendto(data, address) D. sock.push()

Answer: C
Explanation:In UDP, sock.sendto(data, (host, port)) transmits a datagram directly to the specified destination tuple without requiring prior connection establishment.

5.

Which application is best suited for UDP rather than TCP? A. Secure Shell (SSH) remote terminal session. B. Real-time multiplayer game player position updates. C. Online banking ledger transfers. D. Downloading an operating system ISO image.

Answer: B
Explanation:Real-time game positions prioritize the lowest possible latency. If a position update packet is dropped, waiting for a retransmission is counterproductive because newer coordinates are already available.

Next Lesson

Building a Chat Server

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext