ConceptDifficulty: Beginner2 min

TCP: A Reliable, Ordered Stream of Bytes

TCP turns lost, reordered packets into one stream that arrives complete and in order, at a cost in time.

TCP gives two programs a connection that behaves like a pipe: bytes written at one end come out at the other complete, in order and without duplicates, even though the packets underneath can be lost, delayed or reordered. It does this by numbering every byte, waiting for the receiver to confirm what it got, and sending again whatever goes missing.

Its header is larger than UDP's, at least 20 bytes, because it carries the information that promise needs.

The main fields of the TCP header
FieldHolds
Source and destination portThe two programs, as in UDP
Sequence numberThe position in the stream of the first byte in this segment
Acknowledgement numberThe next byte the sender of this segment expects to receive
FlagsSYN to open, ACK to acknowledge, FIN to close, RST to abort
WindowHow many more bytes the sender of this segment can accept
ChecksumA check that the header and data arrived unchanged

Four properties make up the promise.

A connection. Before any data moves, the two ends exchange three segments, the handshake, to agree on starting sequence numbers. Either end can then send.

Order. The receiver uses sequence numbers to put segments back in order before handing data to the program.

Retransmission. Data that is not acknowledged in time is sent again, so the program never sees a gap.

Flow control. The window field lets a slow receiver tell a fast sender to wait, so it is not flooded.

TCP delivers a stream, not messages. A program that writes 300 bytes and then 500 may find the receiver reads 800 at once, or 100 and then 700. Any protocol on top, HTTP included, must mark where each message ends itself, with a length or a delimiter.

The promise has a price, paid in time. The handshake costs one round trip before the first byte of data, more with TLS on top. And because data is delivered in order, one lost segment holds up everything behind it until the copy arrives, even data that reached the receiver safely. That delay, head-of-line blocking, is harmless for a file and painful for a live call.

So TCP is the default for anything where every byte matters, such as web pages, file transfers, database queries and email, and the next topic shows how it keeps its promise.

← → move through sections and cards