TCP Reliability
IP can lose, duplicate and reorder packets. TCP still delivers every byte exactly once and in order. It does it with four tools: sequence numbers, acknowledgements, retransmission timers and a sliding window. In this lesson you'll simulate each one.
Cumulative acknowledgements and reordering
The receiver acknowledges the next byte it expects. If a segment arrives early (out of order), the receiver buffers it but keeps acknowledging the gap; once the missing piece arrives, it delivers everything in order and jumps the ACK forward.
class Receiver:
def __init__(self, start):
self.expected = start
self.buffer = {} # seq -> data, for segments that arrived early
self.delivered = b""
def receive(self, seq, data):
if seq < self.expected:
note = "duplicate, ignored"
elif seq > self.expected:
self.buffer[seq] = data
note = "out of order, buffered"
else:
self.delivered += data
self.expected += len(data)
while self.expected in self.buffer: # fill in from the buffer
chunk = self.buffer.pop(self.expected)
self.delivered += chunk
self.expected += len(chunk)
note = "in order, delivered"
print(f"got seq={seq:<3} {data!r:<8} {note:<24} -> ACK {self.expected}")
rx = Receiver(start=100)
rx.receive(100, b"Hello") # bytes 100-104
rx.receive(111, b"world") # bytes 111-115 arrive early
rx.receive(105, b", net ") # bytes 105-110 fill the gap
rx.receive(100, b"Hello") # a duplicate retransmission
print("application read:", rx.delivered)got seq=100 b'Hello' in order, delivered -> ACK 105
got seq=111 b'world' out of order, buffered -> ACK 105
got seq=105 b', net ' in order, delivered -> ACK 116
got seq=100 b'Hello' duplicate, ignored -> ACK 116
application read: b'Hello, net world'
The second segment was held back until the gap was filled. The application never sees data out of order or twice.
Retransmission on timeout
The sender keeps a copy of everything not yet acknowledged. If no ACK arrives within the retransmission timeout (RTO), it resends. Each further timeout doubles the RTO (exponential back-off), so a struggling network isn't hammered.
lost_transmissions = {("seg 2", 1), ("seg 2", 2)} # the first two tries of segment 2 are lost
def send_reliably(name, rto_ms=200):
attempt, clock = 1, 0
while True:
lost = (name, attempt) in lost_transmissions
status = "LOST" if lost else "ACKed"
print(f"t={clock:>4} ms send {name} (try {attempt}, RTO {rto_ms} ms) ... {status}")
if not lost:
return
clock += rto_ms
rto_ms *= 2
attempt += 1
for seg in ["seg 1", "seg 2", "seg 3"]:
send_reliably(seg)t= 0 ms send seg 1 (try 1, RTO 200 ms) ... ACKed
t= 0 ms send seg 2 (try 1, RTO 200 ms) ... LOST
t= 200 ms send seg 2 (try 2, RTO 400 ms) ... LOST
t= 600 ms send seg 2 (try 3, RTO 800 ms) ... ACKed
t= 0 ms send seg 3 (try 1, RTO 200 ms) ... ACKed
Estimating the RTO
A good RTO is a little longer than the round-trip time. Too short means needless resends; too long means slow recovery. TCP measures RTT samples and keeps a smoothed average (SRTT) and a variation estimate (RTTVAR), then sets RTO = SRTT + 4 × RTTVAR (RFC 6298, with a 1 s minimum in the RFC; Linux uses 200 ms).
alpha, beta = 1 / 8, 1 / 4
samples_ms = [100, 104, 98, 180, 102, 99, 101]
srtt = rttvar = None
for r in samples_ms:
if srtt is None:
srtt, rttvar = r, r / 2
else:
rttvar = (1 - beta) * rttvar + beta * abs(srtt - r)
srtt = (1 - alpha) * srtt + alpha * r
rto = srtt + 4 * rttvar
print(f"sample {r:>3} ms -> SRTT {srtt:6.1f} RTTVAR {rttvar:5.1f} RTO {rto:6.1f} ms")sample 100 ms -> SRTT 100.0 RTTVAR 50.0 RTO 300.0 ms
sample 104 ms -> SRTT 100.5 RTTVAR 38.5 RTO 254.5 ms
sample 98 ms -> SRTT 100.2 RTTVAR 29.5 RTO 218.2 ms
sample 180 ms -> SRTT 110.2 RTTVAR 42.1 RTO 278.5 ms
sample 102 ms -> SRTT 109.1 RTTVAR 33.6 RTO 243.5 ms
sample 99 ms -> SRTT 107.9 RTTVAR 27.7 RTO 218.8 ms
sample 101 ms -> SRTT 107.0 RTTVAR 22.5 RTO 197.1 ms
The one slow sample (180 ms) raised the RTO for a while, then it settled back down as the RTT became steady again.
Fast retransmit
Waiting for a timer is slow. When a segment is lost but later ones arrive, the receiver sends the same ACK again for each of them. Three duplicate ACKs tell the sender "I'm missing that one", and it resends immediately without waiting for the timer:
segments = [1000, 2000, 3000, 4000, 5000, 6000] # each carries 1000 bytes
lost_once = {3000}
expected, acks = 1000, []
received = set()
for seq in segments:
if seq in lost_once:
print(f"seq {seq} lost in the network")
continue
received.add(seq)
while expected in received:
expected += 1000
acks.append(expected)
print(f"seq {seq} arrives -> ACK {expected}")
dup = 0
for i, ack in enumerate(acks[1:], start=1):
if ack == acks[i - 1]:
dup += 1
if dup == 3:
print(f"3 duplicate ACKs for {ack}: fast retransmit of seq {ack}")seq 1000 arrives -> ACK 2000
seq 2000 arrives -> ACK 3000
seq 3000 lost in the network
seq 4000 arrives -> ACK 3000
seq 5000 arrives -> ACK 3000
seq 6000 arrives -> ACK 3000
3 duplicate ACKs for 3000: fast retransmit of seq 3000
Modern TCP also uses SACK (selective acknowledgement), an option that lists exactly which blocks arrived, so the sender resends only the holes.
The sliding window
Sending one segment and waiting for its ACK would be painfully slow on long links. Instead, TCP lets up to a window of unacknowledged bytes be in flight. As ACKs arrive, the window slides forward and new data can be sent. Throughput is limited to roughly window / RTT:
def throughput_mbps(window_bytes, rtt_ms):
return window_bytes * 8 / (rtt_ms / 1000) / 1e6
for window in [1460, 65_535, 1_048_576, 8_388_608]:
for rtt in [10, 100]:
print(f"window {window:>9,} B, RTT {rtt:>3} ms -> max {throughput_mbps(window, rtt):9.1f} Mbit/s")
link_mbps, rtt_ms = 1000, 100
bdp = link_mbps * 1e6 / 8 * rtt_ms / 1000
print(f"to fill 1 Gbit/s at 100 ms you need a window of {bdp:,.0f} bytes (the bandwidth-delay product)")window 1,460 B, RTT 10 ms -> max 1.2 Mbit/s
window 1,460 B, RTT 100 ms -> max 0.1 Mbit/s
window 65,535 B, RTT 10 ms -> max 52.4 Mbit/s
window 65,535 B, RTT 100 ms -> max 5.2 Mbit/s
window 1,048,576 B, RTT 10 ms -> max 838.9 Mbit/s
window 1,048,576 B, RTT 100 ms -> max 83.9 Mbit/s
window 8,388,608 B, RTT 10 ms -> max 6710.9 Mbit/s
window 8,388,608 B, RTT 100 ms -> max 671.1 Mbit/s
to fill 1 Gbit/s at 100 ms you need a window of 12,500,000 bytes (the bandwidth-delay product)
Without window scaling (max 65,535 bytes), a single connection across an ocean could never go faster than about 5 Mbit/s, no matter how fast the link.
Here's the window sliding over a byte stream, segment by segment:
total, mss, window = 8, 1, 3 # 8 segments, window of 3 segments
base, next_seq = 0, 0
step = 0
while base < total:
while next_seq < base + window and next_seq < total:
next_seq += 1 # send another segment
bar = "".join("A" if i < base else "S" if i < next_seq else "." for i in range(total))
print(f"step {step}: [{bar}] acked<{base} in flight {next_seq - base}")
base += 1 # one ACK arrives
step += 1
print("legend: A = acknowledged, S = sent, waiting for ACK, . = not sent yet")step 0: [SSS.....] acked<0 in flight 3
step 1: [ASSS....] acked<1 in flight 3
step 2: [AASSS...] acked<2 in flight 3
step 3: [AAASSS..] acked<3 in flight 3
step 4: [AAAASSS.] acked<4 in flight 3
step 5: [AAAAASSS] acked<5 in flight 3
step 6: [AAAAAASS] acked<6 in flight 2
step 7: [AAAAAAAS] acked<7 in flight 1
legend: A = acknowledged, S = sent, waiting for ACK, . = not sent yet
The receiver controls the window it advertises (flow control): a slow application that doesn't read its socket shrinks the advertised window, down to zero, and the sender must pause. The next lesson adds the sender's own limit, the congestion window.
Test yourself
What does a TCP receiver do with a segment that arrives ahead of a missing one?
- Drops it
- Delivers it to the application immediately
- Buffers it and keeps ACKing the missing byte
- Sends RST
What triggers a TCP fast retransmit?
- A RST
- Three duplicate ACKs
- A full receive buffer
- The handshake
With a 64 KB window and a 100 ms RTT, roughly what is the maximum throughput of one connection?
- About 0.6 Mbit/s
- About 5 Mbit/s
- About 64 Mbit/s
- About 1 Gbit/s