TCP/IP and the network stack
Learn how bytes really move between two machines, so you can read network errors and stop paying for handshakes you do not need.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
Meera's team runs an order service on AWS. Its servers sit in a private subnet. To call a partner's payment API on the internet, every request goes through a NAT gateway. The HTTP client keeps a pool of open connections, so most calls skip the handshake.
Every morning, the first few payment calls fail with connection reset by peer. A retry works. During the day, all is fine. The team blames the partner, and the partner sees nothing in its logs.
An engineer leaves tcpdump running on one server overnight. In the morning, the failed requests went out on connections that had been silent for over six minutes. Each one got an RST straight back. AWS documents that a NAT gateway times out a connection that is idle for 350 seconds or more. If you then send on it, the gateway answers with a reset (RST), not a clean close (FIN) 11.
The partner never saw those calls because they never left Meera's network. The fix was small. They turned on TCP keep-alive with an interval under 350 seconds, as AWS suggests 11. They also made the pool close connections that sit idle for long.
This story is made up, but the timeout and the RST come from the AWS docs. The lesson: you cannot debug this without knowing what a connection really is.
The idea in simple words
The internet is built in layers. Each layer does one job and uses the layer below 5:
- Application: your protocol, like HTTP or DNS.
- Transport: TCP or UDP. It moves data between two programs.
- Internet: IP. It moves single packets from one machine to another, through many routers.
- Link: the local network, like Ethernet or Wi-Fi, to the next device.
An IP address finds the machine. IPv4 addresses are 32 bits, like 10.0.4.17 3. IPv6 addresses are 128 bits 4. A port number finds the program on that machine. TCP uses ports to pick a service 1. In UDP, each port is a 16-bit field 2.
A packet is a small chunk of data with a header. The header says where it comes from and where it goes. IP only tries to deliver packets. It has no rules for reliability, order or flow control 3. Packets can arrive damaged, twice, out of order, or not at all 5.
So the transport layer decides how much to fix:
- UDP adds almost nothing: ports, a length and a checksum. It does not promise delivery or protect against duplicates 2.
- TCP gives you a reliable, in-order stream of bytes over a connection 1.
The key idea. IP can lose, repeat and reorder packets. TCP hides this from you, but the hiding costs time: a handshake to start, and waiting when a packet is lost. Most "network problems" in a backend are about those costs.
How it works
Step through the life of one TCP connection. Use Next and Back, or the ← and → keys.
- Your app wants to call the server on port 443. Its TCP sends a SYN packet. It carries a starting sequence number that is hard to guess. TCP uses these numbers to count bytes.
- The server answers with SYN-ACK. It confirms your number and sends its own starting number.
- Your app sends ACK. The connection is now open. One full round trip has passed, and no request data has moved yet.
- Now the request goes out. (With HTTPS, a TLS handshake would come first. It is left out here.) The server's TCP sends an ACK, which says "I have every byte up to here".
- The server sends the response in packets. The first one is lost. Later parts arrive and wait in a buffer. TCP gives bytes to your app only in order, so your app sees nothing yet.
- The server gets no ACK for part 1 before its retransmission timer ends, so it sends part 1 again. Now your app gets the whole response, in order.
- When one side is done, it sends FIN. The other side answers with ACK. When it is done too, it sends its own FIN. A last ACK closes the connection.
What TCP adds on top of IP
- Connections. Both sides agree to talk with the three-way handshake: SYN, SYN-ACK, ACK 1.
- Ordering and retransmission. Every byte has a sequence number. TCP finds lost data through these numbers and errors through checksums, then sends the data again 1.
- Flow control. Each packet TCP sends carries a window: how many more bytes the receiver will accept right now 1. A slow reader makes a fast sender wait.
- Congestion control. TCP must slow down when the network looks overloaded, so the network does not collapse 1.
Why a new connection costs a round trip
Your app cannot send the request until the handshake ends. That is one full round trip with no useful data. If a round trip to the server takes 150 ms, you wait about 150 ms before the request even leaves. TLS then runs its own handshake on top. See Latency numbers for typical round-trip times.
This is why connection reuse matters. MDN explains it for HTTP/1.x. A short-lived connection does a TCP handshake before each request. A persistent (keep-alive) connection stays open and serves many requests, with no new handshake 10. Idle connections are still closed after some time 10. A pool keeps a few open connections ready for many callers.
Head-of-line blocking
TCP gives bytes to your app only in order 1. If one packet is lost, every byte after it waits.
HTTP/2 sends many requests over one TCP connection. But TCP cannot see those requests. So one lost or reordered packet stalls all of them, even ones the loss did not touch 9. This is head-of-line blocking.
HTTP/3 fixes this by moving to QUIC. QUIC runs over UDP and builds its own reliable streams. A lost packet blocks only the streams with data in it 8. QUIC also includes the TLS handshake inside its own handshake 8. It uses UDP to make it easier to deploy on existing networks 8. HTTP/1.1, HTTP/2 and HTTP/3 goes deeper.
Reading the three common errors
- Connection refused. Your SYN reached the machine, but nothing listens on that port. TCP answers a SYN that matches no connection with a reset (RST) 1. It is fast. Check the port, and check that the process is running.
- Connection reset. The connection was open, then the other side, or a device in the middle, sent RST. TCP tells your app "connection reset" 1. A NAT gateway after an idle timeout is one cause 11. A server that restarted and lost the connection is another. TCP answers packets for a connection it does not know with RST 1.
- Timeout. No answer in time. Packets were dropped, a firewall ignores you, the host is down, or the server is too slow to reply. The TCP standard says a SYN must be retried for at least 3 minutes 1. So always set your own connect and read timeouts.
Private addresses and NAT
Some addresses are private: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Anyone can use them inside their own network, and they are not routed on the public internet 6. To reach the internet, these machines go through NAT. A NAT router swaps the private address and port for its own public address and port. Many machines then share one public address 7. The NAT keeps state for each connection 7. An AWS NAT gateway drops that state after 350 idle seconds 11. That is how Meera's resets happened.
Tools to see the network
ping host: sends ICMP echo requests and shows round-trip times and packet loss 12. If a host does not allow ICMP, you get no reply, even when the host is up 11.traceroute host: uses the IP time-to-live field to find each router on the path 13.curl -v https://host/path: shows the headers sent and received, plus extra lines about what curl does 15.tcpdump -i any port 443: prints the packets that match a filter. The interfaceanymeans all interfaces on Linux and recent macOS 14. Add-w fileto save the raw packets and read them later 14.
Trade-offs
| Option | Reliable and ordered? | Setup cost | Use it when |
|---|---|---|---|
| UDP | No Messages can be lost or repeated. 2 IP can reorder them, and UDP does not fix it. 5 | None. No connection. | Small messages where late data is useless, like game state or live voice. |
| TCP | Yes One ordered byte stream. 1 | One round trip, plus TLS. | Almost all service-to-service calls and databases. |
| QUIC | Yes , per stream. Loss blocks only its streams. 8 | TLS is part of its handshake. 8 | HTTP/3 to users on lossy mobile networks. |
| New connection per request | Yes | A handshake on every request. 10 | Rare calls, or scripts. |
| Keep-alive connection | Yes | Once, then reused. 10 | Repeated calls to the same host. |
| Connection pool | Yes | Once per connection. Idle ones can die in the middle. 11 | Busy services. Set the pool idle time below every timeout on the path. |
Simple rule: use TCP, reuse connections, and set your own timeouts. Reach for UDP or QUIC only when you can name the problem they solve.
At work: how a senior uses this
- When a call fails, ask first: "Refused, reset or timeout?" Each points to a different layer and a different owner.
- List every box between client and server: load balancer, proxy, NAT, firewall. Ask: "What is the idle timeout here?" Keep your pool idle time and keep-alive interval below the smallest one.
- Remember that the TCP standard says keep-alives must be off by default, with a default interval of at least two hours 1. That is far longer than the 350 seconds of an AWS NAT gateway 11. Set the interval yourself.
- Count new connections per request in a trace. A new TLS connection to a far region on every call is a common, hidden cost.
- Set a connect timeout and a read timeout on every client. Retry only idempotent calls, with backoff.
- When two teams blame each other, capture packets on both sides with
tcpdump. Packets end the argument. - See Load balancing for layer 4 and layer 7 balancers, and DNS and service discovery for how a name becomes an address.
With AI
What to ask the agent
"Here is our HTTP client setup in Go. List the connect timeout, read timeout, pool size, pool idle timeout and TCP keep-alive interval. Flag any value that is missing or longer than 350 seconds."
"Here is a curl -v output and a tcpdump capture of one failed call. Explain step by step who sent the RST and when."
"Our service opens a new connection for each call to the billing API. Show how to reuse connections in this code, and what can go wrong."
What to check yourself
- The agent names the real setting for your library and version. Check each default in the library's docs. Do not assume there is a timeout.
- Pool idle time is shorter than every idle timeout on the path: NAT, load balancer and server.
- Retries are added only for idempotent requests. A retried payment can charge twice.
- Any claim like "HTTP/3 is always faster" is tested on your own traffic before you act on it.
- In a packet capture, find who really sent the RST. A NAT gateway can send one too, not only the server 11.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 15 sources and related lessons
- Eddy (ed.), RFC 9293: Transmission Control Protocol (TCP) (IETF, 2022) (opens in a new tab)
The current TCP standard. Section 2.2 lists what TCP gives you; 3.5 and 3.6 show the handshake and the close; 3.8 covers retransmission, congestion control, failures and keep-alives. - Postel, RFC 768: User Datagram Protocol (IETF, 1980) (opens in a new tab)
All of UDP on three pages. The header has only two 16-bit ports, a length and a checksum. Delivery and duplicate protection are not guaranteed. - Postel (ed.), RFC 791: Internet Protocol (IETF, 1981) (opens in a new tab)
IPv4. Section 1.2 says what IP does not do; section 3.1 shows the header with 32-bit addresses and the time-to-live field. - Deering and Hinden, RFC 8200: Internet Protocol, Version 6 (IPv6) Specification (IETF, 2017) (opens in a new tab)
IPv6, which grows addresses from 32 to 128 bits. - Braden (ed.), RFC 1122: Requirements for Internet Hosts – Communication Layers (IETF, 1989), section 1.1.3 (opens in a new tab)
The four layers of the internet protocol suite, each described in a paragraph. - Rekhter et al., RFC 1918: Address Allocation for Private Internets (IETF, 1996) (opens in a new tab)
The three private address blocks, and why they are not routed on the public internet. - Srisuresh and Egevang, RFC 3022: Traditional IP Network Address Translator (Traditional NAT) (IETF, 2001) (opens in a new tab)
How NAT lets many private machines share one public address, by also translating ports. - Iyengar and Thomson (eds.), RFC 9000: QUIC: A UDP-Based Multiplexed and Secure Transport (IETF, 2021) (opens in a new tab)
QUIC streams, the built-in TLS handshake, and why it runs over UDP (section 1). Section 13 explains how it avoids head-of-line blocking across streams. - Bishop (ed.), RFC 9114: HTTP/3 (IETF, 2022), section 1 (opens in a new tab)
A short history of HTTP/1.1 and HTTP/2 over TCP, and why HTTP/3 moved to QUIC. - MDN Web Docs, “Connection management in HTTP/1.x” (opens in a new tab)
Short-lived and persistent connections, pipelining, and why browsers open about six connections per domain. - AWS, Amazon VPC User Guide, “Troubleshoot NAT gateways” (opens in a new tab)
Section “Internet connection drops after 350 seconds”. A connection idle for 350 seconds or more times out; the gateway then returns an RST, not a FIN. The fix is more traffic or TCP keepalive under 350 seconds. - Linux man-pages project, ping(8) (opens in a new tab)
How ping uses ICMP echo requests, and its options. - Linux man-pages project, traceroute(8) (opens in a new tab)
How traceroute uses the IP time-to-live field to find each router on the path. - The Tcpdump Group, tcpdump(1) manual page (opens in a new tab)
Capturing packets on an interface, with filters, and saving them to a file. - curl project, curl man page (option -v, --verbose) (opens in a new tab)
What each line of verbose output means.
Related: HTTP/1.1, HTTP/2 and HTTP/3 · TLS and secure connections · DNS and service discovery · Load balancing · Connection pooling and database limits · Latency numbers and back-of-envelope maths
- TLS and secure connections: the handshake that runs on top of TCP.
- HTTP/1.1, HTTP/2 and HTTP/3: multiplexing, and why QUIC exists.
- WebSockets, SSE and long polling: keeping one connection open for a long time.
- CDNs and HTTP caching: moving content closer, so round trips get shorter.