Topic Overview
TCP vs UDP
Compare TCP and UDP protocols, their characteristics, and when to use each.
TCP vs UDP
Why This Matters
TCP is like sending a registered letter—you get confirmation it arrived, and it arrives in order. UDP is like shouting across a crowded room—you hope someone hears you, but you have no guarantee.
This distinction matters because it determines how your system handles failures. TCP guarantees delivery, but that guarantee has overhead (handshakes, acknowledgments, retries). UDP has no overhead, but packets can be lost, duplicated, or arrive out of order.
In interviews, when someone asks "How would you design a real-time multiplayer game?", they're testing whether you understand this trade-off. Do you use TCP for reliability, or UDP for speed? The answer is usually "both"—TCP for critical events, UDP for frequent updates.
What Engineers Usually Get Wrong
Most engineers think "TCP is reliable, so use TCP for everything." But TCP's reliability comes with overhead. Every TCP connection requires a three-way handshake (one round trip = 50-100ms). For short-lived connections, this overhead is significant. Also, TCP has flow control and congestion control, which can slow down data transfer when the network is congested.
Engineers also think "UDP is unreliable, so never use it." But UDP is perfect for applications where speed matters more than perfect delivery. Video streaming, online gaming, DNS queries—these all use UDP because a lost packet is less important than low latency.
How This Breaks Systems in the Real World
A microservice was making HTTP requests to another service. Each request opened a new TCP connection, sent data, then closed the connection. Under normal load, this worked fine. But during a traffic spike, the service tried to open 10,000 connections per second. Each connection required a three-way handshake (one round trip = 50ms). The handshake queue filled up. New connections timed out. The service became unresponsive.
The fix? Use HTTP keep-alive and connection pooling. Reuse TCP connections instead of creating new ones for each request. But the real lesson is: TCP connections have overhead. Opening and closing connections is expensive. Reuse them.
Another story: A real-time multiplayer game was using TCP for all network communication. The game felt laggy. Investigation showed that TCP's congestion control was slowing down game state updates. When the network was congested, TCP would reduce the sending rate, causing the game to feel unresponsive. The fix? Use UDP for game state updates (position, movement), and TCP only for critical events (player actions, chat). This gave the game low latency while maintaining reliability for important events.
TCP (Transmission Control Protocol)
Characteristics:
- Connection-oriented: Establishes connection before data transfer
- Reliable: Guarantees delivery, ordered delivery
- Flow control: Adjusts sending rate based on receiver capacity
- Congestion control: Adapts to network conditions
- Full-duplex: Bidirectional communication
Header size: 20-60 bytes
Use cases: Web browsing (HTTP), email (SMTP), file transfer (FTP), database connections
TCP Example: HTTP Request
1// TCP connection establishment2const socket = new TCPSocket();3await socket.connect('example.com', 80); // 3-way handshake45// Send HTTP request6await socket.write('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');78// Receive response (guaranteed delivery)9const response = await socket.read();
UDP (User Datagram Protocol)
Characteristics:
- Connectionless: No connection establishment
- Unreliable: No delivery guarantee, no ordering
- No flow control: Sends at maximum rate
- No congestion control: Doesn't adapt to network
- Lightweight: Minimal overhead
Header size: 8 bytes
Use cases: DNS queries, video streaming, online gaming, VoIP, DHCP
UDP Example: DNS Query
1// UDP - no connection2const socket = new UDPSocket();34// Send DNS query5const query = buildDNSQuery('example.com');6await socket.send(query, '8.8.8.8', 53);78// Receive response (may be lost, no guarantee)9try {10 const response = await socket.receive(1000); // 1 second timeout11} catch (timeout) {12 // Retry or use fallback13}
Comparison
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Reliable delivery | Best effort |
| Ordering | Ordered delivery | No ordering |
| Flow Control | Yes | No |
| Congestion Control | Yes | No |
| Overhead | High (20-60 bytes) | Low (8 bytes) |
| Speed | Slower | Faster |
| Use Case | Data integrity critical | Speed critical |
Failure Stories You'll Recognize
The Connection Storm: A service was creating new TCP connections for every request. During a traffic spike, it tried to create 10,000 connections per second. The three-way handshake queue filled up. New connections timed out. The service appeared down. The fix? Use connection pooling.
The Laggy Game: A multiplayer game used TCP for all communication. The game felt laggy because TCP's congestion control slowed down updates during network congestion. The fix? Use UDP for frequent updates, TCP for critical events.
The Lost DNS Queries: A service was making DNS queries over TCP instead of UDP. DNS queries are small and need to be fast. TCP's overhead made DNS lookups slow. The fix? Use UDP for DNS (the standard).
What Interviewers Are Really Testing
They want to hear you talk about the trade-off between reliability and latency. Junior engineers say "use TCP for everything." Senior engineers say "TCP for reliability when you need it, UDP for speed when you can tolerate loss."
When they ask "How would you design a real-time system?", they're testing:
- Do you understand that TCP's reliability has overhead?
- Do you know when UDP is appropriate?
- Can you design a hybrid approach that uses both?
Interview Questions
Beginner
Q: What are the main differences between TCP and UDP?
A:
TCP:
- Connection-oriented, reliable, ordered delivery
- Higher overhead, slower
- Use when data integrity is critical
UDP:
- Connectionless, unreliable, no ordering
- Lower overhead, faster
- Use when speed is critical and some loss is acceptable
Example: HTTP uses TCP (need reliable delivery). DNS uses UDP (speed matters, can retry).
Intermediate
Q: When would you choose UDP over TCP? Give examples.
A:
Choose UDP when:
- Real-time applications: Video streaming, gaming (latency critical)
- Simple request-response: DNS queries (can retry if lost)
- Broadcast/multicast: One-to-many communication
- High throughput: When you need maximum speed
Examples:
- DNS: UDP for queries (fast, can retry)
- Video streaming: UDP for live video (some packet loss acceptable)
- Online gaming: UDP for game state (old updates irrelevant)
- VoIP: UDP for voice (low latency > perfect delivery)
Trade-off: Accept some packet loss for lower latency.
Senior
Q: Design a real-time multiplayer game network protocol. How do you balance reliability and latency? When would you use TCP vs UDP?
A:
Design: Hybrid Approach
1class GameNetworkProtocol {2 // Use UDP for game state (position, movement)3 // Use TCP for critical events (player actions, chat)45 // UDP: Fast, unreliable game state6 async sendGameState(state: GameState): Promise<void> {7 const packet = this.serializeState(state);8 await this.udpSocket.send(packet, this.serverAddress);9 // No retry - next update will replace this10 }1112 // TCP: Reliable critical events13 async sendPlayerAction(action: PlayerAction): Promise<void> {
Strategy:
- UDP for frequent updates: Position, movement (30-60 updates/sec)
- TCP for critical events: Player actions, chat, game events
- Sequence numbers: Detect missing UDP packets
- Selective reliability: Retry only important packets via TCP
- Compression: Reduce UDP packet size
Why this works:
- Low latency for game state (UDP)
- Reliability for critical events (TCP)
- Best of both worlds
-
Three-Way Handshake (TCP) - Understanding TCP connection establishment helps explain why TCP has overhead compared to UDP
-
TCP Connection Termination - Learn how TCP connections are properly closed, complementing the connection-oriented nature of TCP
-
Connection Pooling - Optimize TCP connection reuse to minimize handshake overhead, addressing TCP's connection establishment cost
-
HTTP/1 vs HTTP/2 vs HTTP/3 - HTTP/3 uses QUIC (UDP-based) to overcome TCP limitations, demonstrating real-world UDP usage
-
OSI Model (7 Layers) - TCP and UDP operate at Layer 4 (Transport), understanding the OSI model provides context for protocol placement
-
TCP: Reliable, ordered, connection-oriented - use when data integrity critical
-
UDP: Fast, connectionless, unreliable - use when speed/latency critical
-
Trade-off: Reliability vs Speed
-
Choose based on use case: Web (TCP), Gaming (UDP), Video (UDP), File transfer (TCP)
-
Hybrid approach: Use both - TCP for critical, UDP for frequent updates
-
UDP reliability: Can add reliability on top of UDP if needed (QUIC does this)
How InterviewCrafted Will Teach This
We'll teach this through production failures, not protocol specifications. Instead of memorizing "TCP uses a three-way handshake," you'll learn through scenarios like "what happens when 10,000 clients try to connect simultaneously?"
You'll see how the choice between TCP and UDP affects latency, reliability, and system design. When an interviewer asks "how would you design a real-time system?", you'll think about the trade-off between reliability and speed—not just "use TCP."
Key Takeaways
TCP: Reliable, ordered, connection-oriented - use when data integrity critical
UDP: Fast, connectionless, unreliable - use when speed/latency critical
Trade-off: Reliability vs Speed
Choose based on use case: Web (TCP), Gaming (UDP), Video (UDP), File transfer (TCP)
Hybrid approach: Use both - TCP for critical, UDP for frequent updates
UDP reliability: Can add reliability on top of UDP if needed (QUIC does this)
Related Topics
Three-Way Handshake (TCP)
Understanding TCP connection establishment helps explain why TCP has overhead compared to UDP
TCP Connection Termination
Learn how TCP connections are properly closed, complementing the connection-oriented nature of TCP
Connection Pooling
Optimize TCP connection reuse to minimize handshake overhead, addressing TCP's connection establishment cost
HTTP/1 vs HTTP/2 vs HTTP/3
HTTP/3 uses QUIC (UDP-based) to overcome TCP limitations, demonstrating real-world UDP usage
OSI Model (7 Layers)
TCP and UDP operate at Layer 4 (Transport), understanding the OSI model provides context for protocol placement
What's next?