TCP: reliable, ordered, connection-based
TCPTCPThe transport protocol that delivers a reliable, ordered stream of bytes over a connection.Open in glossary → (Transmission Control Protocol) gives programs a connection: a two-way pipe where every byte sent arrives, exactly once, in the order it was sent. HTTP/1.1 and HTTP/2, database connections, SSH and email all run over TCP.
It starts with the three-way handshakeTCP handshakeThe three messages (SYN, SYN-ACK, ACK) that open a TCP connection, costing one round trip.Open in glossary →:
client server
| ---- SYN (I'd like to connect) ----> |
| <--- SYN-ACK (OK, me too) ---------- |
| ---- ACK (great) ------------------> |
| connection established |That costs one round trip before any data is sent. On a 100 ms mobile connection, 100 ms are gone before the request even starts.
Then TCP keeps its promise like this:
- Numbering: every byte has a sequence number, so the receiver can put packets back in order and ignore duplicates.
- Acknowledgements: the receiver tells the sender what it has received (“I have everything up to byte 48,000”).
- Retransmission: if no acknowledgement comes in time, the sender sends the data again. A lost packet doesn’t lose data; it only causes a delay.
- Flow control: the receiver says how much more it can take (the window), so a fast server doesn’t overwhelm a slow phone.
- Congestion control: the sender starts slowly and speeds up while things go well, and slows down when packets get lost, so it doesn’t flood a busy network. This is called slow start.
When one side is done, it sends FIN (“I’m finished”), and the other side acknowledges and closes its half. A RST (reset) instead ends a connection abruptly: that’s what you get when you connect to a port where nothing is listening.
- Handshake cost: 1 RTT for TCP, plus 1 RTT for TLS 1.3 (2 for TLS 1.2), before the first request byte. Connection reuse (keep-alive, pooling, HTTP/2 multiplexing) removes both. TCP Fast Open (data in the SYN) exists but is rarely usable through middleboxes; QUIC folds transport and TLS into 1 RTT, 0-RTT on resumption.
- Reliability machinery: cumulative ACKs plus SACK (selective acknowledgements), fast retransmit after three duplicate ACKs, retransmission timeouts with exponential backoff (the initial timeout is 1 s; repeated SYN loss turns into seconds of delay).
- Flow control: the receive window (scaled up to 1 GB with window scaling). Throughput is capped by window / RTT: a 64 KB window over 100 ms RTT is about 5 Mbit/s whatever the link speed. Buffer sizes should cover the bandwidth-delay product.
- Congestion control: slow start from an initial window of 10 segments (about 14 KB), doubling per RTT until loss or a threshold; then CUBIC (Linux, macOS, Windows default) or BBR (model-based, Google’s choice for YouTube and Cloud) in steady state. Idle connections can fall back to slow start (
tcp_slow_start_after_idle). - Head-of-line blocking: because delivery is in order, one lost packet holds back everything after it until the retransmission arrives, even data for unrelated HTTP/2 streams. That’s a main motivation for QUIC.
- Connection states: SYN_SENT, ESTABLISHED, FIN_WAIT, CLOSE_WAIT (the app hasn’t closed its socket: a leak in your code if they pile up), TIME_WAIT (the side that closed first, 60 s on Linux).
Predict the output
Nothing listens on port 9 of this laptop. 10.255.255.1 is an address where nobody answers at all. How does each attempt fail?
# -z: only connect, -G 3: give up after 3 seconds (Linux nc: -w 3)
nc -vz -G 3 127.0.0.1 9
nc -vz -G 3 10.255.255.1 443The laptop's OS answers a SYN to a closed port with a RST, so nc learns at once that nothing listens: 'Connection refused' in milliseconds. For the second address, the SYN disappears (no machine, or a firewall that drops packets silently), so the client keeps waiting and retrying until its timeout. Refused means 'reached the machine, wrong port or service down'; a timeout means 'packets aren't getting through', usually routing, a firewall or a security group.
# where the time goes in one HTTPS request: DNS, TCP handshake, TLS, first byte
curl -s -o /dev/null -w 'dns %{time_namelookup} tcp %{time_connect} tls %{time_appconnect} first byte %{time_starttransfer} total %{time_total}\n' https://example.com/
# the handshake itself: SYN, SYN-ACK, ACK (flags S, S., .)
sudo tcpdump -n -i en0 'tcp port 443 and tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0'
# connection states on this machine
netstat -an -p tcp | awk '{print $6}' | sort | uniq -c # Linux: ss -tan | awk ...Worked example: a small request over TCP
An app sends a 300-byte request and gets a 3,000-byte response, over a connection with a 50 ms round trip.
- Handshake. SYN, SYN-ACK, ACK: 50 ms. Nothing useful has been sent yet.
- Request. The client sends the 300 bytes, numbered 1 to 300, in one packet.
- Response. The server acknowledges the request and sends 3,000 bytes in three packets (each carries at most about 1,460 bytes). They are numbered so the client knows their order.
- A packet is lost. The second packet is dropped by a busy router. The client receives packets 1 and 3 and keeps telling the server “I have everything up to the end of packet 1”.
- Retransmission. The server notices the repeated acknowledgement (or its timer runs out) and sends packet 2 again.
- Delivery. Only now does the client’s TCP pass the response to the app, all 3,000 bytes in order. The app never knew a packet was lost; it just got the response later.
- Close. When the app is done, each side sends FIN and acknowledges the other’s. Usually, though, apps keep the connection open for the next request, so they don’t pay for the handshake again.
Deep diveWhy latency, not bandwidth, decides how fast a page loadsInterview favorite
“Users on a 100 Mbit/s mobile connection say the app is slow. How can that be?” Work out a cold fetch of a 100 KB response on a 100 ms RTT:
- DNS lookup, if not cached: up to 1 RTT.
- TCP handshake: 1 RTT.
- TLS 1.3 handshake: 1 RTT.
- Request and the first window of response: slow start allows about 10 segments, roughly 14 KB, in the first data round trip.
- The window doubles each round trip: 14 KB, then 29 KB, then 58 KB. After three data round trips about 100 KB has arrived.
That’s 5 to 6 round trips, 500 to 600 ms, and at 100 Mbit/s the bytes themselves would take 8 ms. Doubling the bandwidth changes almost nothing; halving the RTT halves the time.
What actually helps:
- Reuse connections (keep-alive, HTTP/2, a single client instance), so steps 1 to 3 happen once.
- Move servers closer: CDNs and edge termination cut the RTT for handshakes even when the origin is far away.
- Send less in the critical path: the first 14 KB of a response matter most; compress, and don’t make the first screen wait for several sequential requests (each one costs a full round trip).
- Newer protocols: TLS 1.3 (1 RTT instead of 2), session resumption and 0-RTT, HTTP/3 over QUIC (transport and TLS together), BBR congestion control on lossy links.
The same arithmetic explains why chatty APIs (ten sequential calls to render one screen) feel slow on mobile and fine in the office.
- Handshake 1 RTT, TLS 1.3 another; reuse connections. Refused = RST (reachable, nothing listening); timeout = packets dropped (firewall, routing).
- Sequence numbers, SACK, fast retransmit, RTO backoff; throughput ≤ window / RTT.
- Slow start from about 14 KB, doubling per RTT; short transfers are RTT-bound. CUBIC vs BBR.
- In-order delivery causes head-of-line blocking (HTTP/2 over TCP); QUIC avoids it.
- CLOSE_WAIT piling up = your code isn’t closing sockets.
curl -s -o /dev/null -w 'tcp %{time_connect} tls %{time_appconnect} ttfb %{time_starttransfer}\n' https://host/
nc -vz -G 3 host 5432 # refused vs timed out
ss -tan state close-wait # leaked sockets (Linux)Check this part
What are the three messages of the TCP handshake?
A TCP packet is lost on the way. What does the app see?
Connecting to a database fails with a timeout, not "connection refused". What does that suggest?
A 100 KB response on a fresh connection with 100 ms RTT takes about 500 ms even on a fast link. Main reason?