Sub topic 8
How TCP Delivers Data Reliably and in Order
This chapter assumes you know the layered network model, that IP delivers packets on a best-effort basis, and that you have seen the TCP three-way handshake. It explains the mechanism that turns an unreliable packet service into a reliable, ordered byte stream: sequence numbers, acknowledgments, timers, and retransmission.
The problem TCP has to solve
IP gives no promises. A packet can be dropped by a congested router, corrupted in transit, duplicated, or delivered out of order because two packets took different paths. TCP runs only at the two endpoints, so it must detect and repair all of these problems using only the segments it exchanges.
TCP does this with four ideas:
- Every byte of data has a number.
- The receiver reports which bytes it has received in order.
- The sender keeps a copy of unacknowledged data and a timer.
- If the timer expires or enough hints arrive, the sender sends the data again.
Sequence numbers count bytes
TCP numbers bytes, not segments. The 32-bit sequence number field in a segment header holds the number of the first data byte in that segment. If a segment has sequence number 1000 and carries 500 bytes, it covers bytes 1000 to 1499, and the next segment starts at 1500.
Each side picks its own initial sequence number (ISN) during the handshake. The SYN flag consumes one sequence number, so the first data byte is ISN + 1. The FIN flag also consumes one number. The ISN is chosen unpredictably rather than starting at zero. This prevents old, delayed segments from a previous connection on the same address pair from being mistaken for new data, and it makes it harder for an attacker to forge segments.
Sequence numbers are 32 bits and wrap around after 2^32 bytes. Comparisons use modular arithmetic, so "A is before B" means the difference is less than half the number space. On fast links, wraparound can happen within the lifetime of a delayed segment. The TCP timestamps option (PAWS, Protection Against Wrapped Sequences) adds a check to reject such old segments.
Acknowledgments are cumulative
The acknowledgment number field, valid when the ACK flag is set, holds the next sequence number the receiver expects. It means: "I have received every byte before this number, in order."
This is a cumulative acknowledgment. An ACK of 1500 confirms all bytes up to 1499, even if earlier ACKs were lost. One ACK can therefore cover many segments, and a lost ACK often causes no harm because a later ACK covers the same data.
The table below shows a short exchange where one segment is lost.
| Step | Sender transmits | Receiver action | ACK sent |
|---|---|---|---|
| 1 | seq 1000, 500 bytes | Receives in order | ack 1500 |
| 2 | seq 1500, 500 bytes | Lost in the network | none |
| 3 | seq 2000, 500 bytes | Out of order, buffers it | ack 1500 (duplicate) |
| 4 | seq 2500, 500 bytes | Out of order, buffers it | ack 1500 (duplicate) |
| 5 | seq 1500, 500 bytes (retransmit) | Fills the gap | ack 3000 |
In step 5 the receiver already holds bytes 2000 to 2999, so one ACK jumps from 1500 to 3000.
The receiver also keeps ACKs from piling up. Many stacks use delayed ACKs: they wait a short time (commonly up to 40 to 200 ms) or until two full segments arrive before acknowledging. Out-of-order arrivals are acknowledged immediately, because the sender needs that signal quickly.
Detecting loss: timeout and duplicate ACKs
The sender can learn that a segment was lost in two ways.
Retransmission timeout
The sender starts a timer for the oldest unacknowledged segment. If no ACK covers it before the timer fires, the sender retransmits it. This is the retransmission timeout (RTO).
The RTO must be longer than the round-trip time (RTT), or the sender would retransmit data that was only slow. But it must not be so long that recovery is sluggish. TCP therefore measures RTT samples and keeps a smoothed average and a variance estimate (RFC 6298):
- SRTT = (1 − 1/8) × SRTT + 1/8 × R
- RTTVAR = (1 − 1/4) × RTTVAR + 1/4 × |SRTT − R|
- RTO = SRTT + max(G, 4 × RTTVAR), with a lower bound of 1 second in the RFC (Linux uses a smaller minimum, 200 ms)
Here R is a new RTT sample and G is the clock granularity. Following Karn's algorithm, TCP does not take RTT samples from retransmitted segments, because it cannot tell whether an ACK answers the original or the retransmission. Each time the timer fires, the RTO doubles (exponential backoff), which stops a struggling sender from adding load to a congested path.
Fast retransmit
Waiting for a timer is slow. When the receiver gets out-of-order data, it repeats the same ACK. The sender treats three duplicate ACKs as strong evidence that one segment was lost while later ones arrived. It retransmits the missing segment immediately, without waiting for the RTO. This is fast retransmit.
The threshold of three tolerates mild reordering: one or two duplicate ACKs can come from packets that merely swapped places.
Selective acknowledgments
Cumulative ACKs have a weakness. In the example above, the sender knows only that bytes from 1500 are missing. It cannot tell that 2000 to 2999 arrived safely. It may resend those bytes too, or wait one RTT per lost segment when several are missing.
The SACK option (RFC 2018), negotiated in the SYN segments, fixes this. The receiver adds blocks to its duplicate ACKs listing the ranges it holds beyond the cumulative point, for example "ack 1500, SACK 2000–3000". The sender then retransmits only the gaps. SACK is enabled by default in current operating systems, and it makes recovery from multiple losses in one window much faster.
Putting it together
The following diagram shows a loss recovered by fast retransmit.
Ordering and duplicates
Reliability also covers segments that arrive twice or in the wrong order.
- Out of order: the receiver stores segments that arrive ahead of a gap but does not give them to the application until the gap is filled. The application sees bytes only in order.
- Duplicates: if a segment's sequence range is already acknowledged, the receiver discards it and re-sends an ACK. This is common after a spurious retransmission or a lost ACK.
- Corruption: every segment carries a checksum. A segment that fails it is silently dropped, which the sender sees as ordinary loss.
This design means the application never sees loss, reordering, or duplication. It sees a clean stream of bytes. The cost is latency: a single lost segment holds back all later data until it is recovered. This is called head-of-line blocking.
What reliable does and does not mean
Reliable delivery in TCP is limited, and a few edge cases catch people out.
- Delivered to the peer's kernel, not the application. An ACK means the remote operating system holds the bytes in its receive buffer. It does not mean the remote program has read or processed them. If you need confirmation of processing, add an application-level reply.
sendreturning does not mean delivery.sendallreturns once the data is copied into the local send buffer. If the connection later breaks, you may never learn whether the data arrived.- Failure is reported late. If the peer vanishes without a FIN or RST (power loss, cable cut), a sender with data pending retries with backoff and eventually gives up, often after many minutes (Linux
tcp_retries2, roughly 15 minutes by default). An idle connection may stay "open" indefinitely unless you enable keepalives or an application heartbeat. - Checksum is weak. The 16-bit checksum misses some errors. Applications that must detect corruption, such as file transfers, add their own hash or use TLS.
Observing it
You can watch retransmissions on a live system. On Linux, ss -ti shows per-connection details such as rto, rtt, retrans, and cwnd. The following script runs a transfer on loopback and reads the kernel's counters through TCP_INFO. It runs on Linux only, because the structure layout is Linux specific.
import socket
import struct
import threading
ready = threading.Event()
def server():
with socket.socket() as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9100))
srv.listen()
ready.set()
conn, _ = srv.accept()
with conn:
while conn.recv(65536):
pass
t = threading.Thread(target=server)
t.start()
ready.wait()
with socket.create_connection(("127.0.0.1", 9100)) as s:
s.sendall(b"x" * 1_000_000)
raw = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_INFO, 104)
# struct tcp_info: 8 single-byte fields, then 32-bit counters
fields = struct.unpack("8B24I", raw[:104])
rto_us = fields[8 + 2]
print("retransmission timeout (microseconds):", rto_us)
print("retransmits in flight:", fields[2])
t.join()On a healthy loopback link the retransmit count is normally 0 and the RTO sits near the minimum. On a lossy path, these numbers rise, and that is the first thing to check when a transfer is slow.
Summary of the mechanism
| Problem | TCP tool |
|---|---|
| Lost segment | Retransmission timer, fast retransmit, SACK |
| Out-of-order segment | Sequence numbers, receiver buffering |
| Duplicate segment | Sequence numbers, discard and re-ACK |
| Corrupted segment | Checksum, drop, then retransmit |
| Timer set too short or long | Adaptive RTO with Karn's algorithm and backoff |
| Old segments from earlier connections | Random ISN, timestamps (PAWS) |
Exercise
A sender transmits segments covering bytes 5000–5999, 6000–6999, 7000–7999 and 8000–8999. The segment with bytes 6000–6999 is lost and the others arrive. What ACK numbers does the receiver send for the segments that do arrive, assuming no SACK and no delayed ACKs, and what makes the sender retransmit early?
Show answer
The first segment arrives in order, so the receiver sends ack 6000. The segments for 7000 and 8000 arrive out of order, so the receiver sends ack 6000 again for each, giving two duplicate ACKs. Two duplicates are below the threshold of three, so with only four segments the sender would probably wait for the retransmission timeout, unless a further segment arrives and produces a third duplicate ACK, which triggers fast retransmit of 6000–6999. After the retransmission arrives, the receiver sends ack 9000, because it already holds bytes up to 8999.
Exercise
Why does TCP not use RTT samples from retransmitted segments when computing the RTO, and what does the sender do each time the timer expires?
Show answer
When a segment has been sent twice, an ACK for it may belong to the original or to the retransmission, so the sample could be much too large or too small (Karn's algorithm). Skipping those samples keeps the RTO estimate accurate. Each expiry doubles the RTO (exponential backoff), which reduces load on a congested path.