← Back to Home

🔌 TCP/IP from First Principles

Handshakes, sequence numbers, flow control, congestion control, bufferbloat and the 40 ms Nagle stall, each checked against real packet captures from a two-namespace Linux lab.

Almost every request you send, whether HTTP/1.1, HTTP/2, a database query or a gRPC call, rides on TCP. Most of the time it's invisible. Then a service is slow for no obvious reason, a connection hangs for two minutes, or a fast link delivers a fraction of its bandwidth, and the answer is in TCP.

This article builds TCP up from what IP gives you, and checks each idea against real packets. Every capture and number below comes from a small lab on Linux 6.18: two network namespaces joined by a virtual cable, with tc netem adding delay and loss, a 100 Mbit/s bottleneck, and a 60-line Python packet sniffer. The last section shows how to build it yourself, without root.

It continues from What Happens When You Type a URL, which covered the handshake in passing. Here we slow down.

What IP Gives You, and What TCP Adds

IP moves packets between addresses, and that's all it promises. A packet can be:

IP doesn't tell the sender about any of this. TCP turns that into a reliable, ordered byte stream between two programs. To do that it needs:

Problem TCP mechanism
Which program gets this packet? Ports (source and destination)
Are both sides ready? Three-way handshake
Lost or reordered data Sequence numbers, acknowledgements, retransmission
Receiver can't keep up Flow control (the receive window)
Network can't keep up Congestion control (the congestion window)
Corrupted data Checksum
Clean shutdown FIN exchange and TIME_WAIT

Hold onto the two windows in particular. Flow control protects the receiver; congestion control protects the network. The sender may have in flight at most the smaller of the two.

Anatomy of a Segment

A TCP segment is a header (20 bytes, plus up to 40 bytes of options) followed by data:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------------------------------+-------------------------------+
|          Source Port          |       Destination Port        |
+-------------------------------+-------------------------------+
|                        Sequence Number                        |
+---------------------------------------------------------------+
|                    Acknowledgment Number                      |
+-------+-------+---------------+-------------------------------+
| Offset| Rsvd  |C E U A P R S F|            Window             |
+-------+-------+---------------+-------------------------------+
|           Checksum            |        Urgent Pointer         |
+-------------------------------+-------------------------------+
|                    Options (0 to 40 bytes)                    |
+---------------------------------------------------------------+

The sniffer used in this article decodes exactly these fields. It prints sequence numbers relative to each side's first one, as Wireshark does, because the real starting values are random 32-bit numbers (RFC 6528) chosen so that an attacker can't guess them.

The Three-Way Handshake, Captured

A client connects, sends an 18-byte HTTP request, gets a 24-byte response, and both sides close. The path has 10 ms of one-way delay:

     0.0 ms  client→server  SYN      seq=0      ack=0      win=65495  len=0     mss 65495 sackOK TS wscale 10
    10.4 ms  server→client  SYN+ACK  seq=0      ack=1      win=65483  len=0     mss 65495 sackOK TS wscale 10
    20.9 ms  client→server  ACK      seq=1      ack=1      win=64     len=0     TS
    21.0 ms  client→server  ACK+PSH  seq=1      ack=1      win=64     len=18    TS
    32.0 ms  server→client  ACK      seq=1      ack=19     win=64     len=0     TS
    32.0 ms  server→client  ACK+PSH  seq=1      ack=19     win=64     len=24    TS
    32.1 ms  server→client  ACK+FIN  seq=25     ack=19     win=64     len=0     TS
    42.6 ms  client→server  ACK      seq=19     ack=25     win=64     len=0     TS
    85.8 ms  client→server  ACK      seq=19     ack=26     win=64     len=0     TS
    95.9 ms  client→server  ACK+FIN  seq=19     ack=26     win=64     len=0     TS
   106.5 ms  server→client  ACK      seq=26     ack=20     win=64     len=0     TS

Read it line by line:

  1. SYN. The client picks its initial sequence number and proposes options.
  2. SYN+ACK. The server picks its own sequence number and acknowledges the client's SYN with ack=1. A SYN uses up one sequence number even though it carries no data.
  3. ACK. The client acknowledges the server's SYN. The connection is open after one round-trip. The client sends its request in the very next packet (0.1 ms later); the server can't send anything useful until that request arrives.
  4. Data. The request is 18 bytes, so the server answers ack=19: "I have bytes 1 to 18, send 19 next".
  5. Response and FIN. The server sends 24 bytes (sequence 1 to 24), then FIN at sequence 25. Like SYN, FIN uses one sequence number, so the client's acknowledgement of it is ack=26.
  6. Client FIN. When the client's application calls close(), it sends its own FIN; the server acknowledges it with ack=20.

Notice win=64 after the handshake. That isn't 64 bytes: both sides agreed on wscale 10, so the real window is 64 × 2^10 = 65,536 bytes. Tools that miss the handshake can't know the scale and show nonsense windows, which is a common trap when you start a capture mid-connection.

The four options in the SYN are worth knowing:

Option What it does
mss Maximum segment size: the largest payload this side can receive. 65495 here because loopback has a 64 KB MTU; on Ethernet it's 1460 (1500 minus 20 bytes IP minus 20 bytes TCP).
sackOK Selective acknowledgements allowed: the receiver can say "I'm missing 1000 to 1999, but I have 2000 to 5000", so the sender resends only the hole.
TS Timestamps: used to measure RTT on every ACK and to reject very old duplicate segments. They take 12 bytes, which is why the usable payload on Ethernet is 1448, not 1460.
wscale Window scale: the shift count applied to the 16-bit window field, up to 14 (a 1 GB window).

Options only count if both sides send them in the handshake. A middlebox that strips them silently costs you SACK and large windows for the whole connection.

Closing, and the TIME_WAIT Question

TCP is full duplex, so each direction closes separately: each side sends a FIN and acknowledges the other's. The side that closes first ends up in TIME_WAIT for a while. Three short connections opened and closed by a client leave this behind:

State     Recv-Q Send-Q Local Address:Port  Peer Address:PortProcess
TIME-WAIT 0      0           10.0.0.1:42248     10.0.0.2:9100
TIME-WAIT 0      0           10.0.0.1:42262     10.0.0.2:9100
TIME-WAIT 0      0           10.0.0.1:42278     10.0.0.2:9100
TIME-WAIT 0      0           10.0.0.1:42294     10.0.0.2:9100

TIME_WAIT exists for two reasons. First, if the final ACK is lost, the other side resends its FIN, and someone must still be there to answer. Second, it stops a delayed segment from the old connection being accepted by a new connection that reuses the same four-tuple (both addresses and both ports).

On Linux TIME_WAIT lasts a fixed 60 seconds, set in the kernel source. A common myth is that net.ipv4.tcp_fin_timeout (also 60 here) controls it. It doesn't: that setting is the timeout for FIN_WAIT_2, a different state.

Why should you care? A client that opens a new connection per request to the same server uses a new local port each time, and each lingers for 60 seconds. The default port range here is 32768 60999, about 28,000 ports, so more than roughly 470 new connections per second to one destination runs out of ports. The errors look like EADDRNOTAVAIL or "cannot assign requested address". The fix is almost always connection reuse: HTTP keep-alive, a connection pool in your database driver, or HTTP/2. net.ipv4.tcp_tw_reuse (default 2 on current kernels, which means loopback only) lets new outgoing connections reuse TIME_WAIT ports safely using timestamps. Don't reach for it first.

When Nobody Answers: SYN Retries

"Connection refused" and "connection timed out" are very different failures:

connect to 127.0.0.1:9999 -> ConnectionRefusedError: Connection refused after 0.000s

Refused means the host is up and replied with RST: nothing is listening on that port. It's instant.

Timed out means nothing came back at all: a firewall dropping packets, a host that's down, a routing problem. The kernel keeps resending the SYN. Here every reply from the server is dropped, and the server side records each SYN as it arrives, with the default settings on this kernel (tcp_syn_retries=6, tcp_syn_linear_timeouts=4):

  SYN #1 arrived at   0.00s
  SYN #2 arrived at   1.01s
  SYN #3 arrived at   2.03s
  SYN #4 arrived at   3.06s
  SYN #5 arrived at   4.08s
  SYN #6 arrived at   5.10s
  SYN #7 arrived at   7.12s
  SYN #8 arrived at  11.22s
  SYN #9 arrived at  19.41s
  SYN #10 arrived at  35.54s
  SYN #11 arrived at  68.56s
connect to 10.0.0.2:9998 -> TimeoutError: Connection timed out after 134.095s

The classic schedule doubles the wait every time: 1, 2, 4, 8, 16, 32 s. Linux 6.5 added tcp_syn_linear_timeouts, which retries every second for the first few attempts and only then starts doubling. That reconnects faster after a brief blip, but the total wait is still more than two minutes: 11 SYNs and 134 seconds before connect() gave up.

The lesson for application code: always set a connect timeout. A default library call that blocks for over two minutes turns one unreachable dependency into a pile of stuck threads. Set it to a few times the normal connection time, separately from the read timeout. Idempotency, Retries, Timeouts and Backoff goes deeper.

Flow Control: The Receiver's Window

Every ACK carries the receiver's window: how much more it can buffer. If the application stops reading, the buffer fills and the window shrinks to zero. Here the receiving application sleeps for 1.5 seconds before reading, with a small 32 KB receive buffer:

     5.2 ms  server→client  SYN+ACK  seq=0      ack=1      win=31856  len=0     mss 1460 sackOK TS wscale 0
    15.8 ms  server→client  ACK      seq=1      ack=6993   win=40544  len=0     TS
    26.1 ms  server→client  ACK      seq=1      ack=25817  win=24616  len=0     TS
    68.3 ms  server→client  ACK      seq=1      ack=50433  win=5792   len=0     TS
   117.5 ms  server→client  ACK      seq=1      ack=56225  win=0      len=0     TS sack 1 blocks
   344.7 ms  client→server  ACK      seq=56224  ack=1      win=63     len=0     TS
   350.0 ms  server→client  ACK      seq=1      ack=56225  win=0      len=0     TS
   819.8 ms  client→server  ACK      seq=56224  ack=1      win=63     len=0     TS
  1526.8 ms  server→client  ACK      seq=1      ack=56225  win=40544  len=0     TS

(The server used wscale 0 because of its small buffer, so these windows are plain bytes.)

Meanwhile the sending application didn't notice anything: its send() calls succeeded because the kernel's send buffer absorbed the data. Back-pressure travels backwards through buffers: application, socket buffer, TCP window, sender's buffer, sending application. When the sender's buffer fills too, send() blocks. That's the same mechanism as the producer-consumer backpressure problem, built into the protocol.

A window that sits at zero in a capture is a strong clue: the problem is the receiving application, not the network.

Congestion Control: Probing an Unknown Network

The receiver's window says what the receiver can take. Nothing tells the sender what the network can take: the bottleneck might be a home Wi-Fi link, a congested peering point or a busy server's NIC, and it changes from second to second. So TCP keeps a second limit, the congestion window (cwnd), and adjusts it from what it observes.

The classic algorithm (Reno) has three rules:

This additive-increase, multiplicative-decrease (AIMD) loop produces the famous sawtooth, and it's what made the internet stable after the congestion collapses of 1986.

Modern Linux uses CUBIC by default. It's still loss-based, but after a loss it grows cwnd as a cubic function of the time since that loss: fast at first, flattening as it approaches the window where loss happened last time, then probing beyond it. That fills long, fast paths much sooner than adding one segment per round-trip.

Try both. The path holds 40 segments in flight (the bandwidth-delay product, BDP); the router buffer holds a few more; anything beyond that is dropped:

Press Play. cwnd doubles every round-trip in slow start until the queue overflows, then settles into its loss-and-recover cycle. Change the buffer: with no buffer the link sits partly idle after each cut; with a big one the link stays full but every packet waits in the queue.

Things to try:

There's a different family too. BBR (from Google) doesn't treat loss as the signal: it measures the bottleneck bandwidth and minimum RTT and paces packets to match, keeping queues short. It does well on lossy long-distance links, but it isn't always fair to CUBIC flows sharing a bottleneck. On Linux you select it with net.ipv4.tcp_congestion_control=bbr if the tcp_bbr module is available; this lab's kernel only offers reno and cubic.

Loss Is Expensive

How much does random packet loss hurt? Here's the lab path at 50 ms RTT, a 100 Mbit/s bottleneck and a 50 ms buffer, with packets dropped at random on the data path. Each row is the median of three 8 MB transfers:

Random loss Reno CUBIC Retransmits (Reno / CUBIC) Mathis estimate for Reno
0% 67.4 Mbit/s 68.0 Mbit/s 870 / 0 (no loss)
0.1% 67.4 Mbit/s 68.3 Mbit/s 858 / 10 8.6 Mbit/s
0.5% 5.7 Mbit/s 9.5 Mbit/s 28 / 18 3.8 Mbit/s
1% 3.9 Mbit/s 4.1 Mbit/s 59 / 59 2.7 Mbit/s
2% 3.8 Mbit/s 2.7 Mbit/s 123 / 128 1.9 Mbit/s

(An 8 MB transfer at 0.1% loss sees only a handful of random drops, so it never reaches the steady state the formula describes. Single runs vary by a factor of two or so at high loss; the pattern holds across runs.)

Two things stand out.

First, a little random loss is a disaster for loss-based TCP. Half a percent of drops cuts throughput by seven to twelve times, because every loss looks like congestion and halves the window. A classic approximation (Mathis et al., 1997) says steady-state Reno throughput is about MSS / RTT × 1.22 / √p, where p is the loss rate. At 1% loss and 50 ms that's about 2.8 Mbit/s no matter how fast the link is. The measured values beat it a little because SACK and the initial burst help, but they follow the shape. Real networks rarely lose packets at random, except Wi-Fi and mobile links, which is why those links retry at the link layer.

Second, look at Reno with zero random loss: hundreds of retransmits. Slow start doubled cwnd straight past what the path and buffer could hold, and a whole window of packets was dropped at once. CUBIC on Linux uses HyStart, which watches for RTT starting to rise during slow start and leaves it before the queue overflows. Same link, almost no retransmits.

Notice also that RTT is in the formula. Double the distance and you halve the throughput a loss-limited flow gets. That's one reason CDNs terminate TCP close to users.

Bufferbloat: When Queues Become Latency

Congestion control fills the bottleneck queue until it overflows, so the size of that queue becomes extra latency. Same path, no random loss, CUBIC, with the bottleneck buffer varied:

buffer    5ms: cubic  24MB   6.92s  goodput=  29.1 Mbit/s  retrans=46    median_srtt=  50.5ms
buffer   50ms: cubic  24MB   2.38s  goodput=  84.4 Mbit/s  retrans=43    median_srtt=  76.8ms
buffer  200ms: cubic  24MB   2.39s  goodput=  84.2 Mbit/s  retrans=0     median_srtt=  94.3ms
buffer 1000ms: cubic  24MB   2.39s  goodput=  84.2 Mbit/s  retrans=0     median_srtt=  94.2ms

Anyone else sharing that link, such as a video call or an SSH session, now sees 94 ms instead of 50. On home routers with oversized buffers this reaches seconds: the reason a large upload makes your whole household's browsing feel sluggish.

You can see it live with ss -ti, which prints the kernel's TCP state for each socket. This is the sender in the middle of a transfer:

  ESTAB 0      3732832      10.0.0.1:42248     10.0.0.2:9100
  cubic wscale:10,10 rto:296 rtt:94.238/1.028 mss:1448 pmtu:1500 rcvmss:536 advmss:1448 cwnd:819 ssthresh:514 bytes_sent:10768888 bytes_acked:9587321 segs_out:7440 segs_in:1036 data_segs_out:7438 send 100673783bps lastrcv:1080 pacing_rate 120807896bps delivery_rate 95603848bps delivered:6623 busy:1080ms rwnd_limited:48ms(4.4%) unacked:816 rcv_space:14480 rcv_ssthresh:64088 notsent:2551264 minrtt:50.068 snd_wnd:3689472

The fixes are active queue management in routers (CoDel, fq_codel, CAKE, now default on many Linux systems and good home routers), pacing at the sender, and delay-based algorithms like BBR. For your own services, watch rtt against minrtt.

Nagle and Delayed ACKs: The 40 ms Mystery

Two well-meant optimisations collide in a classic way:

Now write a request in two send() calls (say, header then body) and wait for the response. The first segment goes out; Nagle holds the second until the first is acknowledged; the receiver delays that ACK because it's waiting for the rest of the request. Both sides wait for a timer. Measured on a 10 ms RTT path, 50 requests each:

TCP_NODELAY=0  median=64.0ms  p90=65.1ms  min=20.2ms
TCP_NODELAY=1  median=10.7ms  p90=10.9ms  min=10.3ms

Six times slower for no reason. (The 20 ms minimum is the first request: Linux starts new connections in quick-ACK mode.) Two fixes:

  1. Set TCP_NODELAY on latency-sensitive sockets. Most HTTP clients, database drivers and RPC frameworks already do.
  2. Write the whole message in one call: build the buffer first, or use sendmsg/writev to send several buffers at once. This is better anyway, as it means fewer system calls and fewer packets.

If you ever see latencies stuck near 40 ms or 200 ms (another common delayed-ACK maximum), suspect this first.

Head-of-Line Blocking

TCP delivers one ordered byte stream. If segment 5 is lost, segments 6 to 50 may have arrived, but the application can't read any of them until segment 5 is retransmitted, at least one more round-trip.

That's fine for one stream, and harmful when you multiplex. HTTP/2 sends many requests over one TCP connection; one lost packet stalls all of them, even those whose data arrived intact. At 2% loss, HTTP/2 can do worse than HTTP/1.1 with six separate connections.

This is the main reason HTTP/3 runs over QUIC on UDP: QUIC keeps a separate ordering per stream, so a loss stalls only the stream it belongs to. QUIC also merges the transport and TLS handshakes into one round-trip and keeps connections alive across network changes (Wi-Fi to mobile). It reimplements in user space everything this article has described: sequence numbers, acknowledgements, flow control and congestion control.

Debugging Toolkit

Most TCP problems fall into a few patterns. Each has a signature:

Symptom Likely cause Check
Instant "connection refused" Nothing listening, or a firewall that rejects ss -ltn on the server
Connect hangs, then times out Packets dropped: firewall, security group, routing, host down Capture on both ends; SYNs leaving but no SYN-ACK back
"Cannot assign requested address" Ephemeral ports exhausted by TIME_WAIT Count ss -tan state time-wait; use connection pooling
Throughput far below link speed Loss, high RTT, or a small window ss -ti: retrans, rtt, cwnd, rwnd_limited
Latency high only under load Bufferbloat rtt vs minrtt in ss -ti; ping during a transfer
Window drops to 0 in a capture Receiving application isn't reading fast enough Profile the receiver, not the network
Requests stuck near 40 ms or 200 ms Nagle plus delayed ACK Set TCP_NODELAY; write each message in one call
Connections reset mid-stream Idle timeout in a load balancer or NAT, or a crashed peer Compare keep-alive settings with idle timeouts along the path

Commands worth knowing:

ss -tin dst 10.0.0.2                     # per-socket RTT, cwnd, retransmits, delivery rate
ss -tan state time-wait | wc -l          # TIME_WAIT count
nstat -az | grep -E 'TcpRetransSegs|TcpExtTCPTimeouts|TcpExtListenOverflows'
tcpdump -ni eth0 'tcp port 443 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)'
sysctl net.ipv4.tcp_congestion_control net.ipv4.tcp_syn_retries

TcpExtListenOverflows deserves a mention: it counts connections dropped because a server's accept queue was full. The application was too slow to call accept(), and clients see it as SYN retries. It's a classic cause of mysterious one-second (or three-second) connect delays.

Build the Lab Yourself

Everything above runs as an ordinary user on Linux, using a user namespace for fake root and a mount namespace for ip netns:

# net2.sh: two namespaces joined by a veth pair. Run with: unshare -rnm sh run.sh
set -e
mount -t tmpfs none /run
mkdir -p /run/netns
ip netns add srv
ip link add vc type veth peer name vs
ip link set vs netns srv
ip addr add 10.0.0.1/24 dev vc; ip link set vc up; ip link set lo up
ip netns exec srv ip addr add 10.0.0.2/24 dev vs
ip netns exec srv ip link set vs up
ip netns exec srv ip link set lo up
# netem(delay, loss) -> tbf(bottleneck rate, queue) on the data direction; plain delay on the ACK direction
shape() {  # $1=loss% $2=queue in ms of buffering $3=extra netem args
  tc qdisc replace dev vc root handle 1: netem delay 25ms loss ${1}% limit 1000000 $3
  tc qdisc replace dev vc parent 1:1 handle 10: tbf rate 100mbit burst 20kb latency ${2}ms
  ip netns exec srv tc qdisc replace dev vs root netem delay 25ms limit 1000000
}

Two lessons from building it:

info = struct.unpack("8B24I", sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_INFO, 104))
u = info[8:]
rtt_ms, cwnd, total_retrans = u[15] / 1000, u[18], u[23]

The sniffer opens an AF_PACKET raw socket (allowed inside the user namespace), skips outgoing copies, and decodes the IP and TCP headers with struct.unpack("!HHIIBBH", tcp[:16]). That's 60 lines, and it shows everything you'd see in tcpdump for this purpose.

Key Takeaways

Copied to clipboard!