Summary#
Computers talk through layers: physical links carry bits, IP moves packets between machines using IP addresses, TCP or UDP deliver data to the right program using ports, and applications speak protocols like HTTP on top. NAT lets many private machines share one public address. Anycast sends users to the nearest copy of a service. Two numbers dominate performance: bandwidth (how much per second) and RTT (round-trip time).
Why It Exists#
Every arrow in a design diagram is a network path: it takes time, it can drop data, and it only reaches the right address and port. You need enough vocabulary to say where a component works ("an L4 load balancer"), why a call is slow (RTT), and why a server cannot be reached (NAT, firewall, wrong port). This page builds on What Happens When You Type a URL.
How It Works#
OSI and TCP/IP layers#
The OSI model describes networking in seven layers. The TCP/IP model, which the internet actually uses, merges them into four. Engineers still use OSI numbers as shorthand ("L4", "L7").
| OSI layer | TCP/IP layer | What it does | Examples |
|---|---|---|---|
| 7 Application | Application | Meaning of the data | HTTP, gRPC, DNS, SMTP |
| 6 Presentation | Application | Encoding, encryption | TLS, JSON, compression |
| 5 Session | Application | Conversation state | TLS sessions, RPC sessions |
| 4 Transport | Transport | Delivery to a program (ports), reliability | TCP, UDP, QUIC |
| 3 Network | Internet | Routing packets between networks | IP, ICMP |
| 2 Data link | Link | Delivery within one local network | Ethernet, Wi-Fi, MAC addresses |
| 1 Physical | Link | Bits on a wire or radio | Fibre, copper, radio |
Each layer wraps the data from the layer above with its own header (encapsulation): an HTTP request goes inside a TCP segment, inside an IP packet, inside an Ethernet frame.
Why layers matter to a designer#
Layering is an abstraction, in the same way that calling open() on a file spares you from telling the disk which sectors to read. When your service sends an HTTP request, it does not care which voltages mean 1 and 0, how Wi-Fi retries a frame, or which routers carry the packet between Mumbai and Virginia. Each layer offers a promise to the one above and hides how it keeps it:
- IP (layer 3) promises best-effort delivery of a packet to any address. "Best effort" means no promise at all about loss, duplication or order.
- TCP (layer 4) turns that into a reliable, ordered byte stream between two programs, by numbering bytes, acknowledging them and retransmitting what is lost. Your code can assume the bytes arrive complete and in order, or the connection reports an error.
- Application protocols (layer 7) such as DNS, HTTP and WebSocket give those bytes meaning.
Three layers come up again and again in system design: 3 (IP addressing and routing), 4 (TCP, UDP and QUIC) and 7 (HTTP and friends). Other technologies exist at each layer. Large ML training clusters, for example, often use InfiniBand rather than Ethernet and IP for their internal fabric. But IP, TCP and HTTP cover almost every design discussion.
Layering has a cost that matters in practice: the higher a component works in the stack, the more it must do per request. A layer-3 router looks at a destination address and forwards. A layer-4 load balancer also tracks connections. A layer-7 proxy must reassemble the byte stream, often decrypt TLS, parse HTTP headers and then decide. That is why layer-7 devices are more flexible and more expensive per request, and why "L4 or L7?" is a real design question. See Load Balancing.
Encapsulation overhead. Each layer adds a header, and on small messages the headers can outweigh the data:
| Layer | Header added | Typical size |
|---|---|---|
| Ethernet (L2) | MAC addresses, type, plus a 4-byte CRC trailer | 18 bytes, plus 20 bytes of preamble and inter-frame gap on the wire |
| IPv4 (L3) | Source and destination IP, TTL, protocol, checksum | 20 bytes (40 bytes for IPv6) |
| TCP (L4) | Ports, sequence and ack numbers, window, flags, options | 20-60 bytes, often 32 with the timestamp option |
| UDP (L4) | Ports, length, checksum | 8 bytes |
With the standard Ethernet MTU (maximum transmission unit) of 1,500 bytes, an IPv4 TCP packet leaves 1,460 bytes for data (the MSS, maximum segment size), or 1,448 with timestamps. On the wire that is roughly 95% efficiency for bulk transfers. A tiny message (say a 10-byte game update over TCP) still costs a full set of headers, around 80-90 bytes on the wire, which is why chatty protocols batch small messages together.
Following a packet across the network#
The layers become concrete when you follow one packet from a laptop to a server in the cloud.
- Is the destination local? The laptop compares the destination IP with its own address and subnet mask. A destination outside the local network goes to the default gateway, usually the home or office router.
- ARP. To send an Ethernet frame to the gateway, the laptop needs the gateway's MAC address (the hardware address of its network card). It broadcasts an ARP request ("who has 192.168.1.1?"), and the gateway answers. The result is cached for minutes.
- NAT at the edge. The home router rewrites the private source address to its public one and records the mapping (see NAT below).
- Hop by hop. Each router looks up the destination IP in its routing table and forwards the packet to the next hop. At every hop the layer-2 frame is rebuilt with new MAC addresses, while the IP addresses stay the same (unless NAT rewrites them). Each router also decrements the packet's TTL (time to live) field and drops the packet if it reaches zero, so a routing loop cannot circulate packets forever. The
traceroutetool uses this: it sends packets with TTL 1, 2, 3 and so on and records which router reports each expiry. - Across networks. The packet leaves your ISP, possibly crosses an internet exchange point or a transit provider's backbone, and enters the cloud provider's network, often at an edge location near you.
- Into the data centre. The cloud's own routers, then the load balancer, deliver it to a server, whose network card checks the frame, passes the IP packet to the kernel, and the kernel uses the destination port to hand the data to the right program.
A switch works at layer 2. It forwards frames inside one local network by MAC address and learns which port each MAC lives on. A router works at layer 3. It connects different networks and forwards by IP address. Data-centre gear often does both.
IP addresses#
An IP address identifies a network interface.
- IPv4 addresses are 32 bits (
203.0.113.10); the ~4.3 billion addresses ran out years ago. - IPv6 addresses are 128 bits (
2001:db8::1), enough for every device. - Public addresses are reachable on the internet. Private ranges (
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16) are used inside homes, offices and cloud networks (VPCs) and are not routed on the internet.
A CIDR block such as 10.0.0.0/16 means "the first 16 bits are fixed", giving 65,536 addresses. Cloud networks are carved into subnets this way.
IP addresses in more depth#
Why IPv4 ran out. Thirty-two bits give 2^32, about 4.29 billion addresses, and large blocks are reserved for private use, multicast and other special purposes. IANA, which hands address blocks to the five regional internet registries (ARIN, RIPE NCC, APNIC, LACNIC and AFRINIC), gave out its last free blocks in 2011, and the registries ran out over the following years. Today IPv4 addresses are bought, sold and leased, and cloud providers charge for public IPv4 addresses. Historically, large organisations received huge blocks. Apple, for example, holds the entire 17.0.0.0/8, about 16.7 million addresses. Routers on the internet backbone know that any packet for an address starting with 17 should be sent towards Apple's network.
Public, private and special addresses. An address is only meaningful because someone has announced where it lives. Inside a private network you can number machines however you like, usually assigned automatically by DHCP when they boot, but to be reachable from the internet you need addresses allocated by a registry and announced to the world's routers. Some ranges worth recognising:
| Range | Meaning |
|---|---|
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | Private networks (RFC 1918), not routed on the internet |
127.0.0.0/8 | Loopback: the machine itself (127.0.0.1 is "localhost") |
169.254.0.0/16 | Link-local, self-assigned. Cloud providers serve instance metadata at 169.254.169.254 |
100.64.0.0/10 | Shared address space for carrier-grade NAT inside ISPs |
0.0.0.0 | "Any address", used when a server listens on all interfaces |
CIDR arithmetic. A prefix length /n leaves 32 − n bits for hosts, so a block holds 2^(32 − n) addresses. A /24 has 256, a /20 has 4,096, a /16 has 65,536. Traditionally, the first address of a subnet names the network and the last is the broadcast address. Clouds reserve a few more: AWS keeps five addresses in every subnet for its router, DNS and future use, so a /24 gives 251 usable addresses.
A worked example of planning a cloud network for three availability zones:
| Block | Size | Use |
|---|---|---|
10.0.0.0/16 | 65,536 | The whole VPC |
10.0.0.0/20, 10.0.16.0/20, 10.0.32.0/20 | 4,096 each | Private application subnets, one per zone |
10.0.48.0/22, 10.0.52.0/22, 10.0.56.0/22 | 1,024 each | Private database subnets, one per zone |
10.0.60.0/24, 10.0.61.0/24, 10.0.62.0/24 | 256 each | Public subnets for load balancers and NAT gateways |
Two lessons come from real incidents. First, size generously. Container platforms such as Kubernetes can give every pod its own IP address, so a cluster of 200 nodes running 50 pods each needs 10,000 addresses, and a /24 per zone runs out quickly. Second, avoid overlapping ranges between networks that may one day be connected (VPC peering, VPNs to offices, acquisitions). Two networks that both use 10.0.0.0/16 cannot be routed to each other without painful NAT.
IPv6 in practice. An IPv6 address is 128 bits, written as eight groups of four hex digits. Leading zeros in a group may be dropped, and one run of all-zero groups may be replaced by ::, so 2001:0db8:0000:0000:0000:0000:0000:0001 becomes 2001:db8::1. The standard subnet size is a /64, which holds 2^64 addresses: one subnet has more addresses than the entire IPv4 internet, squared. Hosts can configure their own addresses (SLAAC), and because addresses are plentiful, NAT is not needed: every device can have a globally unique address, with firewalls (not address scarcity) deciding what is reachable. The loopback is ::1, link-local addresses start with fe80::, and fc00::/7 is the private-like "unique local" range.
Adoption is uneven but substantial. Many mobile networks are IPv6-first, and Google's public statistics show a large share of its users (in the 40-50% range in recent years) reaching it over IPv6. That is why public services should be dual-stack: reachable over both IPv4 and IPv6. Clients use Happy Eyeballs to try both and keep whichever connects first.
Ports and common port numbers#
A port is a 16-bit number (0-65535) that identifies a program on a machine. An IP address plus a port (203.0.113.10:443) is a socket address. A connection is identified by source IP, source port, destination IP, destination port and protocol.
| Port | Service |
|---|---|
| 22 | SSH |
| 53 | DNS |
| 80 | HTTP |
| 443 | HTTPS (and HTTP/3 over UDP) |
| 3306 | MySQL |
| 5432 | PostgreSQL |
| 6379 | Redis |
| 9092 | Kafka |
Ports in more depth#
Ranges. Port numbers are split into three ranges by IANA. Well-known ports (0-1023) are for standard services, and on Unix-like systems only privileged processes can listen on them. Registered ports (1024-49151) are used by common applications such as databases. Dynamic or ephemeral ports (49152-65535 in the IANA scheme) are picked by the operating system for the client side of outgoing connections. Linux by default uses 32768-60999 for ephemeral ports, about 28,000 of them.
More ports you will meet in designs:
| Port | Service | Port | Service |
|---|---|---|---|
| 25 / 587 | SMTP mail relay / submission | 5672 | AMQP (RabbitMQ) |
| 123 (UDP) | NTP time sync | 9042 | Cassandra CQL |
| 1433 | Microsoft SQL Server | 9200 | Elasticsearch HTTP API |
| 2181 | ZooKeeper | 11211 | Memcached |
| 2379 | etcd clients | 27017 | MongoDB |
| 8080 / 8443 | Alternative HTTP / HTTPS, common for app servers behind a proxy | 3478 | STUN and TURN for WebRTC |
One listening port, millions of connections. A server listening on port 443 does not "use up" a port per client. Each connection is identified by its full 4-tuple (client IP, client port, server IP, server port), so a million clients connecting to the same server port are a million different tuples. The real limits on concurrent connections are memory (kernel buffers and application state, often a few KB to tens of KB per idle connection), file-descriptor limits and CPU. Well-tuned servers hold hundreds of thousands to millions of idle connections each, which is what makes large chat and push systems possible. See Real-Time Communication.
Ephemeral port exhaustion: a client-side limit. The limit bites on the other side. A proxy or service that opens connections to one destination (one IP and port) can have at most one connection per local ephemeral port, about 28,000 on default Linux settings. Worse, a connection closed by the client sits in TIME_WAIT for about 60 seconds on Linux before its port can be reused for the same destination. A service that opens and closes a fresh connection for every request can therefore sustain only about 28,000 / 60 ≈ 470 new connections per second to that destination before it runs out of ports and starts failing with "cannot assign requested address". Fixes, in order of preference:
- Reuse connections with keep-alive and connection pools, so a few hundred long-lived connections carry all the traffic.
- Spread across more destinations or source IPs, because each distinct 4-tuple has its own port space.
- Tune the kernel (a wider ephemeral range, allowing safe reuse of TIME_WAIT sockets for outgoing connections). This raises the ceiling but does not remove the waste.
Default ports and URL identity. Because http implies port 80 and https implies port 443, https://example.com:443/a and https://example.com/a are the same resource. Systems that use a URL as a key, such as a URL shortener deduplicating links or a cache keyed by URL, should canonicalise first: lowercase the scheme and host, drop default ports, and normalise details such as a trailing slash. Otherwise one resource gets several keys, and caches and deduplication quietly stop working.
NAT#
Network Address Translation rewrites addresses as packets pass through a router. A home router or cloud NAT gateway lets many private machines share one public IP: outgoing packets get the public address and a chosen port, and the router remembers the mapping so replies return to the right machine.
NAT saves IPv4 addresses and hides internal machines, but outside clients cannot start connections to a machine behind it, which is why peer-to-peer video calls need special techniques.
NAT in more depth#
NAT comes in a few forms, and each one shows up somewhere in a typical system:
- Source NAT (SNAT): rewrite the source address of outgoing packets. Home routers and cloud NAT gateways do this so private machines can reach the internet.
- Port address translation (PAT, also NAPT or "NAT overload"): SNAT where many private machines share one public IP, distinguished by the public-side port the router assigns. This is what almost every home router does.
- Destination NAT (DNAT): rewrite the destination of incoming packets, as in "port forwarding" or a layer-4 load balancer that maps a public IP to a private server.
The NAT table is state, and state expires. The router keeps each mapping only while it sees traffic. Timeouts vary by device, from tens of seconds for UDP to minutes or hours for TCP. AWS's NAT gateway, for instance, drops idle TCP connections after 350 seconds. Two design consequences follow:
- Long-lived idle connections die silently. A WebSocket or database connection that sends nothing for several minutes can lose its mapping. The next packet is dropped or reset, and the application sees a hung or broken connection. Send keep-alive or heartbeat messages more often than the shortest NAT timeout on the path (every 20-60 seconds is common for mobile push and chat).
- Inbound connections are impossible by default. No mapping exists until the inside machine sends first, which is why a server behind NAT cannot accept connections without port forwarding.
Carrier-grade NAT (CGNAT). Because IPv4 is scarce, many mobile carriers and some ISPs put thousands of customers behind a shared pool of public addresses, using the 100.64.0.0/10 range internally. From your server's point of view, a large number of unrelated users can arrive from one IP. That matters for rate limiting and abuse blocking by IP: a strict per-IP limit can lock out a whole carrier's customers in a city. Prefer limits by user, API key or device, and treat IP limits as a coarse outer layer. See Rate Limiting.
Getting through NAT: peer-to-peer. Video calls and multiplayer games want devices to talk directly. WebRTC uses a framework called ICE: each peer asks a STUN server "what public address and port do you see me as?", the peers exchange those candidates through a signalling server, and both send packets at once so each NAT creates a mapping that lets the other's packets in (hole punching). When that fails, as it often does with strict corporate or carrier NATs, traffic is relayed through a TURN server, which costs bandwidth and adds latency but always works.
NAT in the cloud. A typical cloud network gives private servers outbound internet access (to download packages or call third-party APIs) through a managed NAT gateway in a public subnet. Gateways charge per hour and per GB processed, so a service that pulls large volumes from the internet (or from cloud storage via public endpoints) through NAT can generate a surprising bill. Private endpoints to the provider's own services avoid that path.
Unicast, broadcast, multicast and anycast#
| Mode | Sends to | Typical use |
|---|---|---|
| Unicast | One specific receiver | Almost all web traffic |
| Broadcast | Every machine on the local network | ARP, DHCP discovery |
| Multicast | A subscribed group | Market data feeds, IPTV inside a network |
| Anycast | The nearest of many servers sharing one IP | DNS root servers, CDNs, DDoS absorption |
Anycast matters most for system design: many sites announce the same IP, and routing delivers each user to the closest one, lowering latency and spreading attack traffic.
Delivery modes in more depth#
Broadcast stays local. A broadcast frame goes to every machine in one layer-2 broadcast domain (one LAN or VLAN) and is never forwarded by routers. ARP uses it to find the MAC address for an IP, and DHCP uses it when a booting machine does not yet have an address. Large flat networks suffer "broadcast storms", which is one reason data centres are divided into many small layer-2 segments connected by routing. Public clouds typically do not support broadcast inside a VPC at all and answer ARP themselves.
Multicast needs the network's cooperation. A sender transmits once to a group address (in 224.0.0.0/4), and routers copy the packet only onto links where some receiver has joined the group (hosts join using IGMP). This is efficient for one-to-many feeds: a stock exchange sending market data to hundreds of trading firms in the same colocation facility, or IPTV inside an operator's network. Multicast is not available across the public internet, and most cloud networks support it only in limited forms, so application designs fan out with unicast, through a message broker or a CDN.
Anycast is how one IP lives in many cities. With anycast, many sites announce the same IP prefix to the internet using BGP (Border Gateway Protocol, the routing protocol between networks). Each router picks the "best" route by BGP's rules, mostly the shortest path in terms of networks crossed and the operators' own policies, so users usually reach a nearby site. Note that "nearest" means nearest in routing terms, which is usually but not always nearest geographically.
Anycast has three properties that make it popular for DNS, CDNs and DDoS protection:
- Low latency without client logic. No GeoDNS lookup is needed. The network itself steers each user.
- Attack absorption. A flood of attack traffic from around the world is split across every site, instead of concentrating on one data centre.
- Simple failover. A site that is unhealthy or under maintenance withdraws its BGP announcement, and traffic shifts to the next-best site within seconds to minutes.
The classic worry is TCP. If routing changed mid-connection and packets started arriving at a different site, that site would know nothing about the connection. In practice internet routes are stable enough over the seconds to minutes of a typical connection that anycast works well for HTTP and DNS. Very long-lived connections are more exposed, and operators mitigate it with careful traffic engineering and by tolerating occasional reconnects.
LAN vs WAN#
A LAN (local area network) connects machines in one building or data center: high bandwidth (10-100 Gbps) and very low RTT (~0.5 ms or less). A WAN (wide area network) connects distant sites, such as regions or offices: lower bandwidth per flow, higher cost and much higher RTT (tens to hundreds of milliseconds). Designs that are chatty over a LAN can be painfully slow over a WAN.
LAN and WAN in more depth#
Inside a data centre. Modern data-centre networks are built as a leaf-spine (or Clos) fabric. Every rack has a top-of-rack leaf switch, and every leaf connects to every spine switch. Any server reaches any other in the same number of hops (server, leaf, spine, leaf, server), and traffic is spread across all the spines using ECMP (equal-cost multi-path routing), which hashes each flow's 5-tuple to pick a path so packets of one connection stay in order. The design is named after Charles Clos, who described such multi-stage switching networks for telephone exchanges in 1953. Google's SIGCOMM 2015 paper "Jupiter Rising" (Singh et al.) describes a decade of building Clos fabrics of this kind at very large scale.
Two terms come from this picture. North-south traffic enters or leaves the data centre (users to load balancers). East-west traffic flows between servers inside it (services calling services, replication, shuffles in batch jobs), and in microservice and data-heavy systems it is often many times larger than north-south traffic. Oversubscription is the ratio between the bandwidth servers in a rack could send and the uplink bandwidth from the rack. At 3:1, if every server in a rack transmits at full speed to other racks at once, each gets only a third of its link speed. That rarely matters for web traffic but matters a lot for big data shuffles and ML training.
Between zones and regions. Availability zones in one region are separate data centres connected by high-capacity private links, typically 1-2 ms apart. That is fast enough for synchronous database replication. Regions are hundreds or thousands of kilometres apart, tens to hundreds of milliseconds round trip, so cross-region traffic is usually asynchronous. Large cloud providers run private backbones between their regions, so traffic between two of their regions often travels on their own fibre rather than the public internet, with more predictable latency.
Ways to connect sites:
| Option | What it is | Fits when |
|---|---|---|
| VPC peering / transit gateway | Private routing between cloud networks | Connecting your own VPCs or accounts |
| Site-to-site VPN | Encrypted tunnel over the internet | Office or on-premises to cloud, modest bandwidth |
| Dedicated interconnect (AWS Direct Connect, Google Cloud Interconnect, Azure ExpressRoute) | A leased private link into the provider | Steady high bandwidth, predictable latency, compliance |
| SD-WAN | Software-managed routing across several links | Many branch offices |
WANs cost money per byte. Inside one zone, traffic is usually free. Between zones, many clouds charge per GB (on AWS around a cent per GB in each direction). Egress to the internet costs several cents per GB, before CDN discounts. A chatty service that sends 100 MB/s across zones moves about 8.6 TB a day, roughly 260 TB a month, which at a cent per GB each way is thousands of dollars a month just to cross a zone boundary. Cost, not only latency, is a reason to keep chatty components together and to compress replication traffic.
Checksums#
Bits can be corrupted by faulty hardware or noise. A checksum is a small value computed from the data and sent with it; the receiver recomputes it and drops the data if it does not match. Ethernet uses a strong CRC; IP, TCP and UDP carry weak 16-bit checksums, so TLS and storage systems add stronger integrity checks.
Checksums in more depth#
How the internet checksum works. IPv4 (for its header), TCP and UDP use the same simple algorithm. Treat the data as a sequence of 16-bit words, add them with one's-complement arithmetic (carries out of the top bit wrap around and are added back in), and send the bitwise complement of the sum. The receiver adds everything, including the checksum, and expects all ones.
// Internet checksum (RFC 1071), simplified
function internetChecksum(bytes: Uint8Array): number {
let sum = 0;
for (let i = 0; i < bytes.length; i += 2) {
const word = (bytes[i] << 8) | (bytes[i + 1] ?? 0); // pad odd length
sum += word;
sum = (sum & 0xffff) + (sum >>> 16); // wrap carry
}
return ~sum & 0xffff; // one's complement
}It is cheap to compute and to update incrementally, which is why routers can patch it when they change a header field such as the TTL. But it is weak. It cannot detect two 16-bit words swapped in order, or errors that cancel out, and a random corruption has about a 1 in 65,536 chance of passing.
CRCs are stronger. A cyclic redundancy check treats the data as a polynomial and divides it by a fixed generator polynomial, sending the remainder. A 32-bit CRC detects every burst of errors up to 32 bits long and almost all other random corruption. Ethernet frames carry a CRC-32. Storage and data systems use CRC-32C (the "Castagnoli" polynomial, which modern CPUs compute in hardware): Kafka, for example, puts a CRC-32C on each record batch, and many file systems checksum their metadata.
Why links checking is not enough. Each link's CRC protects only that link. Inside a router, a switch, a network card or a server's memory, a packet is unprotected between the check on arrival and the new CRC on departure. Jonathan Stone and Craig Partridge's SIGCOMM 2000 paper "When the CRC and TCP Checksum Disagree" analysed real traffic and found that a meaningful number of corrupted packets got past link-level checks, with faulty host and router hardware and software among the causes. For those packets, the weak TCP checksum was the last line of defence.
The end-to-end argument. Saltzer, Reed and Clark's 1984 paper "End-to-End Arguments in System Design" makes the general point: some guarantees can only be made correctly by the endpoints, because only they know what "correct" means. Lower layers can check to improve performance, but the application must check anyway. In practice:
- TLS protects every record with a cryptographic authentication tag (from an AEAD cipher such as AES-GCM), which detects both accidental corruption and deliberate tampering. Plain checksums detect only accidents, since an attacker can simply recompute them.
- Object stores and file transfer tools verify end to end. Clients send a checksum with an upload (Amazon S3 accepts CRC-32, CRC-32C, SHA-1 or SHA-256, or an MD5 in
Content-MD5) and the service rejects data that does not match. - Databases and replication store page or block checksums and compare replicas in the background (anti-entropy), often with Merkle trees, so silent disk corruption is caught and repaired from a good copy.
- Content-addressed systems (Git, many backup tools, container registries) name data by its cryptographic hash, so identity and integrity become the same check.
| Check | Size | Detects | Used by |
|---|---|---|---|
| Internet checksum | 16 bits | Most single-bit and short errors | IPv4 header, TCP, UDP |
| CRC-32 / CRC-32C | 32 bits | All bursts up to 32 bits, nearly all random errors | Ethernet, Kafka, storage systems |
| SHA-256 | 256 bits | Any corruption, practically never collides | Content addressing, downloads, object integrity |
| HMAC / AEAD tag | 128-256 bits | Corruption and tampering, needs a key | TLS, signed tokens, signed URLs |
Bandwidth and RTT#
- Bandwidth is the maximum data rate of a link, quoted in bits per second (1 Gbps is ~125 MB/s).
- RTT (round-trip time) is the time for a packet to reach the other side and a reply to come back. Same data center ~0.5 ms; across a continent ~60-70 ms; between continents ~100-200 ms. See Numbers to Know.
For small requests, RTT dominates: a 1 KB API call across the ocean is slow because of distance, not bandwidth. For large transfers, bandwidth dominates. Each new connection also costs extra round trips for TCP and TLS handshakes; see TCP vs UDP.
Bandwidth and RTT in more depth#
Four parts of latency. The time for one packet to cross a link is the sum of four delays:
| Component | What it is | Formula or typical value |
|---|---|---|
| Propagation | Signal travelling the distance | Distance ÷ about 200,000 km/s in fibre, roughly 5 µs per km |
| Transmission (serialisation) | Pushing the bits onto the link | Packet size ÷ link rate: 1,500 bytes at 1 Gbps takes 12 µs, at 10 Mbps 1.2 ms |
| Queuing | Waiting in router or switch buffers | Zero on an idle path, up to hundreds of ms on an overloaded one |
| Processing | Routers and hosts handling the packet | Microseconds per hop in hardware, more in software and in the application |
Over long distances, propagation dominates and no engineering removes it. Over slow links (old mobile networks, satellite uplinks), transmission time matters. Queuing is the wild card. When buffers in home routers or mobile networks are oversized, a single large upload can fill them and add hundreds of milliseconds to every other packet, a problem known as bufferbloat. Active queue management algorithms such as CoDel and FQ-CoDel were designed to fix it.
Worked example: when does bandwidth matter? Fetch a resource from a server 100 ms RTT away over a 100 Mbps path, ignoring handshakes:
- 1 KB: transmission time is 0.08 ms. Total ≈ 100 ms. Pure RTT.
- 1 MB: transmission is 80 ms, but from a cold start TCP's window begins at about 14.6 KB and doubles each round trip, so delivering 1 MB takes about seven round trips. Total ≈ 700-800 ms, still mostly RTT. A warm, reused connection would need far fewer.
- 1 GB: transmission is 80 seconds. RTT is now negligible, if TCP can keep the pipe full.
The window limit. TCP can have at most one window of unacknowledged data in flight, so a single connection's throughput is at most window ÷ RTT. The original TCP header allows a window of only 64 KB, so without the window scaling option (RFC 7323) one connection at 100 ms RTT is capped at 64 KB ÷ 0.1 s ≈ 5.2 Mbps, however fast the link. To fill a link you need the bandwidth-delay product in flight: 1 Gbps × 100 ms = 12.5 MB. Modern operating systems scale windows automatically, but small buffer settings on servers or proxies still cap long-distance throughput in practice.
The loss limit. Packet loss throttles TCP even more. A well-known approximation by Mathis, Semke, Mahdavi and Ott (1997) says a classic loss-based TCP flow achieves roughly:
throughput ≈ (MSS ÷ RTT) × (1.22 ÷ √p)
where p is the packet loss rate. With MSS 1,460 bytes, RTT 100 ms and 0.1% loss, that is (11,680 bits ÷ 0.1 s) × (1.22 ÷ 0.0316) ≈ 4.5 Mbps. A 1 Gbps link does not help a single flow across an ocean with even light loss. Newer congestion control such as Google's BBR, which models the path's bandwidth and RTT rather than reacting mainly to loss, does much better on such paths. Bulk-transfer tools also open several parallel connections to multiply throughput.
Bandwidth, throughput and goodput. Bandwidth is the link's capacity. Throughput is what a flow actually achieves. Goodput is the useful application data per second, after headers, retransmissions and protocol overhead. Links are quoted in bits per second, files in bytes, so divide by 8: a "1 Gbps" link moves at most about 125 MB/s, and around 110-118 MB/s of goodput after overheads.
Measuring. ping measures RTT with ICMP. traceroute and mtr show per-hop delay and loss along a path, which helps find where latency or loss begins. iperf3 measures achievable throughput between two hosts. In applications, record connection, TLS and time-to-first-byte timings separately so you can tell a slow network from a slow server.
When to Use It#
- When choosing a load balancer: L4 (IP and port) or L7 (HTTP).
- When designing cloud networks: public subnets for load balancers, private subnets with NAT for servers and databases.
- When explaining latency: count round trips, multiply by RTT.
When NOT to Use It#
- Do not go into packet formats or routing protocols in an interview unless asked; stay at the level of layers, addresses, RTT and bandwidth.
How to Implement It#
- Put databases and app servers in private subnets; only load balancers get public addresses.
- Give outbound internet access through a NAT gateway, not public IPs on servers.
- Open only needed ports with security groups or firewalls (443 inbound to the LB; 5432 only from app servers).
- Keep chatty paths inside one zone or region, and reuse connections to avoid repeated handshakes.
VPC 10.0.0.0/16
public subnet 10.0.1.0/24 : load balancer (443 from internet), NAT gateway
private subnet 10.0.2.0/24 : app servers (8080 from LB only)
private subnet 10.0.3.0/24 : PostgreSQL (5432 from app subnet only)| Technology | Fits when |
|---|---|
| AWS VPC, GCP VPC, Azure VNet | Building private cloud networks with subnets and routing |
| Security groups, network ACLs | Restricting which ports and sources are allowed |
| Cloud NAT gateway | Outbound internet for private servers |
ping, traceroute, mtr, dig | Measuring RTT and finding where a path is slow |
A production network, step by step#
The short VPC plan above is enough for one service. A real production network adds a few more pieces. Walking through them in order shows why each exists.
- One subnet per tier per zone. Each availability zone gets its own public, private and data subnet, so losing a zone loses one copy of each tier, not a whole tier. With a
/16VPC you might give each subnet a/20(4,096 addresses), which leaves room for container platforms that assign one IP per pod. - Route tables decide what a subnet is. A "public" subnet is simply one whose route table sends
0.0.0.0/0to the internet gateway. A "private" subnet sends0.0.0.0/0to a NAT gateway instead, so its servers can start outbound connections but nobody can start one to them. A data subnet may have no default route at all. - Two layers of filtering. Security groups are attached to each network interface and are stateful: if an outbound request is allowed, its reply is allowed automatically. Network ACLs are attached to subnets and are stateless: you must allow the reply direction explicitly, including the ephemeral port range (1024-65535). Most teams do almost all filtering with security groups that reference other security groups ("allow 5432 from the app tier's group"), which keeps working as servers come and go, and keep network ACLs as a coarse backstop.
- Private endpoints for cloud services. Without them, a private server talking to object storage or a managed queue goes out through the NAT gateway and pays per-GB processing for every byte. A VPC endpoint (AWS calls it a gateway or interface endpoint; GCP has Private Service Connect) keeps that traffic on the provider's private network, which is cheaper and does not depend on the NAT.
- Connecting networks. Two VPCs can be joined with peering (point to point, non-transitive: if A peers with B and B with C, A still cannot reach C) or through a transit gateway (a hub that routes between many VPCs and on-premises links). Either way the address ranges must not overlap, which is why the address plan matters from day one.
- Operator access. Engineers reach private servers through a VPN, a bastion host, or a provider session manager that needs no open inbound port at all. This is also the "out-of-band" path you will want when the main network is broken.
The same shape appears on every major cloud with different names: AWS VPC and security groups, GCP VPC and firewall rules, Azure VNet and network security groups.
Debugging a slow or failing connection#
When "the service is slow" or "it cannot connect", work up the layers instead of guessing. Each step rules out a whole class of causes:
| Step | Question | Tool | What the answer tells you |
|---|---|---|---|
| 1 | Does the name resolve, and to what? | dig api.example.com | Wrong or stale IP, slow DNS, NXDOMAIN |
| 2 | Is there a route, and where does latency appear? | mtr, traceroute | Which hop adds delay or loss (ICMP may be deprioritised, so look at the trend) |
| 3 | Is the port open? | nc -vz host 443 | "Refused" means the host answered but nothing listens. A timeout usually means a firewall or security group drops it |
| 4 | Where does request time go? | curl -w with time_namelookup, time_connect, time_appconnect, time_starttransfer | DNS vs TCP vs TLS vs server processing |
| 5 | What is the host's connection state? | ss -s, ss -tan | Thousands of TIME_WAIT or SYN_RECV entries, full accept queues |
| 6 | What is actually on the wire? | tcpdump, Wireshark | Retransmissions, resets, zero windows, missing ICMP |
Two distinctions save hours. A refused connection is fast and means the network path works but no process listens on that port. A timeout is slow and means packets are silently dropped, usually by a firewall rule, a missing route or a NAT problem. And if small requests work but large responses hang, suspect MTU before suspecting the application.
A worked reading: curl -w reports DNS 2 ms, connect 75 ms, TLS done at 152 ms, first byte at 610 ms. The network costs are one RTT for TCP (about 75 ms) and one more for TLS 1.3, which fits a client about 7,000 km away. The remaining ~460 ms is the server thinking. The fix is in the application or database, not the network, and moving the server closer would save at most ~150 ms.
Trade-offs#
| Choice | Pros | Cons | Pick when |
|---|---|---|---|
| IPv4 only | Universal support | Address scarcity, NAT everywhere | Most internal networks today |
| Dual-stack IPv4 + IPv6 | Reaches IPv6-only mobile networks | More to configure and secure | Public-facing services |
| Anycast | Nearest site, DDoS spreading | Needs many sites and BGP expertise | DNS, CDNs, global edge |
| Single-region deployment | Low internal RTT, simple | Far users see high RTT | Users mostly in one area |
| NAT gateway for outbound traffic | Private servers stay unreachable from outside | Per-GB processing cost, idle-timeout surprises | Servers that need to call the internet |
| IPv6-only internal network | No address planning pain, no NAT | Some tools and dependencies still assume IPv4 | Very large container fleets, greenfield networks |
| Jumbo frames inside the VPC | Less per-packet overhead for bulk data | Must fall back to 1,500 at the edge, PMTU risks | Storage, replication, analytics traffic |
| Cross-zone deployment | Survives a data-centre failure | 1-2 ms extra RTT, per-GB transfer cost | Anything that must stay available |
| Connection pooling | No handshakes, no ephemeral-port exhaustion | Pools to size and monitor, stale connections | Any service calling another service or a database often |
| Per-IP limits | Simple, works without login | CGNAT puts many users behind one IP | Coarse outer protection only |
Common Pitfalls#
- Confusing bits and bytes when sizing links.
- Putting databases in public subnets.
- Ignoring RTT when a request makes several sequential cross-region calls.
- Assuming a server behind NAT can receive incoming connections.
- Subnets sized too small for container platforms that give each pod its own IP.
- Overlapping private address ranges between networks that later need to be connected.
- Opening a new connection per request to the same backend until ephemeral ports run out.
- Long idle connections through NAT or load balancers with no keep-alives, which then die silently.
- Blocking all ICMP, which breaks path MTU discovery and causes connections that hang on large responses.
- Rate limiting or banning by IP without allowing for carrier-grade NAT.
- Trusting the 16-bit TCP checksum as end-to-end integrity for stored data instead of verifying with a strong checksum or hash.
- Forgetting that cross-zone and internet egress traffic is billed per GB.
Real-World Examples#
The DNS root servers are run by 12 operators under 13 well-known names, but each name is served from many anycast sites worldwide, so a query reaches a nearby copy.
Cloudflare publicly describes using anycast across its network so the same IP addresses are served from many cities.
Facebook's outage of 4 October 2021 is the clearest public example of network fundamentals taking down a whole company. A maintenance command disconnected its backbone, its DNS servers withdrew their BGP routes as designed, and its services vanished from the internet for about six hours. The company's own write-up explains the chain of events.
In February 2008, a BGP announcement from Pakistan Telecom, meant to block YouTube inside Pakistan, leaked to the wider internet and redirected much of YouTube's global traffic for a couple of hours. The incident is a standard case study for why route origin validation (RPKI) exists.
IANA handed out its last free blocks of IPv4 addresses to the regional registries in 2011. The resulting scarcity is why NAT, carrier-grade NAT and paid public IPv4 addresses in the cloud are everyday facts, and why IPv6 adoption keeps growing.
In the Interview#
What interviewers assume, and where networking earns points#
In most design interviews the network is assumed: clients speak HTTPS over TCP, services call each other over the data-centre LAN, and nobody asks about MAC addresses. You rarely need to say "we use TCP", because it is the default. Networking knowledge earns credit in a few specific moments:
- Choosing UDP deliberately. Make the case only where loss is acceptable and latency matters most: live audio and video, game state, high-volume telemetry. Then handle the details. Browsers cannot open raw UDP sockets, so browser clients get UDP only through WebRTC (or QUIC inside HTTP/3). A design that streams live reactions over UDP to the mobile app might send browser users a batched HTTP or WebSocket stream instead.
- Explaining latency with arithmetic. "Three sequential calls from Europe to a US database cost three round trips of about 90 ms, so the page cannot meet a 200 ms target. We will move the read path to a European replica."
- Placing things in the network. Load balancers in public subnets, everything else private, outbound access through NAT, databases reachable only from the application tier, replicas in separate availability zones.
- Recognising connection limits. "Each gateway node holds 500,000 idle WebSocket connections, limited by memory, so 10 million online users need about 20 nodes plus headroom", or "pool connections to the database to avoid ephemeral port and handshake costs".
- Spotting IP-based assumptions. Carrier-grade NAT means many users share an IP, so per-IP rate limits and IP-based identity are weak.
Keep packet-level detail in reserve. If the interviewer has a networking background, a sentence on MTU, BGP or congestion control can impress, but most interviews reward spending the minutes on the problem's real bottleneck.
A one-minute network sketch#
When you draw the high-level design, a compact way to show network awareness is:
- Users reach the service through DNS and a CDN or anycast edge.
- A load balancer in a public subnet ends TLS.
- Application servers sit in private subnets across three availability zones.
- Databases and caches sit in private subnets reachable only from the application tier, with replicas in other zones.
- Outbound calls to third parties go through a NAT gateway or an egress proxy.
- Other regions connect over the provider's backbone with asynchronous replication.
That one minute answers most "where does this live and how does it connect?" questions before they are asked.
Deep Dive: MTU, BGP and why the network is not reliableShow
MTU. Ethernet frames carry at most ~1,500 bytes by default; tunnels reduce this further. Mismatched MTUs cause odd failures where small requests work and large ones hang.
BGP routes the internet. Networks announce which IP ranges they can reach using BGP; anycast announces one range from many places. Wrong announcements have caused large public outages.
The network is not reliable. Packets are dropped, duplicated, reordered and delayed. A request that times out may or may not have been processed. This single fact drives retries, idempotency keys, timeouts and consensus protocols across the rest of this handbook; see Distributed Systems Fundamentals.
Bandwidth-delay product. To keep a link full, the sender must have bandwidth x RTT bytes in flight. A 1 Gbps link with 100 ms RTT needs ~12.5 MB in flight, which is why long-distance transfers need large TCP windows or parallel streams.
Deep Dive: How BGP holds the internet together, and how it breaksShow
The internet is a network of about 75,000-plus independently run networks called autonomous systems (ASes), each identified by an AS number: ISPs, cloud providers, universities, large companies. BGP is how they tell each other which address prefixes they can reach. A route announcement says, in effect, "to reach 192.0.2.0/24, send packets to me, and the path goes through these ASes". Each AS chooses among the routes it hears using local policy (business relationships come first: a customer's route is preferred over a peer's, a peer's over a paid transit provider's) and then mostly the shortest AS path. It then re-announces its choice to its neighbours.
Two properties of BGP explain most of its famous failures:
- Trust by default. Classic BGP accepts announcements without proof that the announcer owns the prefix. In February 2008, Pakistan Telecom announced a more specific route for part of YouTube's address space, intending to block YouTube domestically. The announcement leaked to its upstream provider and spread worldwide, and because routers prefer the most specific prefix, much of the internet sent YouTube traffic to Pakistan for a couple of hours. RPKI (Resource Public Key Infrastructure) now lets owners publish signed statements of which AS may originate their prefixes, and networks that validate them reject such hijacks. Adoption has grown steadily but is not universal.
- Withdrawals are global and fast. On 4 October 2021, a command issued during routine maintenance of Facebook's backbone unintentionally disconnected its data centres. Facebook's DNS servers, designed to withdraw their BGP routes when they cannot reach the data centres, did exactly that, so the rest of the internet could no longer even find Facebook's name servers. Facebook, Instagram and WhatsApp were unreachable for about six hours, and recovery was slowed because the tools engineers would normally use to fix things depended on the same network. Facebook's engineering blog published a detailed account.
Lessons for system designers: keep out-of-band access (management networks and tools that do not depend on the production network), roll out network configuration changes gradually with automatic rollback, and treat DNS and routing as dependencies to be designed for, not background facts.
Deep Dive: MTU, fragmentation and path MTU black holesShow
Every link has an MTU, the largest packet it can carry. Standard Ethernet is 1,500 bytes. Tunnels and overlays (VPNs, IPsec, VXLAN, GRE) add their own headers, so the effective MTU inside them is smaller, often around 1,400-1,450 bytes. Many cloud networks support jumbo frames inside a VPC (AWS supports 9,001 bytes), which reduces per-packet overhead for bulk transfers, but traffic leaving the VPC falls back to 1,500.
When a packet is larger than the next link's MTU, IPv4 can fragment it into pieces that are reassembled at the destination. Fragmentation hurts: losing one fragment loses the whole packet, middleboxes often drop fragments, and reassembly costs memory. IPv6 routers never fragment at all. Instead, TCP uses path MTU discovery: it sends packets with the "don't fragment" flag set, and a router that cannot forward one replies with an ICMP "packet too big" message carrying the smaller MTU. The sender then shrinks its segments.
The classic failure is the PMTU black hole. A firewall blocks all ICMP "for security", so the "packet too big" messages never arrive. Small packets (the TCP handshake, a short request) pass. Large ones (a big response, a TLS certificate chain) are silently dropped. Users see connections that open and then hang. The fixes are to allow the necessary ICMP types through firewalls, and to clamp the TCP MSS on tunnel endpoints so endpoints never send packets too large for the tunnel in the first place. QUIC and modern TCP stacks also probe the path MTU themselves (packetisation-layer PMTUD) instead of relying only on ICMP.
Deep Dive: Inside the server: from the wire to your codeShow
The network does not end at the server's network card. A request still passes through several queues before your handler runs, and each can become the bottleneck:
- The network card (NIC) receives frames into ring buffers in memory. Modern NICs spread flows across many receive queues (RSS, receive-side scaling, hashes the 5-tuple), each handled by a different CPU core, so one core does not have to process every packet.
- The kernel's TCP stack reassembles segments, sends acknowledgements and places data in the socket's receive buffer. New connections wait in the accept queue (its length is set by the
backlogargument tolisten()and a system-wide cap). If the application accepts connections too slowly, the queue fills and new SYNs are dropped, which clients see as connection timeouts even though the server's CPU looks fine. - The application reads from the socket via a thread per connection, or an event loop using
epoll(Linux) orkqueue(BSD) that waits on thousands of sockets at once. Event loops are how servers such as NGINX hold huge numbers of mostly idle connections with modest memory.
At very high packet rates, the per-packet cost of the kernel becomes the limit, and specialised systems bypass parts of it: DPDK moves packet processing into user space, eBPF/XDP runs small programs at the earliest point in the kernel (often used for DDoS filtering and fast load balancing), and RDMA lets machines read each other's memory with no CPU involvement on the remote side, which is common in storage and ML clusters. These are specialist tools, but knowing they exist explains how a single modern load balancer node can process millions of packets per second.
Deep Dive: Data-centre traffic patterns: ECMP, elephants and incastShow
Inside a leaf-spine data centre there are many equal-cost paths between any two servers. Switches spread traffic over them with ECMP (equal-cost multi-path): they hash each packet's 5-tuple (source IP, destination IP, source port, destination port, protocol) and use the hash to pick an uplink. Because the hash is per flow, all packets of one TCP connection take the same path and stay in order, which TCP needs. That choice has three consequences designers run into:
- Elephant flows collide. Most flows are small "mice" (an RPC, a cache read), but a few are huge "elephants" (a backup, a replica rebuild, a shuffle stage in a batch job). Hashing is blind to size, so two elephants can land on the same 100 Gbps uplink while a parallel link sits idle. A single large transfer is therefore often limited to one path's capacity. Tools such as parallel streams (several TCP connections, so several hashes) exist partly to spread one logical transfer across paths.
- Incast. In a scatter-gather request, one aggregator asks 100 servers for a piece of an answer at the same moment (a search query fanning out to index shards, a distributed cache multi-get). All 100 replies arrive at the same switch port in the same few microseconds, overflow its shallow buffer, and many are dropped. TCP's minimum retransmission timeout (commonly 200 ms on Linux) is huge compared with a sub-millisecond data-centre RTT, so a request that should take 1 ms suddenly takes 200 ms. This is the textbook source of mysterious tail latency in fan-out systems. Mitigations are to limit fan-out concurrency, add small random jitter to responses, use protocols tuned for data centres (DCTCP uses ECN marks to slow senders before buffers overflow), and lower retransmission timeouts inside the data centre.
- Microbursts. Average link usage of 30% can hide millisecond bursts at 100% that drop packets. One-minute averages on a dashboard never show them. If you see retransmissions with "idle" links, look at switch buffer drop counters or high-resolution sampling.
A rule of thumb follows for system design: when a design fans out to many servers per request, the network behaviour of the whole fan-out, not one RPC's average latency, sets the tail. Bounding fan-out, hedging slow requests and keeping responses small are network decisions as much as application ones.
Key Takeaways#
- Data moves through layers: application (L7), transport with ports (L4), IP with addresses (L3), and links (L2/L1).
- IPv4 is scarce, so private ranges and NAT are everywhere; IPv6 removes the scarcity.
- Ports identify programs; know the common ones such as 443, 53 and 5432.
- Anycast routes users to the nearest of many servers sharing one IP, used by DNS and CDNs.
- RTT dominates small requests and bandwidth dominates large transfers; keep chatty calls on the same LAN.
- Each layer hides how it keeps its promise: IP gives best-effort packets, TCP gives a reliable ordered stream, and applications add meaning. The higher a device works, the more it costs per request.
- Plan address space generously and without overlaps. A /16 VPC split into per-zone subnets is a common start, and IPv6 removes scarcity.
- A server port can serve millions of connections. The client side runs out of ephemeral ports, so pool connections.
- NAT mappings are state with timeouts. Send keep-alives on idle connections, and remember that many users can share one public IP.
- Anycast plus BGP lets one IP live in many cities, which gives low latency, DDoS absorption and failover by withdrawing routes.
- Latency is propagation, transmission, queuing and processing. One TCP flow is limited by window ÷ RTT and by packet loss, so distance hurts throughput too.
- Link checksums catch accidents on one hop only. Verify integrity end to end with strong checksums, hashes or authenticated encryption.
- Debug connections layer by layer: name resolution, route, port, then timing. A refused connection means nothing listens. A timeout means something drops packets silently.
- Fan-out requests suffer from incast and microbursts that averages hide, so bound fan-out and watch tail latency, not the mean.