Computer Networks
From physical cables to application protocols — everything you need to understand how the internet works, explained from scratch to advanced, with interview focus.
1What is a Computer Network
A computer network is a collection of interconnected devices — computers, servers, smartphones, printers — that can communicate and share resources. Networks underpin every internet request, every database query over the wire, and every microservice call in your distributed system.
Networks are classified by geographic scale:
- PAN (Personal Area Network) — devices within ~10 meters. Bluetooth headset to phone, USB connection.
- LAN (Local Area Network) — single building or campus. Office WiFi, home network. Typically 10 Mbps–10 Gbps over Ethernet or 802.11.
- MAN (Metropolitan Area Network) — spans a city. Cable TV networks, city-wide fiber rings.
- WAN (Wide Area Network) — spans countries or continents. The internet is the world's largest WAN. ISPs connect LANs to the WAN via routers and long-haul fiber.
Key network components: Hosts (end devices), Switches (connect hosts within a LAN at Layer 2), Routers (connect networks at Layer 3), Modems (modulate/demodulate signals between digital and analog), Access Points (wireless bridge to a wired LAN).
Network performance is measured in four key metrics: Bandwidth (maximum data rate, bits/sec), Throughput (actual achieved data rate), Latency (time for a packet to travel from source to destination), and Packet loss (percentage of packets that never arrive).
2OSI Model — 7 Layers
The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes how different network systems communicate. It divides network communication into 7 ordered layers. Data moves down the layers on the sender and up the layers on the receiver — each layer adds (or removes) a header.
Mnemonic (top to bottom): All People Seem To Need Data Processing (Application, Presentation, Session, Transport, Network, Data Link, Physical).
| # | Layer | Unit | Key Protocols | Devices | Function |
|---|---|---|---|---|---|
| 7 | Application | Data | HTTP, HTTPS, FTP, SMTP, DNS, SSH, SNMP | — | User-facing network services |
| 6 | Presentation | Data | TLS/SSL, JPEG, MPEG, ASCII, UTF-8 | — | Encryption, compression, encoding/translation |
| 5 | Session | Data | NetBIOS, RPC, NFS | — | Establish, maintain, terminate sessions |
| 4 | Transport | Segment | TCP, UDP, SCTP | — | End-to-end delivery, ports, flow control |
| 3 | Network | Packet | IP (v4/v6), ICMP, OSPF, BGP | Router | Logical addressing, routing between networks |
| 2 | Data Link | Frame | Ethernet, WiFi (802.11), ARP, PPP | Switch, Bridge | MAC addressing, framing, error detection |
| 1 | Physical | Bit | Ethernet cables, fiber, USB, Bluetooth radio | Hub, Repeater, NIC | Raw bit transmission over physical medium |
Encapsulation: When you send an HTTP request, the Application layer creates the HTTP message. Transport layer wraps it in a TCP segment (adds source/dest ports, sequence numbers). Network layer wraps that in an IP packet (adds source/dest IP). Data Link layer wraps that in an Ethernet frame (adds MAC addresses). Physical layer converts to bits and transmits. The receiver strips each header in reverse order.
Interview tip: Be able to say what "Layer 4 load balancer" vs "Layer 7 load balancer" means. A Layer 4 LB routes based on IP and port (TCP). A Layer 7 LB routes based on HTTP headers, URL, cookies — it understands application content.
3TCP/IP Model
The TCP/IP model (also called the Internet model) is the practical implementation of networking used on the internet. It collapses the OSI's 7 layers into 4 layers. Unlike OSI (which was designed before protocols), TCP/IP was designed around the protocols already in use.
| TCP/IP Layer | Equivalent OSI Layers | Protocols |
|---|---|---|
| Application | Application + Presentation + Session (7, 6, 5) | HTTP, HTTPS, DNS, FTP, SMTP, SSH, TLS |
| Transport | Transport (4) | TCP, UDP |
| Internet | Network (3) | IPv4, IPv6, ICMP, ARP |
| Network Access (Link) | Data Link + Physical (2, 1) | Ethernet, WiFi, fiber optic |
The TCP/IP model is more pragmatic. OSI is more conceptual and useful for understanding and teaching networking. In practice, engineers say "Layer 3" meaning the Network/Internet layer (IP), and "Layer 4" meaning Transport (TCP/UDP), referencing OSI numbering even when describing TCP/IP behavior.
Data flow example — loading https://example.com:
- Browser (Application) constructs HTTP GET request, TLS encrypts it
- TCP (Transport) segments the data, assigns source port (ephemeral, e.g. 52341) and destination port 443
- IP (Internet) adds source IP and destination IP (resolved via DNS)
- Ethernet (Link) adds MAC addresses for next-hop router, sends bits on wire
- Each router in between strips and re-adds the Link layer header but passes the IP packet unchanged
4IP Addressing & Subnetting
IPv4 uses 32-bit addresses written as four octets (e.g. 192.168.1.100). This gives 2³² = ~4.3 billion addresses — exhausted in 2011. IPv4 addresses are divided into classes (historic) and now managed via CIDR.
IPv6 uses 128-bit addresses written as eight groups of four hex digits (e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334). This gives 2¹²⁸ ≈ 3.4 × 10³⁸ addresses — effectively unlimited. Leading zeros can be omitted; consecutive zero groups collapsed to "::".
Special IPv4 ranges:
- 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 — Private ranges (RFC 1918), not routable on public internet
- 127.0.0.0/8 — Loopback (localhost = 127.0.0.1)
- 169.254.0.0/16 — Link-local, auto-assigned when DHCP fails
- 0.0.0.0 — Unspecified / "any" address (used in bind calls)
- 255.255.255.255 — Broadcast to all hosts on local subnet
CIDR (Classless Inter-Domain Routing): Notation IP/prefix-length (e.g. 10.0.0.0/8). The prefix length tells you how many bits are the network portion. Remaining bits identify hosts within that network.
- /24 → 256 addresses (254 usable), subnet mask 255.255.255.0
- /16 → 65,536 addresses, subnet mask 255.255.0.0
- /8 → 16,777,216 addresses, subnet mask 255.0.0.0
- /30 → 4 addresses (2 usable) — common for point-to-point links
- /32 → single host address
Subnetting example: Given 192.168.10.0/24, split into 4 equal subnets. Each subnet gets /26 (64 addresses, 62 usable): 192.168.10.0/26, 192.168.10.64/26, 192.168.10.128/26, 192.168.10.192/26.
DHCP (Dynamic Host Configuration Protocol) automatically assigns IP addresses, subnet mask, gateway, and DNS server to hosts. Uses UDP ports 67 (server) and 68 (client). DORA process: Discover → Offer → Request → Acknowledge.
NAT (Network Address Translation) allows multiple private IPs to share one public IP. The NAT router maintains a translation table mapping (private IP:port) ↔ (public IP:port). This is why your home devices have 192.168.x.x but the internet sees your ISP's IP.
5Routing & Switching
Switches operate at Layer 2 (Data Link). They learn MAC addresses by inspecting frames — when a frame arrives, the switch maps the source MAC to the incoming port in its MAC address table. Future frames for that MAC are forwarded only to the correct port, not flooded. Switches create separate collision domains per port.
Routers operate at Layer 3 (Network). They route packets between different networks using IP addresses. Each router maintains a routing table: a list of network prefixes and the next-hop router (or outgoing interface) to reach them. Routers decrement the TTL on each IP packet — if TTL reaches 0, the packet is dropped and an ICMP "time exceeded" message is sent back.
Routing algorithms:
- Dijkstra's Algorithm (Link State) — used by OSPF (Open Shortest Path First). Each router knows the full network topology and computes shortest paths. O((V+E) log V). Faster convergence, scales to large networks. Routers exchange Link State Advertisements (LSAs).
- Bellman-Ford (Distance Vector) — used by RIP (Routing Information Protocol). Each router only knows about its neighbors and their distances. Slower convergence, vulnerable to routing loops. Detects negative cycles. O(VE).
- BGP (Border Gateway Protocol) — the routing protocol of the internet. An Exterior Gateway Protocol (EGP) used between Autonomous Systems (ISPs, cloud providers, large enterprises). Path vector protocol — advertises full AS-PATH. Policy-based: routes are chosen based on business relationships, not just shortest path. BGP is what makes the internet work at global scale.
Routing table lookup: Uses Longest Prefix Match — given a destination IP, the router picks the most specific (longest prefix) matching route. 10.0.1.5 matches both 10.0.0.0/8 and 10.0.1.0/24; the /24 wins.
ARP (Address Resolution Protocol) maps IP addresses to MAC addresses within a LAN. Host broadcasts "Who has IP 192.168.1.1?" — the device with that IP replies with its MAC. Cached in the ARP table. ARP only works within a broadcast domain (single subnet).
6TCP vs UDP
TCP (Transmission Control Protocol) provides reliable, ordered, error-checked delivery of a stream of bytes. Before data flows, TCP establishes a connection via the three-way handshake:
- Client → Server: SYN (seq=x)
- Server → Client: SYN-ACK (seq=y, ack=x+1)
- Client → Server: ACK (ack=y+1) + data can begin
To close: four-way termination: FIN → ACK → FIN → ACK. TIME_WAIT state holds the connection open for 2×MSL (Max Segment Lifetime) to ensure the final ACK arrives.
TCP reliability mechanisms:
- Sequence numbers — each byte numbered; receiver reorders out-of-order segments
- Acknowledgements — cumulative ACKs confirm received data; sender retransmits on timeout
- Flow Control — receiver advertises a window size (receive buffer space). Sender can't send more unacknowledged bytes than the window. Prevents fast sender from overwhelming slow receiver.
- Congestion Control — prevents overloading the network. Algorithms: Slow Start (cwnd doubles each RTT until ssthresh), Congestion Avoidance (linear growth), Fast Retransmit (3 duplicate ACKs → retransmit without waiting for timeout), Fast Recovery. TCP Cubic and TCP BBR are modern algorithms used by Linux and Google.
UDP (User Datagram Protocol) is connectionless. No handshake, no guaranteed delivery, no ordering, no flow control. Just send datagrams and hope they arrive. Much lower overhead — 8-byte header vs TCP's 20-byte minimum header.
| Property | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake) | Connectionless |
| Reliability | Guaranteed delivery, retransmit on loss | Best-effort, no retransmit |
| Ordering | In-order delivery | No ordering guarantee |
| Flow Control | Yes (window size) | No |
| Congestion Control | Yes (slow start, AIMD) | No |
| Header Size | 20–60 bytes | 8 bytes |
| Speed | Slower | Faster |
| Use Cases | HTTP, email, file transfer, SSH, databases | DNS, video streaming, VoIP, games, WebRTC |
7HTTP & HTTPS
HTTP (HyperText Transfer Protocol) is the application-layer protocol for the web. It is a request-response protocol: client sends a request, server responds. HTTP is stateless — each request is independent (sessions are added via cookies or tokens).
HTTP Request structure: Method + URL + HTTP version (e.g. GET /index.html HTTP/1.1), followed by headers (Host, Accept, Authorization, Content-Type, …), and optional body (for POST/PUT/PATCH).
HTTP Methods:
- GET — retrieve resource. Idempotent, no body, should not change server state.
- POST — submit data, create resource. Not idempotent. Has body.
- PUT — replace resource at URI. Idempotent.
- PATCH — partial update to resource.
- DELETE — remove resource. Idempotent.
- HEAD — same as GET but only returns headers (useful for checking existence without downloading body).
- OPTIONS — returns supported methods. Used in CORS preflight.
HTTP Status Codes:
- 1xx — Informational: 100 Continue, 101 Switching Protocols (WebSocket upgrade)
- 2xx — Success: 200 OK, 201 Created, 204 No Content
- 3xx — Redirect: 301 Moved Permanently, 302 Found (temp redirect), 304 Not Modified
- 4xx — Client Error: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
- 5xx — Server Error: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout
HTTP/1.1 uses persistent connections (keep-alive) to reuse the TCP connection for multiple requests. But requests are processed serially — head-of-line blocking means one slow response blocks others.
HTTP/2 (2015) introduces multiplexing: multiple streams over a single TCP connection, binary framing (not text), header compression via HPACK, and optional server push. Eliminates application-level HOL blocking, but TCP-level HOL blocking remains.
HTTP/3 (2022) replaces TCP with QUIC (which runs over UDP). QUIC handles multiplexing in the transport layer, so a lost packet only blocks the one stream it belongs to, not all streams. Faster connection setup (0-RTT on resumed connections). TLS 1.3 is built into QUIC.
HTTPS = HTTP over TLS (Transport Layer Security). Before HTTP data is sent, a TLS handshake establishes an encrypted channel: cipher suite negotiation, certificate exchange and verification, key exchange (ECDHE), and session key derivation. All subsequent HTTP data is encrypted and authenticated.
8DNS — Domain Name System
DNS is the internet's distributed phone book — it maps human-readable domain names (google.com) to IP addresses (142.250.80.46). DNS uses UDP port 53 (and TCP 53 for large responses or zone transfers).
DNS Resolution — step by step:
- 1. Browser cache — browser checks its own DNS cache first
- 2. OS cache — OS checks /etc/hosts and the system resolver cache
- 3. Recursive resolver — query goes to your configured resolver (e.g. 8.8.8.8 Google, 1.1.1.1 Cloudflare, or ISP's resolver). Resolver does the heavy lifting on your behalf.
- 4. Root nameserver — resolver queries one of 13 root server clusters. Root server responds with the authoritative TLD nameserver for .com, .org, etc.
- 5. TLD nameserver — resolver queries the .com TLD nameserver. It responds with the authoritative nameserver for the specific domain.
- 6. Authoritative nameserver — resolver queries the domain's own nameserver (set by domain registrar). Returns the actual IP address.
- 7. Cache and return — resolver caches the result for TTL seconds, returns IP to client.
DNS Record Types:
- A — maps domain to IPv4 address (google.com → 142.250.80.46)
- AAAA — maps domain to IPv6 address
- CNAME — alias: maps domain to another domain name (www.example.com → example.com). Cannot coexist with other records at root.
- MX — mail exchange: specifies mail servers for a domain, with priority
- NS — nameserver: identifies authoritative nameservers for a domain
- TXT — arbitrary text: used for SPF, DKIM, domain verification, DMARC
- PTR — reverse DNS: maps IP to domain name (used for spam filtering)
- SOA — Start of Authority: administrative info about the zone (primary NS, contact email, serial, refresh, retry intervals)
- SRV — service location: specifies host and port for a service (_sip._tcp.example.com)
TTL (Time To Live): How long resolvers cache a record. Short TTL (60s) allows fast DNS changes during deployments or failover. Long TTL (86400s = 1 day) reduces DNS load but slows propagation of changes.
DNS Security: DNS was designed without authentication. Attacks include DNS spoofing/cache poisoning (injecting fake records into resolver cache), DNS hijacking (redirecting queries), and DNS amplification DDoS (using open resolvers to reflect traffic). DNSSEC adds cryptographic signatures to records. DoH (DNS over HTTPS) and DoT (DNS over TLS) encrypt DNS traffic to prevent eavesdropping.
9Sockets & Ports
A socket is one endpoint of a two-way communication link between programs on a network. A socket is identified by (IP address, port, protocol). The combination of (src IP, src port, dest IP, dest port, protocol) uniquely identifies a connection — this is called the 5-tuple.
Port ranges:
- 0–1023 — Well-known ports (require root/admin to bind). HTTP:80, HTTPS:443, SSH:22, FTP:20/21, SMTP:25, DNS:53, MySQL:3306, PostgreSQL:5432, Redis:6379, MongoDB:27017
- 1024–49151 — Registered ports. Assigned by IANA to specific services.
- 49152–65535 — Ephemeral (dynamic) ports. OS assigns these to client-side connections temporarily.
Socket states (TCP): LISTEN (server waiting), SYN_SENT, SYN_RECEIVED, ESTABLISHED (data transfer), FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT, CLOSING, LAST_ACK, TIME_WAIT, CLOSED.
Key socket operations: socket() creates a socket. bind() assigns an address and port. listen() marks socket as passive (server). accept() waits for and accepts an incoming connection — returns a new socket for that connection. connect() initiates a connection (client). send()/recv() transfer data. close() closes the socket (sends FIN).
Blocking vs non-blocking: By default sockets are blocking — read() blocks until data arrives. Non-blocking sockets return immediately with EAGAIN if no data. Multiplexing (select, poll, epoll, kqueue) lets one thread wait on multiple sockets simultaneously — the basis of high-performance event-driven servers like Nginx, Node.js, and Redis.
10Firewalls, NAT & VPN
Firewalls filter network traffic based on rules. Types:
- Packet filter (stateless) — inspects each packet independently: src/dest IP, port, protocol. Fast but can't track connection state.
- Stateful inspection — tracks connection state table. Knows if a packet is part of an established connection or a new one. Blocks packets that don't belong to a known connection. Default for modern firewalls.
- Application-layer firewall (WAF) — inspects HTTP content, blocks SQLi, XSS, malicious payloads. Operates at Layer 7.
- Next-Generation Firewall (NGFW) — combines stateful inspection + deep packet inspection + IDS/IPS + application awareness.
NAT (Network Address Translation) translates IP addresses as packets cross the NAT device:
- SNAT (Source NAT) — changes source IP. Used by home routers: your private IP → public IP outbound. Router tracks the mapping and translates response packets back.
- DNAT (Destination NAT) — changes destination IP. Used for port forwarding: external IP:80 → internal server 192.168.1.10:8080. Also how load balancers work at Layer 4.
- PAT (Port Address Translation / IP Masquerade) — many private IPs share one public IP, differentiated by port numbers. This is what consumer NAT routers do.
VPN (Virtual Private Network) creates an encrypted tunnel over a public network, making remote resources appear as if they're on the local network:
- IPSec — Layer 3 VPN protocol. Two modes: Transport (encrypts payload only) and Tunnel (encrypts entire IP packet, adds new IP header). Used for site-to-site VPNs.
- OpenVPN — SSL/TLS-based VPN over UDP or TCP. Highly configurable, crosses firewalls easily.
- WireGuard — modern, lean VPN protocol (~4000 lines of code). UDP-based, uses modern cryptography (Curve25519, ChaCha20). Faster and simpler than IPSec/OpenVPN.
- Split tunneling — route only specific traffic through VPN, not all traffic.
11Wireless Networking
WiFi (IEEE 802.11) is the dominant wireless LAN standard. Key generations:
| Standard | Name | Band | Max Speed | Year |
|---|---|---|---|---|
| 802.11b | — | 2.4 GHz | 11 Mbps | 1999 |
| 802.11g | — | 2.4 GHz | 54 Mbps | 2003 |
| 802.11n | WiFi 4 | 2.4/5 GHz | 600 Mbps | 2009 |
| 802.11ac | WiFi 5 | 5 GHz | 3.5 Gbps | 2013 |
| 802.11ax | WiFi 6/6E | 2.4/5/6 GHz | 9.6 Gbps | 2019 |
| 802.11be | WiFi 7 | 2.4/5/6 GHz | 46 Gbps | 2024 |
2.4 GHz vs 5 GHz: 2.4 GHz has longer range but lower bandwidth and more interference (shared with Bluetooth, microwaves, neighboring WiFi). 5 GHz has shorter range but higher bandwidth and less interference. WiFi 6E adds the 6 GHz band, providing a clean spectrum.
CSMA/CA (Carrier Sense Multiple Access with Collision Avoidance): WiFi can't detect collisions like wired Ethernet (CSMA/CD) because transmitting and listening simultaneously is impractical wirelessly. Instead, before transmitting, a device listens to check if the medium is idle. If busy, it waits a random backoff time before retrying. This avoids (rather than detects) collisions. Optional RTS/CTS (Request to Send / Clear to Send) handshake further reduces the hidden node problem.
WiFi Security: WEP (broken, never use), WPA (TKIP, weak), WPA2 (AES-CCMP, secure, use this minimum), WPA3 (SAE handshake, forward secrecy, required for WiFi 6). Enterprise mode uses RADIUS server for per-user authentication instead of a shared password.
MIMO and beamforming: Modern WiFi uses multiple antennas (MIMO — Multiple Input Multiple Output) to transmit multiple data streams simultaneously. Beamforming directs the signal toward specific clients instead of broadcasting in all directions, improving range and throughput.
12Network Security
TLS/SSL Handshake (TLS 1.3): TLS provides authentication (is this really the server?), encryption (nobody can read the data), and integrity (data hasn't been tampered with).
- 1. ClientHello — client sends supported TLS versions, cipher suites, key shares (ECDHE parameters)
- 2. ServerHello + Certificate — server selects cipher suite, sends its certificate (containing public key, signed by a CA)
- 3. Certificate verification — client validates the certificate chain up to a trusted root CA in the browser's trust store, verifies the domain matches, checks expiry and revocation (OCSP)
- 4. Key exchange — ECDHE (Elliptic Curve Diffie-Hellman Ephemeral) derives a shared secret without transmitting it. Both sides independently compute the same session key.
- 5. Encrypted data — all HTTP data now flows encrypted with the session key (typically AES-256-GCM)
TLS 1.3 does this in 1 RTT (vs TLS 1.2's 2 RTT). 0-RTT resumption allows session resumption with no round trips (with forward-secrecy caveats).
Common Network Attacks:
- Man-in-the-Middle (MITM) — attacker intercepts communication between two parties, can read or modify traffic. Prevented by TLS with proper certificate validation. ARP poisoning is a common MITM vector on LANs.
- DDoS (Distributed Denial of Service) — flood a target with traffic from many sources to exhaust bandwidth or server resources. Types: volumetric (UDP flood, ICMP flood), protocol (SYN flood — exhaust server's half-open connections), application-layer (HTTP flood). Mitigated via anycast, rate limiting, traffic scrubbing, CDN absorption.
- DNS Cache Poisoning — inject false DNS records into a resolver's cache, redirecting users to malicious IPs. Prevented by DNSSEC, randomizing source ports and transaction IDs, and using DoH/DoT.
- SYN Flood — attacker sends many SYN packets with spoofed source IPs, never completing the handshake. Server runs out of half-open connection slots. Mitigated by SYN cookies (server encodes state in ISN instead of keeping it in memory).
- Packet Sniffing — capturing network traffic with tools like Wireshark. On shared media (WiFi, hub-based networks) all traffic is visible. Mitigated by encrypting everything (TLS, VPN).
- IP Spoofing — forging the source IP in packets. Used in DDoS amplification attacks and to evade IP-based access controls. Mitigated by ingress filtering (ISPs drop packets with spoofed source IPs — BCP38).
13Common Interview Questions
These are the computer networking questions most frequently asked in software engineering technical screens and system design rounds at Google, Meta, Amazon, and Microsoft.
Q1: What happens when you type a URL in the browser and press Enter?
Full stack walkthrough: (1) URL parsing — browser extracts protocol (HTTPS), hostname (example.com), path (/page). (2) DNS resolution — browser checks cache, OS cache, then queries the recursive resolver → root nameserver → TLD nameserver (.com) → authoritative nameserver → returns IP address. (3) TCP connection — three-way handshake (SYN → SYN-ACK → ACK) to the IP:443. (4) TLS handshake — client hello (cipher suites, TLS version), server hello + certificate, key exchange (ECDHE), session keys established. (5) HTTP request — GET /page HTTP/2 with headers (Host, Accept-Encoding, Cookie). (6) Server processing — may hit CDN edge first; origin processes request, queries DB, renders response. (7) HTTP response — 200 OK + HTML body. (8) Browser rendering — HTML parsed → DOM, CSS parsed → CSSOM, combined → render tree, layout, paint. Sub-resources (CSS, JS, images) trigger parallel HTTP/2 streams. This answer covers DNS, TCP, TLS, HTTP, and rendering — hitting all five OSI layers — and shows you understand end-to-end request flow.
Q2: What is the difference between TCP and UDP? When would you use each?
TCP (Transmission Control Protocol): connection-oriented, reliable, ordered delivery, flow control (receiver window), congestion control (slow start, AIMD), error correction via retransmission. Overhead: 3-way handshake (~1 RTT), header 20 bytes. Use for: HTTP/HTTPS, SSH, database connections, file transfer — any scenario where every byte must arrive correctly. UDP (User Datagram Protocol): connectionless, unreliable, no ordering, no flow/congestion control. Overhead: 8-byte header, no handshake. Use for: video streaming (a dropped frame is better than buffering), DNS queries (fast, one-shot, retry if needed), online gaming (stale position data is worthless; send fresh), VoIP, QUIC (HTTP/3 runs on UDP with its own reliability layer). Key insight: UDP gives you control — you can implement only the reliability you need, tuned for your use case, rather than TCP's one-size-fits-all guarantees.
Q3: What is the three-way handshake? What is TIME_WAIT?
TCP three-way handshake establishes a connection: (1) Client sends SYN (synchronize) with its initial sequence number (ISN). (2) Server responds SYN-ACK, acknowledges client's ISN, sends its own ISN. (3) Client sends ACK, acknowledging server's ISN. Connection is established; both sides have agreed on sequence numbers for reliable delivery. TIME_WAIT is a state after the active closer sends the final FIN-ACK. It lasts 2×MSL (Maximum Segment Lifetime, typically 60–120 seconds). Purpose: (1) ensures the final ACK reached the server (if it didn't, the server retransmits FIN and the client can re-ACK), (2) prevents old duplicate segments from a previous connection on the same port from being mistaken for a new connection. TIME_WAIT causes problems at high connection rates (running out of ephemeral ports). Solutions: SO_REUSEADDR, TCP connection reuse (keep-alive), reducing MSL via tcp_fin_timeout on Linux.
Q4: What is the difference between HTTP/1.1, HTTP/2, and HTTP/3?
HTTP/1.1: text-based protocol. Head-of-line (HOL) blocking — requests on a connection are served sequentially. Workaround: open 6 parallel connections per domain. Keep-alive reuses TCP connections but still sequential. HTTP/2: binary framing, multiplexing — multiple requests/responses interleaved on a single TCP connection, eliminating application-layer HOL blocking. Header compression (HPACK). Server push (deprecated in practice). Still suffers from TCP-level HOL blocking (one lost packet stalls all streams). HTTP/3: runs on QUIC (UDP-based). QUIC implements streams natively — a lost packet only blocks its own stream, not others. Faster connection setup: TLS 1.3 + QUIC handshake in 1 RTT (0-RTT for resumed connections). Better performance on lossy/mobile networks. Downside: UDP may be blocked by enterprise firewalls; CPU overhead of encryption in user space. Use HTTP/3 for latency-sensitive user-facing products; HTTP/2 is the standard for most APIs.
Q5: Explain the TLS handshake and what a certificate proves.
TLS 1.3 handshake (1 RTT): (1) Client hello — TLS version, supported cipher suites, client random, key share (ECDHE public key). (2) Server hello — chosen cipher suite, server random, server key share, certificate, finished MAC. Both sides compute the shared secret from ECDHE key shares. (3) Client verifies certificate and sends finished. All subsequent messages are encrypted with the derived session keys. A certificate is a signed document binding a public key to a domain name. The Certificate Authority (CA — e.g., Let's Encrypt, DigiCert) signs it with their private key after verifying domain ownership. The browser trusts a built-in set of root CAs. Chain of trust: Root CA → Intermediate CA → Server Certificate. Why this matters for interviews: TLS termination at a load balancer means the backend speaks plaintext — relevant for zero-trust architecture and mTLS for service-to-service authentication.
Q6: What is a CDN and how does it work at the network level?
A CDN (Content Delivery Network) is a geographically distributed network of edge servers that cache and serve content from locations close to users, reducing latency and origin load. How it works: (1) DNS-based routing — CDN's authoritative DNS returns the IP of the nearest edge node (using anycast or latency-based routing). (2) Edge caching — static assets (images, CSS, JS) and optionally dynamic responses are cached at edge PoPs (Points of Presence). Cache hit: response served from edge (~5–20ms RTT). Cache miss: edge fetches from origin, caches, and serves. (3) Anycast — CDNs like Cloudflare use BGP anycast so a single IP is advertised from hundreds of PoPs; routing naturally sends clients to the nearest one. Additional benefits: DDoS mitigation (absorb attack traffic at edge), TLS termination at edge (reducing handshake RTT), HTTP/3 support at edge even if origin only speaks HTTP/1.1. Used by: Cloudflare, Akamai, CloudFront, Fastly.
Q7: What is the difference between a Layer 4 and Layer 7 load balancer?
A Layer 4 load balancer operates at the transport layer (TCP/UDP). It routes packets based on IP address and port without inspecting the payload. It's fast (no TLS termination, no HTTP parsing) and works for any TCP/UDP protocol. Limitations: cannot route based on URL path, HTTP headers, or cookies. Examples: AWS NLB, HAProxy in TCP mode. A Layer 7 load balancer operates at the application layer (HTTP/HTTPS). It terminates TLS, reads the full HTTP request, and routes based on URL path (/api → service A, /static → CDN), Host header (virtual hosting), cookies (sticky sessions), or request content. Enables A/B testing, canary deployments, JWT-based routing. Overhead: TLS termination + HTTP parsing = higher latency (~1ms) and CPU cost. Examples: AWS ALB, Nginx, Envoy, HAProxy in HTTP mode. In interviews: choose L4 for raw throughput (game servers, databases), L7 for HTTP microservices where content-aware routing is needed.
Q8: What is CORS and why does it exist?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different origin (protocol + domain + port) than the one that served the page. Without CORS, a malicious site could make authenticated requests to your bank using the victim's cookies. The browser enforces the Same-Origin Policy (SOP). CORS is the mechanism by which servers explicitly opt-in to allow cross-origin requests. For "simple" requests (GET/HEAD/POST with simple headers), the browser includes Origin header and the server responds with Access-Control-Allow-Origin. For "complex" requests (DELETE, custom headers, JSON body), the browser first sends a preflight OPTIONS request to check permissions, then sends the actual request if allowed. Common interview follow-ups: CORS is a browser restriction — curl and server-to-server requests are unaffected. CORS errors mean the server didn't include the right headers, not that the request was blocked at the network level. Fix: add proper CORS headers on the server (e.g., Access-Control-Allow-Origin: https://yourdomain.com).
Sources & Further Reading
This guide draws on the same authoritative references used in networking coursework and production engineering:
- RFC 791 — Internet Protocol and RFC 793 — Transmission Control Protocol, the IETF source standards for IPv4 and TCP.
- Cloudflare Learning Center — Network Layer, a practical explainer of routing, IP addressing, and the layers of the internet.
- MDN — An Overview of HTTP, the canonical reference for HTTP semantics, headers, and connection behavior.
- Computer Networking: A Top-Down Approach (Kurose & Ross), the standard university textbook this guide's structure follows.
Related Topics