Episode 1 — Fundamentals / 1.3 — Internet Protocols

1.3.e — Difference Between TCP and UDP

In one sentence: TCP guarantees that every byte arrives in order at the cost of latency; UDP delivers as fast as possible with no guarantees — and the right choice depends on whether your application values correctness or speed more.

Navigation: ← 1.3.d — How UDP Works · ← Back to 1.3 Overview


Table of Contents


1. The Fundamental Trade-off

Every transport protocol choice boils down to one question:

┌──────────────────────────────────────────────────────────────────┐
│                                                                  │
│   "Is it worse to receive data LATE or to LOSE data?"            │
│                                                                  │
│   If losing data is worse     →  use TCP  (web, email, files)    │
│   If late data is worse       →  use UDP  (games, VoIP, live)    │
│   If you need both            →  use QUIC (HTTP/3, modern apps)  │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘

The restaurant analogy

  TCP = Fine dining restaurant                UDP = Fast food drive-through
  ─────────────────────────                   ──────────────────────────
  • Reservation required (handshake)          • No reservation (just show up)
  • Waiter confirms your order (ACK)          • Shout your order at the window
  • Wrong dish? They remake it (retransmit)   • Wrong order? Too late, next!
  • Courses come in order (ordered)           • Grab whatever's ready first
  • Check at the end (close gracefully)       • Pay and go (no ceremony)
  • Slow but PERFECT                          • Fast but IMPERFECT

2. Side-by-Side Comparison Table

FeatureTCPUDP
Full nameTransmission Control ProtocolUser Datagram Protocol
RFCRFC 793 (1981)RFC 768 (1980)
ConnectionConnection-oriented (handshake required)Connectionless (fire and forget)
ReliabilityGuaranteed delivery (ACKs + retransmission)Best-effort (no guarantees)
OrderingIn-order delivery guaranteedNo ordering; packets may arrive in any order
Error detectionChecksum (mandatory)Checksum (optional in IPv4, mandatory in IPv6)
Flow controlYes (sliding window)No
Congestion controlYes (slow start, AIMD, BBR, etc.)No (app is responsible)
Header size20–60 bytes8 bytes
Data modelByte stream (no message boundaries)Datagrams (message boundaries preserved)
SpeedSlower (overhead of reliability)Faster (minimal overhead)
MultiplexingVia portsVia ports
Broadcast/multicastNot supportedSupported
StateStateful (tracks connection, sequence numbers, windows)Stateless (each datagram is independent)
Connection setup3-way handshake (1 RTT)None (0 RTT)
Connection teardown4-way closeNone

3. Header Comparison

TCP Header (20 bytes minimum)

┌────────────────────┬────────────────────┐
│  Source Port (16)   │  Dest Port (16)    │
├────────────────────┴────────────────────┤
│         Sequence Number (32)            │
├─────────────────────────────────────────┤
│      Acknowledgment Number (32)         │
├──────┬─────┬────────┬───────────────────┤
│Offset│Flags│Reserved│  Window Size (16)  │
├──────┴─────┴────────┼───────────────────┤
│   Checksum (16)      │ Urgent Ptr (16)   │
├──────────────────────┴───────────────────┤
│           Options (variable)             │
├──────────────────────────────────────────┤
│              DATA                        │
└──────────────────────────────────────────┘
  Minimum: 20 bytes (without options)
  With options: up to 60 bytes

UDP Header (8 bytes, always)

┌────────────────────┬────────────────────┐
│  Source Port (16)   │  Dest Port (16)    │
├────────────────────┼────────────────────┤
│    Length (16)       │  Checksum (16)     │
├────────────────────┴────────────────────┤
│              DATA                        │
└──────────────────────────────────────────┘
  Always: 8 bytes. That's it.

What TCP's extra fields give you

TCP-only fieldWhat it enables
Sequence NumberTrack every byte; detect order and gaps
Acknowledgment NumberConfirm receipt; trigger retransmission on loss
Flags (SYN, ACK, FIN, RST)Manage connection lifecycle
Window SizeFlow control (receiver says how much it can handle)
OptionsMSS negotiation, window scaling, SACK, timestamps

UDP has none of these — and that's why it's 2.5x smaller and much simpler.


4. Connection Model

TCP: Stateful connection

  1. HANDSHAKE   ──────────►  Connection ESTABLISHED
  2. DATA FLOW   ◄──────────►  Full-duplex, tracked
  3. CLOSE       ──────────►  Connection TERMINATED

  Both sides maintain state:
  • Current sequence numbers
  • Receive window size
  • Congestion window
  • Retransmission timers
  • Connection phase (ESTABLISHED, FIN_WAIT, etc.)

UDP: Stateless datagrams

  1. SEND ────────────►  Done.
  2. SEND ────────────►  Done.
  3. SEND ────────────►  Done.

  No state maintained between datagrams.
  Each one is independent.
  Sender doesn't know if receiver got any of them.

5. Data Delivery

What happens when a packet is lost

  TCP — Packet 3 of 5 is lost:
  ─────────────────────────────
  Sender:  [1] [2] [3] [4] [5]  →  network
  Network: [1] [2] [✗] [4] [5]  →  receiver
  Receiver: Got 1,2. Missing 3. Hold 4,5 in buffer.
  Receiver → Sender: "I need packet 3" (via duplicate ACKs or timeout)
  Sender: Retransmits packet 3
  Receiver: Now has 1,2,3,4,5 → delivers in order to application

  Result: Application gets [1][2][3][4][5] — PERFECT
  Cost: Delay while waiting for retransmission

  ─────────────────────────────────────────────────

  UDP — Packet 3 of 5 is lost:
  ─────────────────────────────
  Sender:  [1] [2] [3] [4] [5]  →  network
  Network: [1] [2] [✗] [4] [5]  →  receiver
  Receiver: Got 1,2,4,5. Delivers them as they arrive.

  Result: Application gets [1][2][4][5] — INCOMPLETE, possibly out of order
  Cost: None. No delay.

What happens when packets arrive out of order

  TCP:
  Sent: [1] [2] [3]
  Arrived: [3] [1] [2]
  Delivered to app: [1] [2] [3]  (TCP reorders using sequence numbers)

  UDP:
  Sent: [1] [2] [3]
  Arrived: [3] [1] [2]
  Delivered to app: [3] [1] [2]  (UDP delivers as received)

6. Performance

Latency comparison

  SCENARIO: Client sends 1 small message, gets 1 response
  Server is 50ms away (one-way)

  TCP:
  ┌────────────────────────────────────────────────────────────┐
  │  t=0     SYN ──────────────────────────────► server        │
  │  t=50    ◄────────────────────────────────── SYN-ACK       │
  │  t=100   ACK + DATA ──────────────────────► server         │
  │  t=150   ◄────────────────────────────────── RESPONSE      │
  │                                                            │
  │  Total: 150ms (3 one-way trips)                            │
  └────────────────────────────────────────────────────────────┘

  UDP:
  ┌────────────────────────────────────────────────────────────┐
  │  t=0     DATA ────────────────────────────► server         │
  │  t=50    ◄────────────────────────────────── RESPONSE      │
  │                                                            │
  │  Total: 50ms (1 one-way trip + 1 return)                   │
  └────────────────────────────────────────────────────────────┘

  UDP is 3x faster for this pattern!

Throughput comparison

For bulk data transfer (large files), TCP is typically better because:

  • Congestion control maximizes throughput without causing network collapse
  • Reliability ensures no re-downloading
  • Sliding window keeps the pipe full

For many small messages (game state, sensor data), UDP wins:

  • No per-message ACK overhead
  • No head-of-line blocking
  • No connection management overhead

Bandwidth overhead

  Sending 100 bytes of application data:

  TCP:
  Data: 100 bytes + TCP header: 20 bytes + IP header: 20 bytes = 140 bytes
  Plus: ACK packet (40 bytes) from receiver
  Total wire bytes: 180 bytes for 100 bytes of data (55% efficiency)

  UDP:
  Data: 100 bytes + UDP header: 8 bytes + IP header: 20 bytes = 128 bytes
  No ACK needed
  Total wire bytes: 128 bytes for 100 bytes of data (78% efficiency)

7. Use Case Decision Guide

Decision flowchart

              START: What does your application need?
                              │
              ┌───────────────┴───────────────┐
              │                               │
     Must ALL data arrive                Can you tolerate
     correctly and in order?             some data loss?
              │                               │
              ▼                               ▼
          ┌───┴───┐                      ┌────┴────┐
          │  YES  │                      │   YES   │
          └───┬───┘                      └────┬────┘
              │                               │
     ┌────────┴────────┐            ┌─────────┴─────────┐
     │                 │            │                     │
  Is latency        Is it bulk   Is low latency       Is it multicast
  critical?         transfer?    critical?             or broadcast?
     │                 │            │                     │
     ▼                 ▼            ▼                     ▼
  Consider          USE TCP      USE UDP              USE UDP
  QUIC/HTTP3                   (or QUIC if you
  (best of both)               need some reliability)

When to use TCP

Use caseWhy TCP
Web pages (HTTP/1.1, HTTP/2)Every byte of HTML/CSS/JS must arrive correctly
APIs (REST, GraphQL, gRPC)Request and response integrity is critical
Email (SMTP, IMAP)Messages must be complete
File transfer (FTP, SFTP, SCP)A corrupt file is useless
SSHEvery keystroke and output must be reliable
Database connectionsQueries and results must be accurate

When to use UDP

Use caseWhy UDP
DNS queriesSmall, fast; app handles retries
Online gaming (state updates)Old positions are useless; need latest data fast
VoIP / video callsLate audio = echo/delay; drop and move on
Live streamingSlight quality drop beats freezing
IoT sensorsThousands of readings; some loss is acceptable
DHCPInitial network setup; simple protocol needed

When to use QUIC (UDP + custom reliability)

Use caseWhy QUIC
HTTP/3 web trafficReliable like TCP but no head-of-line blocking
Mobile appsConnection migration (Wi-Fi → cellular seamlessly)
Multiplexed streamsIndependent streams on one connection

8. Real-World Protocol Choices

What popular services use

ServiceProtocolWhy
Google Chrome (web)TCP (HTTP/2) or UDP (HTTP/3/QUIC)Moving toward QUIC for speed
Netflix (streaming)TCP (HTTPS)Pre-buffered; reliability matters more than real-time
YouTube (streaming)TCP (HTTPS) + QUICMix of both; QUIC growing
Zoom (video calls)UDP (primary) + TCP (fallback)Real-time needs UDP; falls back to TCP if UDP blocked
Discord (voice)UDP for voice, TCP for text/APIVoice = real-time; text = must not lose messages
Fortnite (game)UDP for game state, TCP for login/chatPositions need speed; account data needs reliability
Slack (messaging)TCP (WebSocket over HTTPS)Messages must arrive reliably and in order
Cloudflare DNSUDP (primary), TCP (large), DoH (HTTPS/TCP)Speed for queries; reliability for big responses

The Netflix exception

You might expect Netflix to use UDP (it's video streaming!), but Netflix uses TCP/HTTPS. Why?

  • Netflix pre-buffers content — you're watching 30+ seconds behind the download
  • Reliability matters — you don't want glitches in a movie you're paying for
  • DRM (Digital Rights Management) requires HTTPS for content protection
  • Adaptive bitrate handles bandwidth fluctuations

Live streaming (Twitch, live sports) is more likely to use UDP-based protocols because there's no buffer — you're watching in real-time.


9. The Modern Landscape — QUIC and Beyond

The evolution

  1980s                    2000s                      2020s
    │                        │                          │
    │  TCP for everything    │  TCP for most            │  TCP + QUIC
    │  UDP for DNS/games     │  UDP for real-time       │  (QUIC = "best of both")
    │                        │  + gaming + VoIP         │
    │                        │                          │
    ▼                        ▼                          ▼

  Simple choice:             Growing split:             Spectrum:
  "Reliable → TCP"          "Fast → UDP"               TCP ←──── QUIC ────→ UDP
  "Fast → UDP"              "Everything else → TCP"     (reliable but    (fast + custom
                                                         some latency)   reliability)

Why QUIC matters for this comparison

QUIC blurs the line between TCP and UDP:

FeatureTCPUDPQUIC
Reliable deliveryYesNoYes (per stream)
Ordered deliveryYes (entire connection)NoYes (per stream, not cross-stream)
Connection setup1 RTT (+ 1 for TLS)0 RTT1 RTT (combined with TLS), 0-RTT for repeat
Head-of-line blockingYes (connection-wide)NoNo (stream-independent)
Congestion controlYesNoYes
Runs overTCP (kernel)UDP (kernel)UDP (userspace)

QUIC takes the best of TCP (reliability, congestion control) and the best of UDP (no HOL blocking, fast setup) and combines them into a modern protocol that runs on top of UDP.


10. Common Interview Questions

Q: "When would you choose UDP over TCP?"

Strong answer: When the application is latency-sensitive and can tolerate some data loss — real-time applications like online gaming, VoIP, live streaming. Also when the protocol needs multicast or when a simple request/response doesn't justify a full connection (DNS). Increasingly, when building custom reliable transport (QUIC) that avoids TCP's head-of-line blocking.

Q: "Is UDP faster than TCP?"

Strong answer: For individual messages, yes — no handshake overhead (0 RTT vs 1 RTT). For sustained bulk transfer, TCP can achieve higher throughput because its congestion control optimizes pipe utilization. "Faster" depends on whether you mean latency (UDP wins) or throughput (TCP often wins).

Q: "Can you make UDP reliable?"

Strong answer: Yes, at the application layer. Add sequence numbers, acknowledgments, and retransmission logic. QUIC is the prime example — it's fully reliable transport built on UDP. The advantage is you control the reliability model (per-stream vs per-connection, selective retransmit, etc.) without being constrained by TCP's kernel implementation.


11. Key Takeaways

  1. TCP = reliable, ordered, connection-oriented at the cost of latency. Use for web, email, files, APIs — anything where data integrity matters.
  2. UDP = fast, connectionless, best-effort with minimal overhead. Use for real-time applications where speed matters more than completeness.
  3. The choice is not always binary — QUIC (HTTP/3) builds reliability on top of UDP to get the best of both worlds.
  4. TCP has a 20+ byte header with sequence numbers, ACKs, flags, and window size. UDP has an 8-byte header with just ports, length, and checksum.
  5. TCP prevents data loss through retransmission; this causes head-of-line blocking. UDP avoids blocking but loses data silently.
  6. Many real-world applications use both: UDP for real-time data + TCP for reliable control channels (e.g., Discord: UDP voice + TCP text).
  7. For interviews: understand the trade-off (reliability vs speed), name real examples, and mention QUIC as the modern evolution.

12. Explain-It Challenge

Without looking back, explain in your own words:

  1. In one sentence each, describe when to use TCP, when to use UDP, and when to use QUIC.
  2. Draw a comparison table from memory with at least 6 differences between TCP and UDP.
  3. Why does Netflix use TCP for video while Zoom uses UDP for video? What's the fundamental difference?
  4. How does QUIC solve TCP's head-of-line blocking problem?
  5. Why do games like Fortnite use both TCP and UDP in the same application?

If you can answer all five confidently, you have mastered this section.


Navigation: ← 1.3.d — How UDP Works · ← Back to 1.3 Overview