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 port | What breaks if bytes go missing |
|---|---|---|
| Laptop / app → kade-api | 443 | An order arrives half-written |
| kade-api → kade-db | 5432 | A payment is saved without its order lines |
| kade-api → PayGate | 443 | A charge amount changes |
| You → kade-api (SSH) | 22 | Your 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:
| Who | 192.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 count | sequence and acknowledgement numbers (chapter 17) |
| Data waiting | a send buffer (sent but not yet confirmed) and a receive buffer (arrived but not yet read by the app) |
| Timers and estimates | round-trip time, retransmit timer, congestion window (section 7) |
| State name | ESTABLISHED, 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:
| Message | Direction | Meaning |
|---|---|---|
| SYN | laptop → kade-api | "I want to talk. My starting sequence number is x." |
| SYN-ACK | kade-api → laptop | "OK. My starting number is y, and I acknowledge x." |
| ACK | laptop → kade-api | "I acknowledge y." Connection established. |
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:
| # | After | Laptop knows | kade-api knows |
|---|---|---|---|
| 1 | SYN arrives | nothing yet | laptop → kade-api works |
| 2 | SYN-ACK arrives | both directions work | still unsure its reply got through |
| 3 | ACK arrives | both directions work | both directions work |
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.
- 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
| # | Promise | What it means | How | Details in |
|---|---|---|---|---|
| 1 | Reliable | Lost segments are detected and resent | ACKs, timers, retransmission | Chapter 17 |
| 2 | In order | The app reads bytes in the order they were sent | Sequence numbers, a reassembly buffer | Chapter 17 |
| 3 | Error-checked | Damaged segments are thrown away and resent | Checksum with pseudo-header, like UDP | Chapter 18 |
| 4 | Flow control | Never overwhelms a slow receiver | The receiver's window: "room for N more bytes" | Chapter 18 |
| 5 | Congestion control | Backs off when the network is busy | A congestion window that grows and shrinks | Below |
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:
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:
Laptop: CLOSEDkade-api: LISTEN
kade-api's Node app opens a socket and listens. The laptop has no connection yet.
You will see these names in ss and netstat. What a pile of one state usually means:
| # | State | Meaning | Many of them usually means |
|---|---|---|---|
| 1 | LISTEN | A server waiting for connections | Normal: one per listening port (Node on 443, PostgreSQL on 5432) |
| 2 | SYN-SENT | Client sent SYN, waiting | Stuck here = SYNs being dropped: firewall or wrong IP |
| 3 | SYN-RECEIVED | Server got SYN, sent SYN-ACK | Thousands = a SYN flood attack (section 9) |
| 4 | ESTABLISHED | Open, data can flow | The healthy state. Count = open connections. |
| 5 | CLOSE-WAIT | Other side closed; waiting for our app to close | A bug in our app: it never closes sockets (a connection leak) |
| 6 | FIN-WAIT-1/2, LAST-ACK | Closing in progress | Normally short-lived |
| 7 | TIME-WAIT | Closed, waiting before forgetting | Many 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
| # | Idea | In one line | New terms |
|---|---|---|---|
| 1 | TCP | Reliable, ordered, error-checked byte stream; unit is a segment | TCP, segment |
| 2 | Connection | State on the two ends only; routers know nothing | connection-oriented |
| 3 | Opening | SYN, SYN-ACK, ACK: one round trip before data | three-way handshake, keep-alive |
| 4 | Why three | Both sides confirm both directions | |
| 5 | Failures | RST = refused (no app); silence = timed out (firewall) | RST |
| 6 | Closing | FIN/ACK per direction; TIME-WAIT; RST is the abrupt way | half-close, TIME-WAIT |
| 7 | Promises | Reliable, ordered, checked, flow and congestion control | flow control, congestion control, slow start |
| 8 | States | LISTEN … ESTABLISHED … TIME-WAIT; CLOSE-WAIT piles = app bug | TCP states |
| 9 | Attack | SYN floods; defended with SYN cookies | SYN 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 -tanConnections 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-waitJust the handshake
- What to look for: "succeeded", "refused" (RST) or a long wait then "timed out".
- From section: 5. When the handshake fails: refused vs timed out
nc -vz api.kade.lk 443How long the handshake took
- What to look for:
tcp≈ one round trip;tlsadds about another. - From section: 3. Opening: the three-way handshake
curl -o /dev/null -s -w 'tcp %{time_connect}s tls %{time_appconnect}s total %{time_total}s\n' https://example.comOnly opens, closes and resets
- What to look for:
[S]SYN,[S.]SYN-ACK,[F.]FIN,[R]RST. - From section: 3. Opening: the three-way handshake
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