Command Palette

Search for a command to run...

Hectal
PHASE 2Intermediate ~7 min· topic 2 of 4

Topic 2.2

The TCP Handshake and Teardown

In one line

TCP opens every connection with a three-way handshake (SYN, SYN-ACK, ACK) and closes it with FIN/ACK exchanges or an abrupt RST; each costs round trips, which is why connection reuse matters so much.

0/4 · 0%

Think of it like this

A phone call. 'Hello, can you hear me?' (SYN). 'Yes, I can hear you, can you hear me?' (SYN-ACK). 'Yes!' (ACK). Only then do you start talking. Hanging up politely is 'bye' / 'bye' (FIN, FIN).

Key ideas

  1. 01

    THREE-WAY HANDSHAKE: the client sends SYN with an initial sequence number; the server replies SYN-ACK acknowledging it and sending its own; the client replies ACK. After one full round trip, data can flow. Add TLS on top and a new HTTPS connection costs 2–3 round trips before the first byte of the request.

  2. 02

    GRACEFUL CLOSE: each side sends FIN when it has finished sending and ACKs the other's FIN. Either side can close first; the side that closes first ends up in TIME_WAIT (Topic 2.3).

  3. 03

    RST (reset) aborts a connection immediately. You'll see it as 'connection reset by peer'. Causes: nothing is listening on that port (connection refused), a firewall or load balancer killing an idle connection, or an application crashing mid-request.

  4. 04

    'Connection refused' (an RST came back: host reachable, nothing listening) vs 'connection timed out' (no answer at all: packets dropped by a firewall or security group, or a routing problem). Telling these apart instantly narrows the search, as in the AWS course's security-group debugging.

Code & diagrams

TcpLifecyclediagram
Rendering diagram…
refused-vs-timeout.shbash
nc -vz 127.0.0.1 9999          # nothing listening → "Connection refused" (instant)
nc -vz -w 5 10.255.255.1 80     # blackholed → times out after 5 s
sudo tcpdump -nn -i any 'tcp[tcpflags] & (tcp-syn|tcp-rst) != 0'   # watch SYNs and RSTs live

Explain it without notes

01

Why does reusing connections (HTTP keep-alive, connection pools) make such a big latency difference, especially across regions?

02

Your app reports 'connection timed out' connecting to Postgres. Name two likely causes and one that's unlikely.

Practice

01

Capture a curl https://example.com with tcpdump -nn host example.com and identify the SYN, SYN-ACK, ACK, and the first FIN.

Trade-offs

  • ↔

    Long-lived connections save handshakes but consume resources on both ends and through middleboxes (NAT and load balancer idle timeouts can silently kill them). Use keep-alive and pools with idle timeouts shorter than the middleboxes'.

Done when you can

  • I can draw the three-way handshake and the FIN teardown.

  • I know the difference between RST (refused/reset) and timeout.

  • I can spot handshake packets in tcpdump output.