Every distributed system is, underneath, programs exchanging packets over a network that can delay, drop, duplicate and reorder them. This lesson covers the networking every system designer needs: the OSI and TCP/IP layer models, IP addressing (IPv4, IPv6, CIDR, private ranges, NAT, ports), TCP vs UDP, the three-way handshake, how TCP avoids overwhelming receivers and the network, and where latency actually comes from.
Think of it like
Nested envelopes in the postal system
You write a letter (application data) and put it in an envelope marked with an apartment number (the port: which program). The building's mailroom puts that in a bigger envelope with the street address (the IP address: which machine). Trucks and sorting centers move it hop by hop using only the outer address (routers). Each layer reads and writes only its own envelope, which is exactly how network layers stay independent.
Why layers?
Networking is split into layers so each one can evolve independently. HTTP does not care whether it runs over Wi-Fi or fiber, and Ethernet does not care whether it carries a web page or a video call. On the way out, each layer encapsulates the data from the layer above by adding its own header; on the way in, each layer strips its header and passes the rest up.
Application [ HTTP request ]
Transport [TCP hdr][ HTTP request ] segment
Network [IP hdr][TCP hdr][ HTTP request ] packet
Link [Eth hdr][IP hdr][TCP hdr][ HTTP request ][Eth FCS] frame
Physical 0110100101110010... (voltages, light pulses or radio waves)The OSI model
The Open Systems Interconnection model is a seven-layer reference model. Real protocols do not map onto it perfectly, but its vocabulary is everywhere: "an L4 load balancer", "an L7 firewall", "a layer 2 switch".
| # | Layer | Role | Protocols and examples | Devices and components |
|---|---|---|---|---|
| 7 | Application | Network services used directly by applications | HTTP, DNS, SMTP, SSH, gRPC, WebSocket | L7 load balancer, API gateway, WAF |
| 6 | Presentation | Data representation: encoding, compression, encryption | TLS (loosely), JSON, Protobuf, gzip, UTF-8 | Implemented in software libraries |
| 5 | Session | Opening, managing and closing dialogs between peers | RPC sessions, NetBIOS, TLS session resumption | Implemented in software libraries |
| 4 | Transport | Process-to-process delivery via ports; reliability and flow control (TCP) | TCP, UDP, QUIC | L4 load balancer, stateful firewall |
| 3 | Network | Logical addressing and routing between networks | IPv4, IPv6, ICMP, IPsec | Router, L3 switch |
| 2 | Data link | Frames between directly connected nodes using MAC addresses | Ethernet, Wi-Fi (802.11), ARP, VLANs | Switch, bridge, network card |
| 1 | Physical | Raw bits as electrical, optical or radio signals | Copper (Cat6), fiber, 5G radio | Cables, repeaters, hubs, transceivers |
The TCP/IP model
| TCP/IP layer | OSI layers | Unit | Examples | Addresses |
|---|---|---|---|---|
| Application | 5, 6, 7 | Message | HTTP, DNS, TLS, SMTP, gRPC | URLs, host names |
| Transport | 4 | Segment (TCP) / datagram (UDP) | TCP, UDP, QUIC (on UDP) | Port numbers |
| Internet | 3 | Packet | IPv4, IPv6, ICMP | IP addresses |
| Link | 1, 2 | Frame | Ethernet, Wi-Fi, cellular | MAC addresses |
IP addressing
IPv4
- 32-bit addresses, written as dotted decimal:
203.0.113.10 - 2³² ≈ 4.3 billion addresses, effectively exhausted
- Header of 20 to 60 bytes; routers may fragment packets
- NAT is everywhere to stretch the address space
IPv6
- 128-bit addresses in hex groups:
2001:db8::8a2e:370:7334 - 2¹²⁸ ≈ 3.4 × 10³⁸ addresses: every device can be globally addressable
- Fixed 40-byte header; only the sender fragments
- Stateless autoconfiguration (SLAAC); NAT is not required
CIDR notation
Classless Inter-Domain Routing writes a network as an address plus a prefix length: 10.0.0.0/16 means the first 16 bits identify the network and the remaining 16 bits identify hosts within it. A smaller prefix means a bigger network.
| Prefix | Addresses | Typical use |
|---|---|---|
/32 | 1 | A single host (firewall rule, route to one machine) |
/28 | 16 | A tiny subnet |
/24 | 256 | A classic LAN or one cloud subnet (AWS reserves 5, leaving 251 usable) |
/20 | 4,096 | A larger subnet for a Kubernetes node pool |
/16 | 65,536 | A whole VPC, carved into many /24 subnets |
/8 | 16,777,216 | The entire 10.x.x.x private range |
Private ranges and special addresses
| Range | Span | Size | Purpose |
|---|---|---|---|
10.0.0.0/8 | 10.0.0.0 to 10.255.255.255 | 16.7M | Private (RFC 1918): large corporate networks, cloud VPCs |
172.16.0.0/12 | 172.16.0.0 to 172.31.255.255 | 1M | Private (RFC 1918): Docker's default bridge networks live here |
192.168.0.0/16 | 192.168.0.0 to 192.168.255.255 | 65,536 | Private (RFC 1918): home routers |
127.0.0.0/8 | 127.0.0.0 to 127.255.255.255 | 16.7M | Loopback: 127.0.0.1 is always this machine |
169.254.0.0/16 | 169.254.0.0 to 169.254.255.255 | 65,536 | Link-local; also cloud metadata at 169.254.169.254 |
100.64.0.0/10 | 100.64.0.0 to 100.127.255.255 | 4M | Carrier-grade NAT inside ISPs |
NAT: many devices, one public address
Network Address Translation lets a whole private network share one public IPv4 address. The router rewrites each outgoing packet's private source address and port to its own public address and a unique port, and remembers the mapping so replies can be translated back. The diagram shows it in action, along with a TCP handshake and teardown.
Ports and the 5-tuple
An IP address identifies a machine; a 16-bit port (0 to 65,535) identifies a process on it. Ports 0 to 1023 are well-known (privileged on Unix), 1024 to 49151 are registered, and 49152 to 65535 are ephemeral per IANA (Linux defaults to 32768 to 60999 for outgoing connections). A TCP connection is uniquely identified by its 5-tuple: protocol, source IP, source port, destination IP, destination port.
| Port | Service | Port | Service |
|---|---|---|---|
| 22 | SSH | 3306 | MySQL |
| 25 | SMTP | 5432 | PostgreSQL |
| 53 | DNS (UDP and TCP) | 6379 | Redis |
| 80 | HTTP | 9092 | Kafka |
| 443 | HTTPS (TCP) and HTTP/3 (UDP) | 27017 | MongoDB |
TCP vs UDP
TCP: reliable byte stream
- Connection setup with a three-way handshake
- Every byte acknowledged; losses retransmitted
- Delivered in order, no duplicates
- Flow and congestion control built in
- Web, APIs, databases, email, file transfer
UDP: fire-and-forget datagrams
- No handshake: the first packet carries data
- No acknowledgments or retransmission
- Datagrams may arrive out of order, duplicated or not at all
- 8-byte header; the application handles everything else
- DNS, VoIP, video calls, games, QUIC (HTTP/3), metrics
| Property | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Guaranteed delivery (or an error) | Best effort |
| Ordering | In-order byte stream | No ordering |
| Message boundaries | None: a stream of bytes the app must frame | Preserved: one send is one datagram |
| Header size | 20 to 60 bytes | 8 bytes |
| Congestion control | Yes (slow start, AIMD, CUBIC, BBR) | None; the app must be well behaved |
| Head-of-line blocking | Yes: one lost segment stalls everything behind it | No |
| Broadcast / multicast | No | Yes |
The three-way handshake
TCP numbers every byte. Before sending data, each side picks a random initial sequence number (ISN) and must learn the other's. Step through the handshake in the simulation above and watch the sequence and acknowledgment numbers.
- 1
SYN
The client sends a segment with the
SYNflag and its ISN, sayseq=1000. It moves toSYN-SENT. - 2
SYN-ACK
The server replies with
SYN+ACK, its own ISNseq=5000, andack=1001("I expect your byte 1001 next"). It moves toSYN-RECEIVED. - 3
ACK
The client sends
ack=5001. Both sides areESTABLISHED. The client may include request data in this segment, so the handshake costs one round trip before data flows.
Client Server (LISTEN)
| -- SYN seq=1000 ---------------------------> |
| <------------------ SYN-ACK seq=5000 ack=1001 --- | SYN-RECEIVED
| -- ACK seq=1001 ack=5001 ------------------> | ESTABLISHED
| -- data "GET / HTTP/1.1" (78 bytes) --------> |
| <------------------ ACK + data "HTTP/1.1 200" --- |
| ... |
| -- FIN ------------------------------------------> | CLOSE-WAIT
| <--------------------------------------- ACK ----- |
| <--------------------------------------- FIN ----- | LAST-ACK
| -- ACK ------------------------------------------> | CLOSED
TIME_WAIT (2 x MSL), then CLOSEDFlow control and congestion control
Flow control: protect the receiver
- Receiver advertises a receive window (
rwnd) in every ACK - It is the free space in the receiver's buffer
- A slow reader shrinks the window; at zero the sender pauses
- End-to-end, between two hosts
Congestion control: protect the network
- Sender keeps a congestion window (
cwnd) of its own - Grows while ACKs arrive, shrinks on packet loss
- Prevents many senders from collapsing shared links
- Inferred from loss and delay, never told directly
Slow start and AIMD
- 1
Slow start
A new connection starts with a small
cwnd, typically 10 segments (about 14 KB, RFC 6928). Each ACK adds one segment, socwnddoubles every round trip: exponential growth despite the name. - 2
Congestion avoidance
Once
cwndreaches the slow-start threshold (ssthresh), growth becomes linear: one segment per round trip. This is the additive increase. - 3
Loss via duplicate ACKs
Three duplicate ACKs signal a single lost segment. TCP retransmits it immediately (fast retransmit) and halves
cwnd: the multiplicative decrease. - 4
Loss via timeout
A retransmission timeout signals serious congestion. Classic TCP (Reno) sets
ssthreshto half the window and dropscwndback to one segment, re-entering slow start.
| Round trip | cwnd (segments) | Phase |
|---|---|---|
| 1 | 10 | Slow start |
| 2 | 20 | Slow start (doubling) |
| 3 | 40 | Slow start |
| 4 | 64 | Reached ssthresh = 64 |
| 5 | 65 | Congestion avoidance (+1 per RTT) |
| 6 | 66 | Loss detected by 3 duplicate ACKs |
| 7 | 33 | Multiplicative decrease, then +1 per RTT again |
Where latency comes from
- Propagation delay
- Distance ÷ signal speed. Light in fiber travels about 200,000 km/s, roughly 5 µs per km. Physics; only moving closer helps.
- Transmission delay
- Packet size ÷ link bandwidth: the time to push all bits onto the wire. A 1,500-byte packet takes 12 µs at 1 Gbps but 1.2 ms at 10 Mbps.
- Queuing delay
- Time spent waiting in router and switch buffers behind other packets. Near zero on idle links, dominant on congested ones (oversized buffers cause "bufferbloat").
- Processing delay
- Time for each device to inspect headers, check for errors and look up the route. Usually microseconds.
New York to London
~5,600 km
Great-circle distance
One-way in fiber
≥ 28 ms
5,600 km ÷ 200,000 km/s
Minimum RTT
≥ 56 ms
Real paths measure ~70 ms
1,500 B at 1 Gbps
12 µs
Transmission delay is tiny
Watch it on a real machine
# Which IPs and subnets does this host have?
ip addr show
# Path and per-hop latency to a server
traceroute example.com
# Capture only handshake and teardown segments for HTTPS
sudo tcpdump -i any -nn 'tcp port 443 and (tcp[tcpflags] & (tcp-syn|tcp-fin) != 0)'
# Count sockets stuck in TIME_WAIT
ss -tan state time-wait | wc -l
# Current congestion control algorithm
sysctl net.ipv4.tcp_congestion_controlImplementation
The same echo service over both transports. Notice the handshake, half-close and stream semantics in TCP, and the timeout the UDP client needs because datagrams can vanish.
import socket
import threading
import time
def tcp_echo_server(port: int) -> None:
# SOCK_STREAM = TCP: connection-oriented, reliable, ordered byte stream
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # rebind despite TIME_WAIT
srv.bind(("127.0.0.1", port))
srv.listen() # the kernel completes handshakes into an accept queue
while True:
conn, _ = srv.accept()
with conn:
while data := conn.recv(4096): # b"" means the peer sent FIN
conn.sendall(data)
def udp_echo_server(port: int) -> None:
# SOCK_DGRAM = UDP: no connection, every datagram stands alone
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
srv.bind(("127.0.0.1", port))
while True:
data, addr = srv.recvfrom(65535)
srv.sendto(data, addr)
def tcp_client(message: bytes, port: int) -> bytes:
with socket.create_connection(("127.0.0.1", port), timeout=2) as sock: # SYN, SYN-ACK, ACK
sock.sendall(message)
sock.shutdown(socket.SHUT_WR) # send FIN (half-close) but keep reading
chunks = []
while chunk := sock.recv(4096):
chunks.append(chunk)
return b"".join(chunks)
def udp_client(message: bytes, port: int) -> bytes | None:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(1.0) # no ACKs in UDP: the app must decide when to give up
sock.sendto(message, ("127.0.0.1", port))
try:
data, _ = sock.recvfrom(65535)
return data
except socket.timeout:
return None # lost request or lost reply: retry is up to us
if __name__ == "__main__":
threading.Thread(target=tcp_echo_server, args=(9000,), daemon=True).start()
threading.Thread(target=udp_echo_server, args=(9001,), daemon=True).start()
time.sleep(0.1)
print(tcp_client(b"hello over tcp", 9000))
print(udp_client(b"hello over udp", 9001))Key takeaways
- Layers encapsulate: application data is wrapped in a TCP/UDP segment, then an IP packet, then a link frame.
- OSI gives the vocabulary (L4 vs L7); the four-layer TCP/IP model is what the internet runs on.
- CIDR
/nleaves 32 − n host bits, so a block holds 2^(32 − n) addresses; RFC 1918 ranges are private and reach the internet through NAT. - TCP trades latency for reliability, ordering and congestion control; UDP is minimal and leaves those choices to the application.
- The three-way handshake costs one round trip; slow start means new connections ramp up over several more, so reuse connections.
- Latency = propagation + transmission + queuing + processing; propagation is bounded by the speed of light, so move data closer.
Common pitfalls
- Treating TCP as a message protocol: it is a byte stream, so one
sendcan arrive as severalrecvs (or several as one). Frame your messages. - Assuming UDP datagrams arrive, arrive once, or arrive in order.
- Opening a new TCP (and TLS) connection per request, paying handshakes and slow start every time and exhausting ports in TIME_WAIT.
- Confusing flow control (receiver's buffer,
rwnd) with congestion control (network capacity,cwnd). - Overlapping CIDR blocks between VPCs or offices you later need to connect (peering and VPNs require non-overlapping ranges).
Interview tips
- Use layer vocabulary precisely: an L4 load balancer routes on IP and port; an L7 one reads HTTP.
- When choosing a transport, argue from requirements: "stale data is useless, so UDP" or "every byte must arrive in order, so TCP".
- Quantify network costs: one RTT per handshake, roughly 5 µs per km of fiber, and around 70 ms for a transatlantic round trip.
Real-world applications
- Planning VPC and subnet layouts in the cloud.
- Choosing transports for streaming, gaming, VoIP and telemetry.
- Debugging connection issues with
tcpdump,ssandtraceroute. - Tuning servers for high connection counts (port ranges, TIME_WAIT, keep-alive).
Test yourself
At which OSI layer does a router make its forwarding decisions?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.