Chapters

TCP: the reliable backbone

Almost everything Kadé does that must not go wrong runs over TCP: every order sent to kade-api, every query to kade-db, every call to PayGate. This chapter covers what TCP promises, how a connection opens and closes, and the states you will see when debugging.

Layers, routing and transport · chapter 16 of 34 · 7 min read

What TCP is

TCP (Transmission Control Protocol) gives reliable, ordered, error-checked delivery of a stream of bytes between two applications. If something is lost, TCP resends it. If pieces arrive out of order, TCP puts them back in order. Its unit of data is the segment.

TCP connection in KadéServer portWhat breaks if bytes go missing
Laptop / app → kade-api443An order arrives half-written
kade-api → kade-db5432A payment is saved without its order lines
kade-api → PayGate443A charge amount changes
You → kade-api (SSH)22Your command runs wrong

Connection-oriented

Unlike UDP (chapter 14), TCP is connection-oriented: before any data is sent, both sides set up a connection and agree on starting values. Only then does data flow. This setup is what makes tracking and reliability possible.

A "connection" is not a wire or a reserved path. Routers in between know nothing about it (chapter 11: they never read the TCP header). It is only state kept on the two ends:

Who192.168.1.23:52814 ↔ 34.87.120.15:443 the four values from chapter 1, plus the protocol
Where each side is in the byte countsequence and acknowledgement numbers (chapter 17)
Data waitinga send buffer (sent but not yet confirmed) and a receive buffer (arrived but not yet read by the app)
Timers and estimatesround-trip time, retransmit timer, congestion window (section 7)
State nameESTABLISHED, TIME-WAIT … (section 8)

Opening: the three-way handshake

Connections open with a three-way handshake. Here, your laptop opens a connection to kade-api:

Laptop :52814kade-api :443kade-api's Node app is waitingLISTENSYN · SEQ = xSYN-SENTSYN-ACK · SEQ = y, ACK = x + 1SYN-RECEIVEDACK · SEQ = x + 1, ACK = y + 1ESTABLISHEDESTABLISHEDdata: GET /profile …the request can finally go
MessageDirectionMeaning
SYNlaptop → kade-api"I want to talk. My starting sequence number is x."
SYN-ACKkade-api → laptop"OK. My starting number is y, and I acknowledge x."
ACKlaptop → kade-api"I acknowledge y." Connection established.
The SYN and SYN-ACK also carry settings for the connection: the largest segment each side accepts (MSS), and options like window scaling and selective ACKs. Chapter 18 opens them.

What it costs: the handshake takes one full round trip before the first byte of data. From home to kade-api that is about 41 ms (chapter 13). HTTPS then adds TLS, usually one more round trip. So the first request on a new connection waits about 80 ms before the request itself is even sent. This is why browsers and HTTP clients reuse connections (keep-alive) instead of opening a new one for every request.

Why three messages, not two

Three is the minimum for both sides to know that both directions work:

#AfterLaptop knowskade-api knows
1SYN arrivesnothing yetlaptop → kade-api works
2SYN-ACK arrivesboth directions workstill unsure its reply got through
3ACK arrivesboth directions workboth directions work
With only two messages, kade-api would never learn whether its reply arrived. It would also have no way to tell a fresh SYN from an old, delayed one still wandering the network. The third message confirms the laptop really wants this connection, with these numbers.

When the handshake fails: refused vs timed out

The two most common connection errors come from the handshake, and they mean very different things:

"Connection refused"

The machine answered the SYN with RST (reset): "nobody is listening on that port". It arrives in about one round trip.

Kadé: the Node app on kade-api crashed. The VM is up, but nothing listens on 443.

"Connection timed out"

No answer at all. The SYN was dropped. The client retries with growing gaps (about 1 s, 2 s, 4 s …) and gives up after tens of seconds.

Kadé: no GCP firewall rule allows port 443, or the VM is off.

Closing: FIN, ACK, FIN, ACK

Closing takes four messages, because each side shuts down its own direction separately. One side sends FIN ("I have nothing more to send"), the other ACKs it. Later the other side sends its own FIN, which gets ACKed. In between, data can still flow the other way: this is a half-close.

Laptopkade-apiboth sides ESTABLISHED; the laptop is doneESTABLISHEDESTABLISHEDFIN · "I have nothing more to send"FIN-WAIT-1ACKFIN-WAIT-2CLOSE-WAITdata can still flow this way (half-close)FIN · "me too"LAST-ACKACKTIME-WAITCLOSEDthe laptop waits 60 s, then forgets the connectionCLOSED
  • Often only three packets. If kade-api has nothing left to send, it combines its ACK and FIN into one segment.
  • TIME-WAIT. The side that closed first waits a while (60 seconds on Linux) before forgetting the connection, in case its last ACK was lost and the other side resends its FIN. Also, late packets from this connection cannot be mistaken for a new one on the same ports.
  • RST is the abrupt close. No goodbye: "this connection is gone". Apps see it as connection reset by peer. Chapter 10's NAT timeout is a classic cause: kade-api sends on an idle pooled connection whose NAT row was deleted, and gets a reset.

What TCP gives

#PromiseWhat it meansHowDetails in
1ReliableLost segments are detected and resentACKs, timers, retransmissionChapter 17
2In orderThe app reads bytes in the order they were sentSequence numbers, a reassembly bufferChapter 17
3Error-checkedDamaged segments are thrown away and resentChecksum with pseudo-header, like UDPChapter 18
4Flow controlNever overwhelms a slow receiverThe receiver's window: "room for N more bytes"Chapter 18
5Congestion controlBacks off when the network is busyA congestion window that grows and shrinksBelow

Flow control and congestion control sound alike but protect different things. Flow control protects the receiver: kade-db tells kade-api how much buffer it has left. Congestion control protects the network in between: the sender does not know how much the path can carry, so it probes. It starts small, roughly doubles its sending amount every round trip (slow start), and cuts back sharply when a loss shows the network is full:

amount in flight (congestion window)time (round trips) →what the network can really carryslow start: doubles each round triploss → cutthen grows slowly

The sawtooth is TCP sharing the network fairly with everyone else. It is also why a brand-new connection starts slow: another reason to reuse connections.

Wide by design - scroll it sideways.

TCP states

A TCP connection moves through named states. Step through one full connection, from the Node app starting to listen, to the last goodbye:

step 1 of 12

Laptop: CLOSEDkade-api: LISTEN

kade-api's Node app opens a socket and listens. The laptop has no connection yet.

Laptopkade-apithe Node app starts listening on 443CLOSEDLISTEN

You will see these names in ss and netstat. What a pile of one state usually means:

#StateMeaningMany of them usually means
1LISTENA server waiting for connectionsNormal: one per listening port (Node on 443, PostgreSQL on 5432)
2SYN-SENTClient sent SYN, waitingStuck here = SYNs being dropped: firewall or wrong IP
3SYN-RECEIVEDServer got SYN, sent SYN-ACKThousands = a SYN flood attack (section 9)
4ESTABLISHEDOpen, data can flowThe healthy state. Count = open connections.
5CLOSE-WAITOther side closed; waiting for our app to closeA bug in our app: it never closes sockets (a connection leak)
6FIN-WAIT-1/2, LAST-ACKClosing in progressNormally short-lived
7TIME-WAITClosed, waiting before forgettingMany short connections. Harmless in small numbers; in huge numbers it uses up ports (chapter 10). Fix: reuse connections.

SYN floods

Each SYN makes the server set aside memory and wait for the final ACK. An attacker can send huge numbers of SYNs from fake addresses (easy, since no handshake finishes) and never send the ACK. The server's queue fills and real users cannot connect. The standard defence is SYN cookies: the server stores nothing and instead encodes what it needs into its own starting sequence number, checking it when (and if) the ACK arrives. Linux turns this on automatically when under pressure. Load balancers in front of kade-api (a later chapter) absorb these floods before they reach the VM.

Summary

#IdeaIn one lineNew terms
1TCPReliable, ordered, error-checked byte stream; unit is a segmentTCP, segment
2ConnectionState on the two ends only; routers know nothingconnection-oriented
3OpeningSYN, SYN-ACK, ACK: one round trip before datathree-way handshake, keep-alive
4Why threeBoth sides confirm both directions
5FailuresRST = refused (no app); silence = timed out (firewall)RST
6ClosingFIN/ACK per direction; TIME-WAIT; RST is the abrupt wayhalf-close, TIME-WAIT
7PromisesReliable, ordered, checked, flow and congestion controlflow control, congestion control, slow start
8StatesLISTEN … ESTABLISHED … TIME-WAIT; CLOSE-WAIT piles = app bugTCP states
9AttackSYN floods; defended with SYN cookiesSYN flood, SYN cookies

Try it yourself

All TCP connections with their state

  • What to look for: LISTEN lines for servers, ESTABLISHED for open ones, some TIME-WAIT.
  • Runs on: Linux · macOS: netstat -an -p tcp
  • From section: 8. TCP states
ss -tan

Connections our app forgot to close

  • What to look for: Should be empty or tiny. A growing number is a leak.
  • Runs on: Linux, on kade-api
  • From section: 8. TCP states
ss -tan state close-wait

Just the handshake

nc -vz api.kade.lk 443

How long the handshake took

curl -o /dev/null -s -w 'tcp %{time_connect}s tls %{time_appconnect}s total %{time_total}s\n' https://example.com

Only opens, closes and resets

sudo tcpdump -n -i en0 'tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0'

Which programs listen on which TCP ports

  • What to look for: node on 3000 or 443, postgres on 5432.
  • From section: 8. TCP states
lsof -iTCP -sTCP:LISTEN -n -P

Spotted a mistake, or something unclear? Suggest an edit on GitHub