SYS ARCHITECTLearning Platform
Settings
Theory

TCP vs UDP: Transport Layer Decision Matrix

📋 Overview

At the Transport Layer (Layer 4), the choice between TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) is the ultimate trade-off between reliability and speed. Understanding these protocols is critical for designing low-latency real-time systems versus data-integrity-critical transactional systems.


🏗️ Core Principles & Characteristics

  • TCP (Connection-Oriented):
    • Reliability: Uses sequence numbers, ACKs (Acknowledgements), and retransmissions.
    • Flow Control: Sliding windows prevent the sender from overwhelming the receiver.
    • Congestion Control: Algorithms (like BBR or Cubic) detect network congestion and slow down.
  • UDP (Connectionless):
    • "Fire and Forget": No handshake, no ACKs, no retransmissions.
    • Minimal Header: 8 bytes (UDP) vs. 20+ bytes (TCP), reducing overhead for tiny packets.
    • Broadcasting: Supports one-to-many communication natively.

⚖️ Trade-offs: Pros & Cons

TCP

  • Pros: Guaranteed delivery, in-order packets, handles network congestion gracefully.
  • Cons: High overhead (Handshake + ACKs), "Head-of-Line Blocking" (one lost packet stalls all subsequent packets).

UDP

  • Pros: Ultra-low latency, no handshake delay, full control over timing (good for real-time).
  • Cons: Packets can be lost, duplicated, or arrive out of order; no built-in congestion protection (can cause "Network Collapse").

🌍 Real-World Implementation

  • HTTP/1.1 & HTTP/2 (TCP): Reliability is required for loading web resources (HTML/JS) correctly.
  • Online Gaming (UDP): A lost packet (movement glitch) is better than a 2-second stall to wait for retransmission.
  • Live Video (UDP/RTP): Dropping a frame is acceptable to keep the stream "Live."
  • DNS (UDP): Requests are usually a single packet; if it fails, the client just retries.
  • HTTP/3 (QUIC on UDP): Uses UDP to avoid TCP's Head-of-Line blocking while adding its own reliability layer in user-space.

💡 Interview "Gotchas" & Tips

  • The "Three-Way Handshake": Be ready to explain SYN -> SYN-ACK -> ACK and the latency cost (1.5 RTTs) before data even moves.
  • Head-of-Line (HoL) Blocking: The single biggest reason for moving from TCP to QUIC/UDP for the modern web.
  • TLS Handshake: Remember that on top of TCP, TLS adds another 1-2 RTTs of delay.
  • MTU (Maximum Transmission Unit): If a UDP packet is too large, it gets fragmented by routers, often leading to it being dropped.

📐 Suggested Architecture Primitives

  • Socket.io / WebSockets: Built on TCP for persistent, reliable full-duplex communication.
  • WebRTC: Uses UDP (via DTLS/SRTP) for ultra-low latency peer-to-peer video/audio.
  • HAProxy / Nginx: L4 Load Balancers can be configured to handle both TCP and UDP traffic.
  • QUIC/HTTP3: The emerging standard for high-performance web traffic.
Canvas