TCP / Networking
Every time you open a webpage, stream a video, or send a message, data travels across networks as a series of small chunks called packets. TCP — the Transmission Control Protocol — is the system that makes sure those packets arrive in the right order, with nothing missing, even when the network between you and the server is unreliable.
TCP trades speed for reliability. If that trade-off is wrong for your use case — live video, gaming, DNS lookups — you use UDP instead and handle the unreliability yourself. Most of the web runs on TCP. Most real-time apps run on UDP.
The OSI model
The OSI model splits networking into 7 layers. Each layer has a specific job and only talks to the layers directly above and below it. TCP lives at layer 4. HTTP lives at layer 7. Click any layer to see what it does.
The three-way handshake
Before any data is sent over TCP, the client and server must establish a connection. This takes exactly three messages — SYN, SYN-ACK, ACK. It guarantees both sides are reachable and agree on sequence numbers before a single byte of real data moves.
The TCP segment
Every piece of data sent over TCP is wrapped in a segment — a header plus payload. Click each field to see what it does.
TCP vs UDP
TCP and UDP share the same layer but make completely opposite bets. TCP assumes the network is unreliable and fixes it. UDP assumes you do not care.
Ports
A port is a 16-bit number that identifies a specific process on a machine. The IP address gets you to the right computer. The port gets you to the right door on that computer.
Packet loss & retransmission
The internet does not guarantee delivery. TCP detects packet loss with timeouts and duplicate acknowledgements, then retransmits. Watch what happens to throughput as loss increases.
# Tools for poking at the network
ping google.com # round-trip time to a host
traceroute google.com # every hop between you and the host
curl -v https://example.com # full HTTP request/response with headers
netstat -an # all open ports and connections
nslookup example.com # DNS lookup
ss -tulpn # modern netstat: sockets, ports, PIDs
Why TCP is slow to start
TCP uses slow start — a congestion control algorithm that begins by sending a small window of data and doubles it every round trip until it hits a limit or detects packet loss. This is why the first few seconds of a large download feel slower than the rest.
let cwnd = 1 // start: 1 segment
let ssthresh = 64 // slow start threshold
// Each ACK received:
if (cwnd < ssthresh) {
cwnd *= 2 // slow start: exponential
} else {
cwnd += 1 // congestion avoidance: linear
}
// On packet loss:
ssthresh = cwnd / 2 // back off
cwnd = 1 // restart slow start