TCP vs UDP
Master the protocols of data transport. Learn the trade-offs between reliable, ordered delivery and fast, best-effort streaming.
π TCP vs UDP
TCP and UDP are transport layer protocols used to send data over the internet. Choosing between them depends on whether you value reliability or speed.
π‘ The Logic (ELI5)
TCP (The Certified Letter)
Think of a Certified Registered Letter:
- You send the letter.
- The mailman asks the receiver to sign for it (Acknowledgement).
- If no signature is returned, you send the letter again (Retransmission).
- You ensure the letters arrive in the exact order you sent them.
- It's safe, but it takes time to wait for those signatures.
UDP (The Public Announcement)
Think of a Radio Broadcast or a Megaphone:
- You yell the information out.
- You don't know who heard you or if they missed a word.
- You don't repeat yourself.
- It's incredibly fast and real-time, but some words might be lost in the wind.
π The Deep Dive
| Feature | TCP (Transmission Control Protocol) | UDP (User Datagram Protocol) |
|---|---|---|
| Connection | Connection-oriented (Handshake) | Connectionless |
| Reliability | Guaranteed delivery | Best-effort (No guarantee) |
| Order | Guaranteed order | No guaranteed order |
| Speed | Slower (Overhead of checks) | Faster (Minimal overhead) |
| Usage | Web Browsing, Email, File Transfer | Video Streaming, Gaming, VOIP |
The TCP Three-Way Handshake
Before sending any data, TCP does a 3-step dance:
SYN(Synchronize)SYN-ACK(Synchronize-Acknowledge)ACK(Acknowledge) This ensures both sides are ready.
π― Interview Pulse
Use Case: Multiplayer Gaming
Why does a game like Call of Duty use UDP? Answer: If you lose one packet containing a player's movement from 0.1 seconds ago, you don't care! You only care about where they are now. Waiting for a TCP retransmission would cause "Lag."
Use Case: HTTP/3 (QUIC)
Modern HTTP/3 actually uses UDP instead of TCP! Why? To avoid "Head-of-Line Blocking" (where one lost packet stalls the entire stream). It builds the reliability layers on top of UDP for maximum speed.
Key Word: Packet Loss
In UDP, data is sent as "Datagrams." If a datagram is lost, it's gone. In TCP, the protocol automatically handles the re-request. β‘