TCP vs UDP Trade-offs and How TCP Infers Packet Loss
System DesignModel answerLast updated
Compare TCP and UDP across reliability, ordering, congestion control, setup and overhead, then explain how TCP detects loss through timers, duplicate ACKs and SACK.
You are designing a networked service and need to justify your choice of transport protocol.
Part 1. Compare TCP and UDP along these axes:
- reliability
- ordering
- congestion and flow control
- connection setup and teardown
- per-packet overhead
Say when you would pick each one.
Part 2. The network never tells a TCP sender that a packet was dropped. Explain how the sender infers loss and decides to retransmit. Cover at least:
- retransmission timeouts
- duplicate ACKs and fast retransmit
- selective acknowledgments (SACK)
Also discuss how the sender's behavior differs between these signals, and which edge cases make loss detection hard.
A strong answer is structured, gives concrete numbers or formulas where they help, and names trade-offs. You may include a short code sketch of the sender-side logic.
Hints
Hint 1
Think of TCP as a reliable ordered byte stream built on an unreliable packet network, and UDP as little more than IP plus ports and a checksum. Ask which responsibilities each pushes onto the application.
Hint 2
The sender has two kinds of evidence for loss: silence (a timer expires with no ACK) and ACK patterns (repeated cumulative ACKs, or SACK blocks showing gaps). Ask which is faster and which is more reliable.
Hint 3
Consider cases where the faster signals fail: very small windows, loss of the last packets in a flight, reordering that looks like loss, and retransmitted segments whose ACKs are ambiguous for RTT measurement.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: TCP vs UDP
TCP gives the application a reliable, ordered byte stream. It uses sequence numbers, ACKs, retransmission, flow control and congestion control to do so. UDP is a thin datagram service: IP plus source/destination ports and an optional checksum (mandatory in IPv6). Anything beyond that is the application's job.
| Axis | TCP | UDP |
|---|---|---|
| Reliability | Lost data is retransmitted until acknowledged | Best effort; a lost datagram is gone |
| Ordering | Delivered in order, so one hole stalls later data (head-of-line blocking) | None; datagrams can be reordered or duplicated |
| Data model | Byte stream with no message boundaries | Each send is one self-contained datagram |
| Flow control | Receiver advertises a window | None |
| Congestion control | Built in (slow start, AIMD, CUBIC, BBR) | None; the app must pace itself |
| Setup | 3-way handshake, so 1 RTT before data (TLS adds more) | None; the first packet can carry data |
| State | Per-connection state, FIN exchange, TIME_WAIT | Stateless |
| Header | 20 bytes minimum, up to 60 with options | 8 bytes |
Choosing:
- TCP fits when correctness matters more than latency: web APIs, databases, file transfer, SSH.
- UDP fits when late data is worthless (voice, video, games), when messages are tiny and independent (DNS), or when you want custom reliability. QUIC is the main example: it runs over UDP and gives per-stream ordering, which avoids TCP's connection-wide head-of-line blocking.
- A common mistake is saying "UDP is faster." UDP has less overhead and no built-in waiting, but it gives up congestion control. Unpaced UDP can harm the network and itself.
Part 2: How TCP infers loss
ACKs are cumulative: the receiver always acknowledges the next byte it expects. That one fact drives most of the machinery.
1. Retransmission timeout (RTO), the last resort
The sender times each segment and keeps a smoothed RTT (RFC 6298):
- First sample:
SRTT = R,RTTVAR = R/2 - Later:
RTTVAR = 3/4·RTTVAR + 1/4·|SRTT − R|, thenSRTT = 7/8·SRTT + 1/8·R RTO = SRTT + max(G, 4·RTTVAR), where G is the clock granularity
The initial RTO is 1 s. The RFC recommends a 1 s minimum; Linux uses 200 ms.
Karn's rule: never sample RTT from a retransmitted segment, because the ACK could belong to either copy. The timestamps option removes the ambiguity.
On timeout the sender:
- Retransmits the oldest unacknowledged segment.
- Doubles the RTO (exponential backoff).
- Sets
ssthresh = max(FlightSize/2, 2·MSS)andcwnd = 1 MSS, then restarts slow start.
This is a severe reaction because total silence suggests heavy congestion or a broken path.
2. Duplicate ACKs and fast retransmit
If segment N is lost but N+1, N+2, … arrive, the receiver keeps re-acknowledging N. After 3 duplicate ACKs the sender retransmits N at once without waiting for the RTO. Three is a compromise: one or two dup ACKs are often just mild reordering.
Fast recovery (Reno/NewReno) treats this as a milder signal than a timeout, because dup ACKs show packets are still getting through:
ssthresh = cwnd/2,cwnd = ssthresh + 3·MSS- Inflate
cwndby 1 MSS per extra dup ACK to keep data flowing - Deflate to
ssthreshwhen new data is acknowledged
NewReno uses "partial ACKs" to continue recovery when several segments are lost in one window, but it repairs only about one hole per RTT.
3. Selective acknowledgment (SACK, RFC 2018)
SACK is negotiated in the SYN. Each ACK carries up to 3 to 4 blocks describing out-of-order ranges the receiver holds, for example "I have 3000–5000 and 6000–8000." The sender builds a scoreboard and retransmits exactly the holes, possibly several per RTT, rather than guessing. DSACK extends this by reporting duplicate arrivals, so the sender can recognize a spurious retransmission and widen its reordering tolerance.
4. Modern refinements
- RACK (RFC 8985, the Linux default) is time-based: a segment is deemed lost if a segment sent later has been delivered and a small reordering window has passed. This handles reordering and lost retransmissions better than counting dup ACKs.
- Tail Loss Probe sends a probe after about 2·SRTT when the tail of a flight goes quiet. Without it, tail losses generate no dup ACKs and must wait for a full RTO.
Sketch
DUP_THRESH = 3
class Sender:
def __init__(self):
self.snd_una = 0 # oldest unacked byte
self.dup = 0
self.srtt = None
self.rttvar = 0.0
self.rto = 1.0
self.sacked = [] # merged (start, end) ranges
def rtt_sample(self, r): # call only for never-retransmitted data
if self.srtt is None:
self.srtt, self.rttvar = r, r / 2
else:
self.rttvar = 0.75 * self.rttvar + 0.25 * abs(self.srtt - r)
self.srtt = 0.875 * self.srtt + 0.125 * r
self.rto = max(0.2, self.srtt + 4 * self.rttvar)
def holes(self, snd_nxt):
"""Gaps between snd_una and the highest SACKed byte."""
out, cur = [], self.snd_una
for s, e in sorted(self.sacked):
if s > cur:
out.append((cur, s))
cur = max(cur, e)
return out
def on_ack(self, ack, sack_blocks=()):
self.sacked = merge(self.sacked + list(sack_blocks))
if ack > self.snd_una:
self.snd_una, self.dup = ack, 0
elif ack == self.snd_una:
self.dup += 1
if self.dup == DUP_THRESH:
return "fast_retransmit"
return None
(merge combines overlapping ranges.) Each ACK costs O(1) for the timer and dup counter. The scoreboard costs O(log n) per update with a balanced tree, and O(n) space for n outstanding segments.
Edge cases to mention
- Small windows: with fewer than 4 segments in flight, 3 dup ACKs never occur. Limited Transmit (RFC 3042) and TLP help.
- Reordering: it can trigger spurious fast retransmits. DSACK and RACK's adaptive window mitigate this.
- Lost ACKs: these are usually harmless, since a later cumulative ACK covers them.
- Delayed ACKs: they inflate RTT samples and slow dup-ACK generation.
- Retransmission ambiguity: handled by Karn's rule or timestamps.
- Lost retransmissions: dup-ACK logic cannot see them. RACK or the RTO is needed.
Why it works
Sequence numbers and cumulative ACKs tell the sender the lowest missing byte, and the RTO guarantees progress even if every ACK is lost. Dup ACKs, SACK and RACK are optimizations that find the loss about one RTT after it happens rather than after a full timeout, and they let the sender respond more gently.