13. TCP: A Reliable Byte Stream

How sequence numbers, acknowledgements, timers and a sliding window turn IP's unreliable packets into an ordered stream of bytes, from the three-way handshake to TIME-WAIT

In the UDP article we sent postcards. Now suppose you need to send someone a whole novel, and the only thing the postal service will carry is postcards. Some will be lost, some will overtake others, and occasionally one will turn up twice.

You'd number them. Not page 1, page 2, page 3, but the position of the first character on each card: card 0 starts at character 0, the next at character 480, the next at 960. Your friend files them in order and leaves gaps for the missing ones. Every so often they send you a postcard back: "I have everything up to character 2,400." That one sentence tells you which cards made it, and if a while passes and the number stops going up, you send the cards after it again. You'd also agree first on where the numbering starts, so cards from an old book aren't mixed into the new one. You wouldn't send more cards than their letterbox can hold. And when the book is finished, you'd both say so, and make sure the other one heard.

That's TCP, the Transmission Control Protocol. It runs on top of the same unreliable IP that UDP does, and out of lost, reordered and duplicated packets it builds a reliable, ordered stream of bytes between two programs. The web, email, SSH, database connections and the BGP sessions that hold the Internet together all run over it.

This page follows one connection from our laptop to the web server at 203.0.113.80: the first packet byte by byte, the handshake that opens it, the machinery that keeps it reliable, and the goodbye that closes it, including the strange two-minute wait at the end.

What TCP Promises

UDP's header was a port pair, a length and a checksum. TCP's promise is much bigger:

  • Connection-oriented. Before any data flows, the two sides run a handshake and agree on starting sequence numbers. At the end, each side says when it's finished.
  • Reliable. Every byte the sender writes either arrives or the connection reports failure. Lost data is retransmitted, damaged data is discarded and resent.
  • Ordered and duplicate-free. The receiving program reads bytes in exactly the order they were written, each exactly once, however the packets arrived.
  • A byte stream, full duplex. Each direction is an independent stream of bytes, with no message boundaries. Both directions run at once.
  • Flow-controlled. A fast sender can't overrun a slow receiver.
  • Congestion-controlled. A sender backs off when the network is overloaded. That's the subject of the next article.

TCP is IP protocol number 6. Vint Cerf and Bob Kahn described it in 1974; the version we use was standardised in RFC 793 in September 1981, split from IP the way the UDP article told. In August 2022, RFC 9293 replaced RFC 793 with a single document that gathers up four decades of fixes. The basic header hasn't changed since 1981.

The running example

Our laptop, 192.168.10.10 on VLAN 10, is going to fetch a page from the web server at 203.0.113.80, port 80. (Plain HTTP so that we can read the bytes. HTTPS on port 443 is identical at the TCP level: the encrypted bytes are just TCP's payload.) The browser asks the kernel for a TCP socket and calls connect(), and the kernel picks an ephemeral source port from Linux's range, 32768–60999. This time it picks 47130.

Our connection, as a four-tuple

protocol   TCP (6)
laptop     192.168.10.10 : 47130    ephemeral port
server     203.0.113.80  : 80       HTTP

A TCP connection is identified by all four values. The server can have thousands of connections on port 80 at once, and they never get confused, because no two have the same remote address and port. On the way out, R1's NAT rewrites the source to its WAN address 198.51.100.23 and fixes the checksums, so the server sees the connection as coming from 198.51.100.23. Everything on this page is shown from the laptop's side of R1.

Every TCP packet is called a segment, and every segment starts with this header. It's 20 bytes when there are no options, and the data follows straight after. Here are the values from the first segment of our connection, the SYN, which carries 20 bytes of options:

bit 0 4 8 16 31 Source port (2) b8 1a = 47130 Destination port (2) 00 50 = 80 Sequence number (4) 6b 2f 91 c4 = 1798279620 Acknowledgment number (4) 00 00 00 00 (ignored: ACK flag is off) Offset a = 10 Reserved 0 CEUAPRSF flags 02 = SYN Window (2) fa f0 = 64240 Checksum (2) 06 4a Urgent pointer (2) 00 00 Options (0–40 bytes, a multiple of 4) here 20: MSS 1460 · SACK-permitted · timestamps · NOP · window scale 7 Fixed part 20 bytes. Data offset × 4 = header length, so 20 to 60 bytes.
Bytes Field Meaning
0–1 Source port The sending program's port
2–3 Destination port The receiving program's port
4–7 Sequence number Stream position of this segment's first data byte (or of the SYN)
8–11 Acknowledg­ment number The next byte the sender expects to receive. Valid only if ACK is set.
12, top 4 bits Data offset Header length in 32-bit words, 5 to 15
12, low 4 bits Reserved Zero. RFC 9768 (April 2026) gives the lowest bit to Accurate ECN as "AE".
13 Flags Eight 1-bit flags, below
14–15 Window How many more bytes the sender of this segment is willing to receive
16–17 Checksum Over a pseudo-header, the TCP header and the data
18–19 Urgent pointer Only meaningful with URG. Effectively unused.

There's no length field. UDP needed one; TCP takes the segment's length from the IP header, and the receiver works out where the data starts from the data offset.

The flags

Byte 13 holds eight flags, most significant bit first:

Bit Flag Meaning when set
0x80 CWR Congestion Window Reduced: "I saw your ECE and slowed down" (RFC 3168)
0x40 ECE ECN-Echo: "a router marked one of your packets as congested"
0x20 URG The urgent pointer is valid
0x10 ACK The acknowledgment number is valid. Set on every segment after the first.
0x08 PSH Push: deliver to the application now, don't wait for more
0x04 RST Reset: abort the connection, or "no such connection"
0x02 SYN Synchronise sequence numbers: the first segment from each side
0x01 FIN Finished: the sender has no more data to send

The combinations you'll see most are 02 (SYN), 12 (SYN + ACK), 10 (a plain ACK), 18 (data with PSH + ACK, as in the Layers article's frame), 11 (FIN + ACK) and 14 (RST + ACK). The two ECN flags belong to the Congestion Control article. URG and the urgent pointer were meant for things like a Telnet user pressing Ctrl-C ahead of a pile of queued output; implementations never agreed on what the pointer pointed at, and RFC 6093 (2011) advises new applications not to use it.

The checksum

TCP's checksum is the same 16-bit ones'-complement Internet checksum as UDP's, over the same kind of pseudo-header: source and destination address, a zero byte, the protocol number, and the length. The only differences are that the protocol is 6, the length is the TCP segment's length (which the receiver computes from the IP header, since TCP has none), and the checksum is mandatory, over IPv4 as well as IPv6. So unlike UDP, 0000 doesn't mean "no checksum" and needs no special treatment. We'll work it out for real in a moment.

Options

Everything after the 20 fixed bytes, up to the data offset, is options. Each option is a kind byte, then (for all but two) a length byte counting the whole option, then its value. The options space is at most 60 − 20 = 40 bytes, and it has to end on a 4-byte boundary, which is what the one-byte NOP is for.

Kind Length Option
0 1 End of option list
1 1 No-operation: padding, to align the next option
2 4 Maximum Segment Size (SYN only)
3 3 Window scale (SYN only)
4 2 SACK permitted (SYN only)
5 10, 18, 26 or 34 SACK: 1 to 4 blocks of received data
8 10 Timestamps: TSval and TSecr, 32 bits each
34 variable TCP Fast Open cookie
  • MSS (RFC 9293). "Don't send me segments with more than this much data." It's the largest TCP payload that fits the sender's link MTU: 1500 − 20 (IPv4) − 20 (TCP) = 1460, or 1500 − 40 − 20 = 1440 over IPv6. Each side announces its own in its SYN. If a side sends no MSS option, the other must assume 536 bytes for IPv4 and 1220 for IPv6.
  • Window scale (RFC 7323). A shift count, 0 to 14. From then on, every window field the sender of this option sends is to be read multiplied by 2shift. It's used only if both SYNs carry it. More in Flow Control.
  • SACK permitted and SACK (RFC 2018). The SYN option says "I understand selective acknowledgements"; later ACKs can then carry SACK blocks, pairs of 32-bit sequence numbers describing data received beyond a gap. More in SACK.
  • Timestamps (RFC 7323). The sender puts a clock value in TSval; the receiver echoes the most recent one back in TSecr. That gives a round-trip measurement on every ACK, even for retransmitted data, and protects against wrapped sequence numbers (PAWS). It costs 10 bytes in every segment (12 with padding), which is why the Layers article's "real" segment had a 32-byte header.

The SYN, Byte by Byte

When the browser calls connect(), the laptop's kernel sends this. It's a complete IPv4 packet as it leaves the laptop, without the Ethernet header (from …aa:bb:01 to R1's …cc:dd:02, EtherType 0800, as in earlier articles). Both checksums were computed for these exact bytes.

Hex dump: a 60-byte SYN

0000  45 00 00 3c 8e 4d 40 00 40 06 a5 6b c0 a8 0a 0a  E..<.M@[email protected]....
0010  cb 00 71 50 b8 1a 00 50 6b 2f 91 c4 00 00 00 00  ..qP...Pk/......
0020  a0 02 fa f0 06 4a 00 00 02 04 05 b4 04 02 08 0a  .....J..........
0030  0c 4a 7e 19 00 00 00 00 01 03 03 07              .J~.........

 IPv4  bytes 0–19 ·  TCP header  bytes 20–39 ·  TCP options  bytes 40–59

There's no data at all. A SYN's whole job is to carry a starting sequence number and the options. Reading it the way the server's kernel would:

  1. Offset 0x00: IPv4

    45: version 4, 20-byte header. Total length 00 3c = 60. 40 00: Don't Fragment. TTL 40 = 64. Protocol 06, TCP. Header checksum a5 6b. Source c0 a8 0a 0a = 192.168.10.10, destination cb 00 71 50 = 203.0.113.80.

  2. Offset 0x14: ports and sequence numbers

    Source port b8 1a = 47130, destination 00 50 = 80. Sequence number 6b 2f 91 c4 = 1,798,279,620: the laptop's randomly chosen initial sequence number. Acknowledgment number zero, because there's nothing to acknowledge yet.

  3. Offset 0x20: offset, flags, window, checksum

    a0: data offset a = 10 words = 40 bytes, so 20 bytes of options. Flags 02: SYN only. Window fa f0 = 64,240 bytes, which is 44 × 1460: the laptop can take 44 full segments before the server must wait. (Windows in SYNs are never scaled.) Checksum 06 4a. Urgent pointer zero.

  4. Offset 0x28: options

    02 04 05 b4: MSS 1460. 04 02: SACK permitted. 08 0a then 0c 4a 7e 19 and 00 00 00 00: timestamps, TSval 206,208,537 (a millisecond clock with a random per-connection offset) and TSecr 0. 01: NOP. 03 03 07: window scale, shift 7, so the laptop's later windows are to be multiplied by 128. This is the order Linux uses.

The checksum, by hand

The method is exactly the UDP one: sum the 16-bit words of the pseudo-header and the segment, with the checksum field as zero, fold the carries back in, and flip the bits. The pseudo-header's length word is 0028 = 40, the whole segment.

The six pseudo-header words:

c0a8+0a0a+cb00+ 7150+0006+0028= 20730\begin{aligned} & \texttt{c0a8} + \texttt{0a0a} + \texttt{cb00} \\ +\ & \texttt{7150} + \texttt{0006} + \texttt{0028} \\ =\ & \texttt{20730} \end{aligned}

The ten words of the fixed header, checksum as zero:

b81a+0050+6b2f+ 91c4+0000+0000+ a002+faf0+ 0000+0000= 3504f\begin{aligned} & \texttt{b81a} + \texttt{0050} + \texttt{6b2f} \\ +\ & \texttt{91c4} + \texttt{0000} + \texttt{0000} \\ +\ & \texttt{a002} + \texttt{faf0} \\ +\ & \texttt{0000} + \texttt{0000} \\ =\ & \texttt{3504f} \end{aligned}

The ten words of options:

0204+05b4+0402+ 080a+0c4a+7e19+ 0000+0000+ 0103+0307= a231\begin{aligned} & \texttt{0204} + \texttt{05b4} + \texttt{0402} \\ +\ & \texttt{080a} + \texttt{0c4a} + \texttt{7e19} \\ +\ & \texttt{0000} + \texttt{0000} \\ +\ & \texttt{0103} + \texttt{0307} \\ =\ & \texttt{a231} \end{aligned}

Total:

20730+3504f+a231= 5f9b0\begin{aligned} & \texttt{20730} + \texttt{3504f} + \texttt{a231} \\ =\ & \texttt{5f9b0} \end{aligned}

Fold the carry:

f9b0+5=f9b5\texttt{f9b0} + \texttt{5} = \texttt{f9b5}

Flip every bit:

¬ f9b5=064a\lnot\,\texttt{f9b5} = \texttt{064a}

That's the 06 4a in bytes 16–17. The server checks it the UDP way: the sum of everything, checksum included, is 5f9b0 + 064a = 5fffa, which folds to fffa + 5 = ffff.

Over IPv6, from 2001:db8:1234:10:0:ff:feaa:bb01 to 2001:db8:113::80, the same SYN would announce MSS 1440 (05 a0), and with the bigger pseudo-header (addresses, 32-bit length 00000028, three zero bytes and next header 06) its checksum comes out as e3 6c. The widget below shows that one word by word too.

Addresses and ports

Sequence numbers (decimal, or hex with 0x)

Flags, window and urgent pointer

Options (laid out the way Linux does)

Payload

The segment


      

Pseudo-header, never sent

Built in memory by sender and receiver from the IP header’s fields, checksummed, and thrown away.


      

The checksum

Every 16-bit word, in order, with the running total:

Sequence Numbers Count Bytes

Our homemade protocol in the UDP article numbered messages: 1, 2, 3. TCP numbers bytes. Each direction of a connection is a stream of bytes, every byte has a 32-bit sequence number, and a segment's sequence number field is the number of its first data byte. If a segment carries 37 bytes starting at sequence number S, the next segment starts at S + 37. That way the sender can cut the stream into segments however it likes, and resend a different cut of the same bytes later, and the receiver still knows exactly where everything goes.

The acknowledgment number works the same way: it's the sequence number of the next byte the receiver expects, which means "I have every byte before this one". That's a cumulative ACK.

SYN and FIN each take a number

There's one twist. The SYN and the FIN each consume one sequence number, as if they were a byte of data. That way they can be acknowledged, and retransmitted, exactly like data. So our connection's numbers go like this:

Where the laptop's numbers go

1798279620          SYN                    (the ISN)
1798279621 - ...657 GET / HTTP/1.1 ...    37 bytes of data
1798279658          FIN

The server's first ACK says 1798279621: "I got your SYN, send byte 1798279621 next." After the request it says 1798279658, and after the FIN, 1798279659. Packet analysers like Wireshark show relative numbers instead, counting from the ISN: SYN 0, data 1 to 37, FIN 38. We'll use relative numbers from here on when the absolute ones would only get in the way.

Why the ISN is random

If every connection started at zero, a delayed segment from an old connection between the same two ports could land in the right place in a new one. It's also an invitation to attackers. As far back as 1985, Robert T. Morris showed that predictable ISNs let someone who can't see the replies forge a whole TCP connection from a trusted address, by guessing the server's ISN; Kevin Mitnick famously used the technique on Christmas Day, 1994.

Modern stacks follow RFC 6528 (2012), which RFC 9293 now includes:

ISN = M + F(local IP, local port, remote IP, remote port, secret key)
# M: a clock that ticks every 4 microseconds
# F: a keyed hash, such as SipHash, that outsiders can't compute

Different connections get unrelated starting points that no outsider can predict. But the same four-tuple's starting point still moves forward with the clock, so a new connection on the same ports starts above where an old one probably left off.

Wraparound and PAWS

A 32-bit sequence number runs out after 232 bytes, 4 GiB, and wraps round to zero. That's fine: TCP compares sequence numbers modulo 232 ("is a less than b" means "is b − a, as a 32-bit number, between 1 and 231 − 1"), and connections happily carry terabytes.

The danger is speed. At 1 Gb/s the numbers wrap in

232×8109≈34 s\frac{2^{32} \times 8}{10^{9}} \approx 34\text{ s}

and at 10 Gb/s in about 3.4 s, while a delayed segment may, in theory, survive in the network for up to two minutes.

A segment delayed long enough could arrive after the numbers have wrapped and look like new data. PAWS, Protection Against Wrapped Sequences (RFC 7323), uses the timestamps option to spot it: a segment whose TSval is older than one already seen on this connection is discarded, whatever its sequence number says.

The Three-Way Handshake

Before data flows, each side has to tell the other its ISN and hear that it arrived. That's two SYNs and two ACKs, but the server's ACK rides on its own SYN, so it takes three segments:

Laptop 192.168.10.10:47130 Web server 203.0.113.80:80 CLOSED SYN-SENT ESTABLISHED LISTEN SYN-RECEIVED ESTABLISHED SYN seq=1798279620 MSS 1460 · SACK ok · TS · WS 7 SYN-ACK seq=3558738487 ack=1798279621 · MSS 1460 · … ACK seq=1798279621 ack=3558738488 PSH, ACK seq=1798279621 37 bytes: GET / HTTP/1.1 … Relative numbers, as Wireshark shows them: SYN 0; SYN-ACK 0, ack 1; ACK 1, ack 1.
  1. SYN: "Here's my starting number"

    The laptop sends the SYN we just decoded, with ISN 1798279620, and moves to SYN-SENT. It starts a retransmission timer: if no answer comes in one second (RFC 6298's initial timeout), it sends the SYN again, doubling the wait each time. Linux tries six retransmissions, giving up after a little over two minutes.

  2. SYN-ACK: "Got it. Here's mine"

    The server has a socket in LISTEN on port 80. Its kernel records the request, moves it to SYN-RECEIVED and answers with flags SYN and ACK, its own random ISN 3558738487, and acknowledgment number 1798279621: the laptop's ISN plus one, for the SYN. It sends its own MSS, SACK-permitted, timestamps (echoing the laptop's TSval) and window scale.

  3. ACK: "Got yours"

    The laptop moves to ESTABLISHED and acknowledges the server's SYN with ack 3558738488. When it arrives, the server is ESTABLISHED too, and its kernel queues the new connection for the web server program's next accept(). The laptop doesn't wait: its first data can follow the ACK immediately, or even ride in the same segment.

The cost is one round trip before the first byte of data can be sent, on top of DNS, and before TLS adds its own round trip for HTTPS. On a 100 ms path that's 100 ms on every new connection, which is what TCP Fast Open and QUIC try to claw back.

Why three segments and not two? Because both ISNs have to be acknowledged. With only a SYN and a SYN-ACK, the server would never learn whether its ISN arrived, or whether the SYN it answered was a fresh one or an old duplicate still wandering the network from a previous attempt. RFC 793 gives exactly that example: if an old SYN reaches the server, the server's SYN-ACK acknowledges a sequence number the laptop never used, and the laptop answers with a reset instead of an ACK.

Two rarer cases fit the same rules. If nothing is listening on the port, the server's kernel answers the SYN with RST + ACK, and connect() fails at once with "connection refused". And if both ends send a SYN to each other at the same moment, a simultaneous open, each goes from SYN-SENT to SYN-RECEIVED and both connections merge into one. It almost never happens on purpose, but the state machine allows it.

Closing: Four Segments and a Wait

A TCP connection is two independent byte streams, so it closes one direction at a time. When an application calls close() (or shutdown() for writing), its TCP sends a FIN: "I have no more data". The other side ACKs it, but may go on sending data of its own for as long as it likes, a half-close. When it's done too, it sends its own FIN, and that gets ACKed.

Suppose the laptop has sent its 37-byte request, received the server's 1,256-byte response, and closes first. In relative numbers:

Laptop closes first (active close) Web server passive close ESTABLISHED FIN-WAIT-1 FIN-WAIT-2 TIME-WAIT CLOSED ESTABLISHED CLOSE-WAIT LAST-ACK CLOSED waits 2 × MSL (60 s on Linux) FIN, ACK seq=38 ack=1257 "I'm done sending" ACK seq=1257 ack=39 "got your FIN" FIN, ACK seq=1257 ack=39 "me too" ACK seq=39 ack=1258 (the server may still send data here: a half-close)

The FIN has sequence number 38, right after the 37 data bytes, and the server acknowledges it with 39 because it consumed a number. If the server has nothing left to say, its ACK and FIN are often combined into one segment, and the close takes three segments instead of four.

The side that closes first does an active close and goes through FIN-WAIT-1, FIN-WAIT-2 and TIME-WAIT. The other side does a passive close: its kernel ACKs the FIN and moves to CLOSE-WAIT, where it waits for its application to notice (a read() returns 0, "end of file") and call close(). Then it sends its FIN and waits in LAST-ACK for the final ACK. (A server with thousands of connections stuck in CLOSE-WAIT almost always has an application bug: it never closes sockets whose peers have gone.)

The State Machine

Everything above fits into a state machine of eleven states, which RFC 793 drew in 1981 and RFC 9293 keeps. Each connection is in exactly one state at a time, and ss -tan on Linux shows the state of every socket on the machine.

passive open active open send SYN rcv SYN send SYN-ACK rcv SYN-ACK send ACK rcv ACK close send FIN rcv FIN send ACK rcv ACK rcv FIN send ACK rcv FIN send ACK rcv ACK 2 × MSL timeout close send FIN rcv ACK CLOSED LISTEN SYN-SENT SYN-RECEIVED ESTABLISHED FIN-WAIT-1 CLOSING CLOSE-WAIT FIN-WAIT-2 TIME-WAIT LAST-ACK CLOSED usual client path usual server path
State What it means
CLOSED No connection. Not a real state, just the absence of one.
LISTEN A server socket waiting for SYNs
SYN-SENT Sent a SYN, waiting for the SYN-ACK
SYN-RECEIVED Got a SYN, sent a SYN-ACK, waiting for the ACK
ESTABLISHED Open: data flows both ways
FIN-WAIT-1 We sent a FIN, it hasn't been ACKed yet
FIN-WAIT-2 Our FIN was ACKed; waiting for the peer's FIN
CLOSE-WAIT The peer sent a FIN; waiting for our application to close
LAST-ACK We've sent our FIN too; waiting for its ACK
CLOSING Both sides sent FINs at once; waiting for the ACK of ours
TIME-WAIT All done; waiting 2 × MSL before forgetting the connection

Why TIME-WAIT exists

The side that sends the last ACK can't simply forget the connection. RFC 9293 defines the Maximum Segment Lifetime, MSL, as two minutes, the longest a segment is assumed to survive in the network, and the active closer waits in TIME-WAIT for 2 × MSL. (Linux uses a fixed 60 seconds for the whole of TIME-WAIT.) There are two reasons:

  1. The last ACK might be lost. If the server never gets it, its FIN timer fires and it resends the FIN. A laptop still in TIME-WAIT recognises the FIN and ACKs it again. A laptop that had forgotten everything would answer with a reset, and the server would report an error on a connection that actually finished cleanly.
  2. Old duplicates must die out. If the laptop opened a new connection with the same four-tuple straight away, a delayed segment from the old one could arrive inside the new one's window and be taken for real data. Waiting long enough for anything from the old connection to expire means that can't happen.

TIME-WAIT has a cost: it ties up the four-tuple. A client that opens and closes thousands of short connections to the same server address and port can run out of ephemeral ports: with Linux's 28,232 ports and a 60-second TIME-WAIT, that's about 470 new connections a second. Connection reuse (HTTP keep-alive, connection pools) is the real fix; Linux's tcp_tw_reuse lets a new outgoing connection reuse a TIME-WAIT four-tuple when timestamps prove the new segments are newer. Because only the active closer pays, servers generally prefer that clients close first.

Resets and half-open connections

The RST flag means "this connection doesn't exist, or doesn't any more". A TCP sends one when a segment arrives that makes no sense: a SYN to a port with no listener, or data for a connection it has no record of. An application can also abort a connection on purpose (on Linux, by closing with SO_LINGER set to zero), which sends a RST and throws away any unsent data. Nobody ACKs a RST; the receiver just drops the connection, and its application sees "connection reset by peer".

That's what clears up half-open connections. Suppose the server crashes and reboots while the laptop's connection is idle. The laptop still thinks it's ESTABLISHED. The server has no memory of it. The next time the laptop sends anything, the server's kernel finds no matching connection and answers with RST, and the laptop tears down its side. The opposite case is nastier: if the laptop vanishes (battery dies, Wi-Fi drops) the server may never send anything that would trigger a RST, and it holds the connection open forever. That's what keepalives and application timeouts are for.

Because a RST can kill any connection, an attacker who could forge one would have an easy weapon. RFC 5961 (2010) makes it hard: a RST is accepted only if its sequence number is exactly the next one expected. One that's merely somewhere in the window gets a "challenge ACK" back instead, which a real peer will answer with a correctly numbered RST, and a blind attacker can't.

Reliability: ACKs and Retransmission

Now the part TCP exists for. Data is sent in segments, the receiver ACKs what it has, and anything not ACKed in time is sent again. Each piece is the UDP article's homemade protocol, done properly.

Cumulative ACKs

TCP's acknowledgment number means "everything before this has arrived". That has two pleasant consequences. A receiver doesn't need to ACK every segment separately; one ACK covers all the data so far. And a lost ACK is harmless as long as a later one gets through, because the later one says everything the lost one did and more.

What a cumulative ACK can't say is "I have some of what comes after the gap". If segment 2 of 5 is lost, the receiver keeps saying "everything before segment 2" however many later segments turn up, and the sender can't tell which of them arrived. SACK fixes that.

The retransmission timer

When a segment isn't ACKed in time, the retransmission timeout (RTO) fires and the oldest unacknowledged segment is sent again. The UDP article used a fixed 200 ms. TCP can't: the round trip time is 1 ms across a data centre and 600 ms over a geostationary satellite, and it changes from moment to moment as queues fill and drain. Too short an RTO resends data that wasn't lost; too long, and every loss stalls the connection.

So TCP measures. Every round trip it can time (send time to the ACK covering that segment) is a sample R. RFC 6298 keeps a smoothed average, SRTT, and a smoothed measure of how much the samples vary, RTTVAR, and sets the timeout to the average plus four times the variation. This is Van Jacobson's 1988 algorithm:

On the first sample RR:

SRTT=RRTTVAR=R/2\begin{aligned} \text{SRTT} &= R \\ \text{RTTVAR} &= R/2 \end{aligned}

On each later sample R′R', update RTTVAR first, using the old SRTT:

RTTVAR=34 RTTVAR+14 ∣SRTT−R′∣SRTT=78 SRTT+18 R′\begin{aligned} \text{RTTVAR} &= \tfrac{3}{4}\,\text{RTTVAR} \\ &\quad + \tfrac{1}{4}\,\lvert \text{SRTT} - R' \rvert \\ \text{SRTT} &= \tfrac{7}{8}\,\text{SRTT} + \tfrac{1}{8}\,R' \end{aligned}

Then, either way:

RTO=SRTT +max⁡(G, 4⋅RTTVAR)\begin{aligned} & \text{RTO} = \text{SRTT}\ + \\ & \max(G,\ 4 \cdot \text{RTTVAR}) \end{aligned}

Here G is the clock granularity, a floor so that a perfectly steady link doesn't get an RTO equal to its RTT. Before there's any sample, the RTO is 1 second.

Worked example: three round trips

Suppose the laptop's first three samples are 100 ms, 120 ms and 80 ms. In each update, the first number is three-quarters of the old RTTVAR (or seven-eighths of the old SRTT), and the second is a quarter of the gap between SRTT and the sample (or an eighth of the sample).

Sample 1, R=100R = 100:

SRTT=100RTTVAR=50RTO=100+4×50=300 ms\begin{aligned} \text{SRTT} &= 100 \\ \text{RTTVAR} &= 50 \\ \text{RTO} &= 100 + 4 \times 50 \\ &= 300\text{ ms} \end{aligned}

Sample 2, R′=120R' = 120:

RTTVAR=37.5+14×20=42.5SRTT=87.5+15=102.5RTO=102.5+170=272.5 ms\begin{aligned} \text{RTTVAR} &= 37.5 + \tfrac{1}{4} \times 20 \\ &= 42.5 \\ \text{SRTT} &= 87.5 + 15 \\ &= 102.5 \\ \text{RTO} &= 102.5 + 170 \\ &= 272.5\text{ ms} \end{aligned}

Sample 3, R′=80R' = 80:

RTTVAR=31.875+14×22.5=37.5SRTT=89.6875+10=99.6875RTO≈99.7+150≈249.7 ms\begin{aligned} \text{RTTVAR} &= 31.875 + \tfrac{1}{4} \times 22.5 \\ &= 37.5 \\ \text{SRTT} &= 89.6875 + 10 \\ &= 99.6875 \\ \text{RTO} &\approx 99.7 + 150 \\ &\approx 249.7\text{ ms} \end{aligned}

The average barely moves, but the variance term shrinks as the samples settle, so the timeout creeps closer to the real round trip. A sudden 300 ms sample would push RTTVAR up sharply and the timeout with it, which is exactly the caution you want when the path gets less predictable.

Three more rules finish the job:

  • A floor. RFC 6298 says an RTO below 1 second should be rounded up to 1 second. That's very conservative for modern networks, and Linux uses a 200 ms minimum instead (all three values above would stand; on a LAN with a 1 ms RTT, Linux still waits 200 ms).
  • Exponential backoff. Each time the timer fires, the RTO doubles (up to a cap of at least 60 seconds), so a dead path gets 0.25 s, 0.5 s, 1 s, 2 s… rather than a storm of retransmissions. A new measurement brings it back down.
  • Karn's algorithm. Never take a sample from a segment that was retransmitted: when its ACK comes back, there's no telling which copy it's for. (Phil Karn and Craig Partridge, 1987.) The timestamps option sidesteps the problem, because the echoed TSval says exactly which copy the ACK is answering.

Fast retransmit: three duplicate ACKs

Waiting for the timer is slow: at least 200 ms, often much more. But a receiver often hands the sender a strong hint much sooner. When a segment arrives after a gap, the receiver can't advance its cumulative ACK, so it immediately sends the same ACK again, a duplicate ACK. Each one means "something arrived, but I'm still missing the byte I named".

Segment 2 of 6 goes missing

sender  →  seq 1     arrives      ACK 1001
sender  →  seq 1001  LOST
sender  →  seq 2001  arrives      ACK 1001   duplicate 1
sender  →  seq 3001  arrives      ACK 1001   duplicate 2
sender  →  seq 4001  arrives      ACK 1001   duplicate 3  → resend 1001 now
sender  →  seq 5001  arrives      ACK 1001   duplicate 4
           seq 1001  (again)      ACK 6001   all six segments in

One duplicate ACK might just mean two segments swapped places on the way. Three in a row almost certainly means a loss, so the sender retransmits the missing segment straight away, without waiting for the timer. When it arrives, the ACK jumps from 1001 to 6001, because the receiver had been holding segments 3 to 6 all along.

That's fast retransmit, introduced by Van Jacobson in BSD in the late 1980s and now part of RFC 5681. It needs at least three segments to arrive after the lost one, so it can't rescue a loss at the very end of a transfer, when nothing follows. Those still wait for the RTO.

If two segments in the same window are lost, plain cumulative ACKs make things slow: the retransmission of the first hole produces an ACK that stops at the second hole (a partial ACK), and only then can the sender resend the second. One round trip per lost segment. The "NewReno" rules (RFC 6582) at least resend at once on each partial ACK, rather than waiting for three fresh duplicates.

Selective acknowledgements

SACK (RFC 2018, 1996) lets the receiver say what it does have beyond the gap. If both SYNs carried SACK-permitted, a duplicate ACK can carry up to four SACK blocks, each a left edge and right edge of contiguous data received out of order (three if the timestamps option is also using up space):

Two holes, one ACK

ACK 1001   SACK 5001-6001, 2001-4001

"I have everything before 1001. I also have 2001 to 4000 and 5001 to 6000." The blocks' right edges are the first byte after each block. The sender can see two holes, 1001–2000 and 4001–5000, and resend both at once instead of discovering the second a round trip later. The first block is always the one containing the most recently received segment.

Today nearly every TCP stack negotiates SACK, and Linux enables it by default. RFC 6675 describes how a sender uses the information during recovery.

Delayed ACKs

Sending an ACK for every single segment doubles the packet count in the reverse direction. So receivers delay ACKs: a receiver that has just got one segment waits a little, hoping either a second segment arrives (then one ACK covers both) or the application writes a reply (then the ACK rides along on the reply for free). RFC 9293 requires the delay to be less than 0.5 seconds and says to ACK at least every second full-sized segment. Linux delays between 40 ms and 200 ms and adapts; Windows defaults to 200 ms. Out-of-order segments are always ACKed immediately, since those duplicate ACKs are what fast retransmit feeds on.

Nagle's algorithm

The opposite problem is the sender of tiny writes. A Telnet or SSH user typing one character at a time would send a 41-byte packet (20 IP + 20 TCP + 1) per keystroke, almost all of it header. In 1984 John Nagle proposed (RFC 896) a simple rule:

def on_application_write(data):
    buffer.append(data)
    try_send()
def try_send():
    if len(buffer) >= MSS and window_allows(MSS):
        send(buffer.take(MSS))               # full segments always go
    elif nothing_unacknowledged_in_flight():
        send(buffer.take_all())              # small segment OK if the pipe is empty
    # otherwise: hold small data until an ACK arrives, then try again
def on_ack():
    try_send()

At most one small segment is in flight at a time. While it's out, further keystrokes pile up in the buffer and go together when the ACK comes back. On a fast LAN that's barely noticeable; on a slow link it saves a great deal of overhead. Linux and every other stack enable Nagle by default.

When Nagle meets delayed ACK

Each idea is sensible on its own. Together they can produce a stall. Picture a client that sends each request in two writes, a small header and then a small body, before reading the reply:

  1. Write the header

    Nothing is in flight, so Nagle lets the header go at once.

  2. Write the body

    The header isn't ACKed yet, so Nagle holds the small body back.

  3. The server waits

    The server got the header but can't reply until it has the body, so it has nothing to piggyback an ACK on. Delayed ACK holds the ACK for its timer: 40 ms on Linux, 200 ms on Windows.

  4. Finally

    The delayed-ACK timer fires, the ACK reaches the client, Nagle releases the body, and the server can answer. Every request has paid up to 200 ms for nothing.

This write-write-read pattern is a classic performance bug. The fixes: assemble the whole request and write it in one call (or with writev()), or set TCP_NODELAY on the socket to turn Nagle off. Latency-sensitive programs, from SSH to game servers to most RPC libraries, set TCP_NODELAY routinely.

Flow Control: The Receive Window

Reliability stops data getting lost on the network. Flow control stops it overflowing the receiver. Each TCP has a receive buffer, where data waits until the application calls read(). If the application is slow (it's writing to a slow disk, or simply busy), the buffer fills, and any more data would have to be thrown away.

So every segment carries a window: how many more bytes, beyond the acknowledgment number, the sender of that segment can accept right now. The other side may send up to that much unacknowledged data and no more. As the receiver's application reads, buffer space frees up and the window in later ACKs grows again. That's the sliding window: the range of sequence numbers the sender may use slides forward as ACKs arrive.

130016001900112001 SND.UNA 1001 SND.NXT 4001 SND.UNA + window window: 5,000 bytes ACKed sent, not ACKed may send now not yet: outside the window

The variable names come from RFC 9293: SND.UNA is the oldest unacknowledged byte, SND.NXT the next byte to send, and SND.WND the window the receiver last advertised. When an ACK for 2001 arrives with a window of 5,000, the left edge moves to 2001 and the right edge to 7001, and one more segment's worth may be sent.

Zero window and the persist timer

If the receiving application stops reading altogether, the buffer fills and the receiver advertises a window of zero: "send nothing more". The sender stops. Later the application reads, space frees up, and the receiver sends an ACK with a bigger window, a window update.

But that window update carries no data, so nobody ACKs it, and nobody would notice if it were lost. The sender would wait for a window that it believes is still zero, and the receiver would wait for data that never comes. Deadlock. To prevent it, a sender facing a zero window starts a persist timer and, when it fires, sends a zero-window probe: a tiny segment that forces the receiver to reply with an ACK showing its current window. (Linux sends one with an already-acknowledged sequence number, SND.UNA − 1, and no data.) If the window is still zero, the sender backs off exponentially and probes again, for as long as the receiver keeps answering.

Window scaling

The window field is 16 bits, so it can't say more than 65,535 bytes. In 1981 that was plenty. Today it's a hard speed limit, because a sender can have at most one window of data in flight per round trip:

throughput≤windowRTT\text{throughput} \le \frac{\text{window}}{\text{RTT}}

With a 65,535-byte window and a 100 ms round trip:

65,535×8 bits0.1 s≈ 5.2 Mb/s\begin{aligned} & \frac{65{,}535 \times 8\text{ bits}}{0.1\text{ s}} \\ \approx\ & 5.2\text{ Mb/s} \end{aligned}

To fill a 1 Gb/s path with a 100 ms RTT, the window must hold the bandwidth-delay product:

109 b/s×0.1 s= 108 bits=12.5 MB\begin{aligned} & 10^{9}\text{ b/s} \times 0.1\text{ s} \\ =\ & 10^{8}\text{ bits} = 12.5\text{ MB} \end{aligned}

The window scale option (RFC 1323 in 1992, now RFC 7323) fixes this without changing the header. Each side announces a shift count in its SYN, and every later window field it sends means field × 2shift. Our laptop announced 7, so a window field of 01 f5 (501) in one of its later segments means 501 × 128 = 64,128 bytes. The maximum shift is 14, for windows up to 65,535 × 214 = 1,073,725,440 bytes, about 1 GiB. Scaling is used only if both SYNs carry the option; if the server's SYN-ACK hadn't, neither side would scale. (That's also why windows in SYNs themselves are never scaled: nobody knows yet whether scaling is on.)

Silly window syndrome

There's one way a window can go badly wrong. Suppose the receiver's application reads one byte at a time. Each read frees one byte of buffer, the receiver advertises a window of 1, the sender dutifully sends a 1-byte segment, and the connection fills with 41-byte packets carrying one byte each. David Clark named this silly window syndrome in RFC 813 (1982), and the cure is applied at both ends:

  • The receiver doesn't advertise small increases. It keeps announcing zero (or the old value) until the free space reaches a full MSS or half its buffer, whichever is smaller.
  • The sender doesn't send small segments into a small window: it waits until it can send a full segment, or at least half the largest window the receiver has offered, or everything it has. Nagle's algorithm is part of the same family.

Watch it all happen

The simulator below runs a complete connection, the laptop uploading 12,000 bytes to the server, with every mechanism from this page switched on. To keep the picture readable it uses 1,000-byte segments, a one-way delay of 50 ms plus 0–10 ms of random jitter, a sender that paces segments 10 ms apart, and a congestion window held fixed at five segments (the next article sets it free). The handshake and the close are never lost; everything in between can be. The RTO follows RFC 6298 with Linux's 200 ms floor, and the receiver ACKs every segment.

With the defaults, seed 196 and 10% loss, here's what happens:

  1. 0–150 ms: handshake

    The SYN-ACK comes back at 100 ms. That's the first RTT sample, so SRTT = 100, RTTVAR = 50 and RTO = 300 ms. The laptop sends five segments, 10 ms apart, from 110 ms: a full window. Segments 2 (seq 1001) and 5 (seq 4001) are lost.

  2. 222–327 ms: duplicate ACKs

    ACK 1001 arrives at 221.9 ms and lets segment 6 go. Segments 3, 4 and 6 reach the server after the gap, and each produces another ACK 1001. The third duplicate arrives at 327.0 ms and the laptop fast-retransmits seq 1001 at once. The RTO wouldn't have fired until 485.2 ms.

  3. 429–542 ms: a partial ACK

    The retransmission fills the first hole, but the server is still missing seq 4001, so its ACK only climbs to 4001. That partial ACK arrives at 429.3 ms and the laptop resends seq 4001 straight away; ACK 6001 arrives at 541.7 ms. The second hole cost a whole extra round trip.

  4. 562–921 ms: a tail loss

    The last segment, seq 11001, is lost. Nothing follows it, so there are no duplicate ACKs, and the laptop has to wait for the RTO, 200 ms after the last ACK: it fires at 867.9 ms. The retransmission arrives at 920.6 ms, and all 12,000 bytes are in.

  5. 980–1150 ms: close

    The laptop's FIN goes at 980.4 ms. It enters TIME-WAIT at 1100.4 ms, and the server is CLOSED at 1150.4 ms.

Now switch on SACK and replay. The third duplicate ACK carries SACK 5001-6001, 2001-4001, so the laptop can see both holes and resends seq 4001 at 337.0 ms, right behind seq 1001. ACK 6001 arrives at 449.4 ms instead of 541.7, and all the data is in by 838.1 ms instead of 920.6. The tail loss still needs the timer: SACK can only describe data that arrived.

Then try the slow reader preset: no loss, but the server has a 4,000-byte receive buffer and its application doesn't read anything until 700 ms. The ACKs carry windows of 3,000, 2,000, 1,000 and then 0, at 242.8 ms. With nothing in flight, the laptop starts its persist timer (one RTO, 200 ms), and its window probe at 442.8 ms gets back "window 0". At 700 ms the application reads everything, the server sends a window update for 4,000 bytes, and sending resumes at 754.7 ms.

The laptop uploads 12,000 bytes in 1,000-byte segments, at least 10 ms apart, with the congestion window fixed at five segments. The handshake and the close are never lost.

The path

The receiver

Event log (times in ms)

A Stream Has No Boundaries

The UDP article ended its comparison with this, and it's worth seeing from TCP's side. TCP delivers bytes, not messages. When the laptop's application writes 100 bytes and then 200, TCP is free to send them as one 300-byte segment, or as three segments of 100, or to wait and combine them with the next write. The server's read() returns whatever has arrived and fits in its buffer: maybe 300 bytes at once, maybe 50 and then 250. The boundary between the two writes doesn't exist on the receiving side.

UDP

One sendto() is one datagram is one recvfrom(). A message arrives whole or not at all, but maybe out of order, maybe twice.

TCP

Bytes arrive exactly once and in order, but writes and reads don't line up. The application must mark where its messages begin and end.

So every protocol on top of TCP has its own framing. There are two common ways:

  • A delimiter. HTTP/1.1 ends its header block with a blank line (\r\n\r\n), and SMTP ends a message with a line containing a single dot. Simple, but the delimiter can't appear in the data unless it's escaped.
  • A length prefix. Each message starts with its own length. BGP messages begin with a 16-byte marker and a 2-byte length, TLS records carry a 2-byte length, and HTTP/2 frames a 3-byte one.

Reading a length-prefixed message has to cope with recv() returning less than you asked for:

def recv_exact(sock, n):
    buf = b""
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))     # may return fewer bytes than asked
        if not chunk:
            raise EOFError("peer closed")   # recv() returning nothing means FIN
        buf += chunk
    return buf
def recv_message(sock):
    length = int.from_bytes(recv_exact(sock, 4), "big")
    return recv_exact(sock, length)

The bug this prevents is real and common: code that works perfectly on a LAN, where each small write happens to arrive as one segment and one recv(), and breaks over the Internet, where a message can be split across segments or two messages can arrive glued together.

Keepalive

An idle TCP connection sends nothing at all. If one end vanishes without a FIN or RST, the other can sit in ESTABLISHED forever. Keepalive is an optional probe for that. After a connection has been idle for a while, TCP sends an empty segment with an old sequence number (SND.NXT − 1), which a live peer must answer with an ACK. (That's RFC 1122's choice; Linux uses SND.UNA − 1, like its zero-window probes, which is the same number on an idle connection.) No answer after several tries means the peer is gone, and the connection is dropped.

RFC 1122 says keepalives must be off by default and, when on, must wait at least two hours of idleness. Linux follows that: tcp_keepalive_time is 7,200 seconds, then 9 probes 75 seconds apart, so a dead peer is noticed after about 2 hours 11 minutes. That's far too slow for most applications, so they either tune it per socket (TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT) or send their own heartbeats, like BGP's KEEPALIVE messages. Keepalives also keep NAT and firewall entries from timing out, though NATs keep TCP mappings for much longer than UDP ones: RFC 5382 asks for at least 2 hours 4 minutes for an established connection.

A Second Window

Everything on this page protects the receiver. Nothing yet protects the network. A sender that only respects the receive window will happily blast a whole 8 MB window into a path whose bottleneck can't carry it, overflow a router queue, lose half of it, and retransmit, making the congestion worse.

So a TCP sender keeps a second limit, the congestion window (cwnd), its own estimate of how much the network can take, and never has more than the smaller of the two windows in flight. A new connection starts cwnd small and grows it quickly with slow start, then more carefully, and cuts it when loss or ECN marks show the network is full. How that works, and why it's what keeps the Internet from collapsing, is the Congestion Control article. (The simulator above held cwnd fixed at five segments, which is why it never sped up or slowed down.)

SYN Floods and SYN Cookies

The handshake has a weak spot. When a SYN arrives, the server has to remember it, the ISN it chose, the client's MSS and options, while it waits for the final ACK. Those half-open entries sit in a per-listener queue (the SYN queue), and a SYN-ACK that goes unanswered is retransmitted for about a minute (Linux tries five times) before the entry is dropped.

A SYN flood exploits that. The attacker sends SYNs from forged source addresses as fast as it can. Each one gets a SYN-ACK sent to an address that never asked for it, and an entry that will never complete. The queue fills, and genuine clients' SYNs are turned away. On 6 September 1996, a SYN flood knocked out Panix, one of New York's first Internet providers, for days, and the technique was suddenly famous.

There's no attack demo here; the defence is the interesting part. Within weeks, Daniel J. Bernstein and Eric Schenk worked out SYN cookies: don't store anything. Encode it in the server's ISN instead. In Bernstein's design, the 32-bit ISN is:

Bits Contents
5 A counter that ticks every 64 seconds, mod 32
3 Which of eight MSS values the server picked
24 A keyed hash of both addresses, both ports and the counter

The server sends the SYN-ACK and forgets the SYN completely. A real client answers with an ACK whose acknowledgment number is that ISN plus one. The server subtracts one, recomputes the hash from the ACK's addresses and ports and a recent counter value, and if it matches, it rebuilds the connection from the cookie, MSS included. A forged SYN costs the server one SYN-ACK and no memory at all.

The price is that a cookie only has room for the MSS: window scale, SACK-permitted and the like would be forgotten. Linux recovers them by encoding them in the low bits of the timestamp it sends, when the client uses timestamps. So cookies are a fallback, not the normal path: Linux's tcp_syncookies defaults to 1, which means "use cookies only when a listener's SYN queue overflows". RFC 4987 surveys this and the other defences: bigger queues, recycling the oldest half-open entry, firewalls that complete handshakes on the server's behalf, and, once again, BCP 38 filtering of forged source addresses.

Faster Starts and Head-of-Line Blocking

TCP's design is over forty years old, and two of its costs have become hard to ignore.

TCP Fast Open

The handshake costs a full round trip before any data. TCP Fast Open (RFC 7413, 2014) lets a client that has talked to a server before put data in the SYN itself. On the first connection, the server hands the client a cookie (option kind 34), typically a MAC of the client's IP address computed with a server secret. On the next connection, the client sends the cookie and its request in the SYN, and the server, having checked the cookie, passes the data to the application before the handshake finishes. The response can be on its way in the SYN-ACK's round trip.

The catch is that data in a SYN can be replayed: a duplicated SYN delivers the request twice, so TFO is only safe for requests that are harmless to repeat. It also ran into middleboxes that drop SYNs carrying data or unknown options, and it saw limited use. Its ideas live on in TLS 1.3's 0-RTT data and in QUIC.

Head-of-line blocking

TCP delivers one ordered stream. That's the whole point, and it's also its biggest limitation for the modern web. A browser fetching a page over HTTP/2 multiplexes dozens of resources (HTML, scripts, images) over one TCP connection. If a single segment carrying part of one image is lost, TCP can't hand the application any of the bytes after it, including complete pieces of unrelated files, until the retransmission arrives a round trip later. The receiver has the data in its buffer. It just isn't allowed to deliver it. That's head-of-line blocking, the same effect we saw in the UDP article's simulator, now hitting streams that have nothing to do with each other.

TCP can't fix it without breaking its own contract, and changing TCP itself is slow: it lives in operating system kernels and in the assumptions of countless middleboxes. That's why QUIC (RFC 9000) runs over UDP instead, with many independent streams in one connection, so a lost packet only stalls the stream it belonged to, and with the transport and TLS handshakes merged into one round trip. HTTP/3 runs on QUIC. TCP still carries a great deal of the Internet's traffic, and the ideas on this page, sequence numbers, cumulative and selective ACKs, adaptive timers and flow-control windows, are exactly the ones QUIC reimplemented.

Where to Go Next

  • Congestion Control: the second window. Slow start, AIMD, fast recovery, CUBIC and BBR, and how TCP shares a network fairly.
  • UDP: the protocol TCP was split from, and what you give up and gain without a connection.
  • NAT: how R1 tracks TCP connections by their flags and rewrites ports and checksums on the way through.
  • HTTP: what flows over the connection once it's open, and how HTTP/1.1, HTTP/2 and HTTP/3 deal with head-of-line blocking.
  • BGP: a long-lived TCP session on port 179, with its own keepalives and length-prefixed messages.
  • TLS (Encryption): the encrypted record layer that sits between TCP and HTTPS.

Key Takeaways

  • TCP (IP protocol 6; RFC 793, 1981; now RFC 9293, 2022) turns IP's unreliable packets into a reliable, ordered, flow- and congestion-controlled byte stream in each direction. A connection is identified by its four-tuple.
  • The header is 20 bytes plus up to 40 of options: ports, 32-bit sequence and acknowledgment numbers, a data offset, eight flags (CWR ECE URG ACK PSH RST SYN FIN), a 16-bit window, a mandatory checksum over the same pseudo-header as UDP with protocol 6, and the unused urgent pointer.
  • Options: MSS (1460 for IPv4 on Ethernet, 1440 for IPv6), window scale (shift up to 14), SACK-permitted and SACK blocks, timestamps (RTT measurement and PAWS), and Fast Open cookies. The laptop's SYN: 60 bytes, checksum 06 4a.
  • Sequence numbers count bytes; SYN and FIN each consume one. ISNs are unpredictable (RFC 6528). Numbers wrap after 4 GiB; PAWS uses timestamps to reject old segments.
  • Opening takes three segments (SYN, SYN-ACK, ACK) and one round trip; closing takes a FIN and an ACK in each direction. Eleven states; the active closer waits in TIME-WAIT for 2 × MSL (MSL = 2 minutes; Linux waits 60 s) to resend a lost final ACK and let old duplicates die.
  • RST aborts or rejects a connection and clears half-open ones; RFC 5961 makes forged resets hard.
  • ACKs are cumulative. The RTO follows RFC 6298: SRTT and RTTVAR with gains 1/8 and 1/4, RTO = SRTT + 4·RTTVAR, initially 1 s, minimum 1 s (Linux 200 ms), doubling on each timeout; Karn's algorithm skips retransmitted samples.
  • Three duplicate ACKs trigger fast retransmit. SACK lets the receiver report data beyond the gaps so several holes are repaired in one round trip. Tail losses still need the timer.
  • Delayed ACKs (under 0.5 s, every second full segment) and Nagle's algorithm (one small segment in flight) each save packets, but together they can stall write-write-read applications; TCP_NODELAY or single writes fix it.
  • The receive window stops a sender overrunning the receiver. A zero window is resolved by persist-timer probes; window scaling allows up to about 1 GiB, needed when the bandwidth-delay product exceeds 64 KB; SWS avoidance keeps both ends from trading tiny segments.
  • TCP has no message boundaries: applications frame messages with delimiters or length prefixes. Keepalives (off by default, 2 hours on Linux) detect vanished peers.
  • The congestion window caps sending too; that's the next article. SYN floods are defused by SYN cookies, which store the handshake state in the ISN. Fast Open saves the handshake round trip for repeat visits, and TCP's head-of-line blocking is the main reason QUIC exists.

TCP gets every byte to the other side, in order, without overrunning the receiver. But our simulated sender had a fixed five-segment limit, and the real question is where that number comes from. A sender alone on a path could use far more; a sender sharing a congested link with thousands of others must use far less, and must work it out from nothing but delays and losses. That's Congestion Control.