PrepStack › CS Fundamentals › Computer Networks

Computer Networks interview cheat sheet

OSI/TCP-IP, IP & subnetting, TCP vs UDP, DNS, HTTP/HTTPS & TLS, what happens on a URL

Networking rounds check that you can explain how bytes actually travel: the layer model, addressing and subnetting, how TCP makes an unreliable network reliable, how DNS and HTTP/TLS work, and what sits in between (NAT, proxies, load balancers, CDNs, firewalls). The favourite closing question is “what happens when you type a URL”, which ties it all together. Read the 15-minute revision first, run the Python demos to make the maths concrete, then switch to Quiz mode and answer out loud.

15-minute revision

  1. OSI has 7 layers (Physical, Data link, Network, Transport, Session, Presentation, Application). TCP/IP has 4 (Link, Internet, Transport, Application). PDUs: bits → frame → packet → segment/datagram → data.
  2. Hub = L1 repeater (one collision domain). Switch = L2, forwards by MAC table. Router = L3, forwards by IP and splits broadcast domains. Gateway = translates between different networks or protocols.
  3. MAC is a 48-bit hardware address used inside one link. IP is a logical, routable address. ARP maps IP → MAC on the local network; the MAC changes at every hop, the IP stays the same (except through NAT).
  4. IPv4 = 32 bits (~4.3 billion addresses), IPv6 = 128 bits. IPv6 has no broadcast, no NAT need, a fixed 40-byte header, and uses NDP instead of ARP.
  5. CIDR /n = n network bits. Hosts = 2^(32−n) − 2. Private ranges: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. Loopback 127.0.0.0/8, link-local 169.254.0.0/16.
  6. NAT/PAT rewrites private IP:port to one public IP with unique ports. DHCP hands out IPs with DORA: Discover, Offer, Request, Ack (UDP 67/68).
  7. ICMP carries errors and diagnostics: ping = Echo Request/Reply; traceroute raises the TTL by 1 each probe and reads the ICMP Time Exceeded replies.
  8. Routing: distance vector (RIP, Bellman-Ford, hop count ≤ 15) vs link state (OSPF, Dijkstra, full map). BGP is path-vector routing between autonomous systems over TCP 179.
  9. TCP = connection-oriented, reliable, ordered, flow + congestion control, 20-byte header. UDP = connectionless, best-effort, 8-byte header, used by DNS, video, games and QUIC.
  10. Handshake: SYN → SYN-ACK → ACK. Teardown: FIN → ACK, FIN → ACK. The side that closes first waits in TIME_WAIT for 2×MSL (60 s on Linux).
  11. Flow control protects the receiver (advertised window rwnd). Congestion control protects the network (cwnd: slow start, AIMD, fast retransmit on 3 duplicate ACKs; CUBIC is the Linux default, BBR models bandwidth and RTT).
  12. DNS: browser/OS cache → recursive resolver → root → TLD → authoritative. Records: A, AAAA, CNAME, MX, NS, TXT, SOA, PTR, SRV. TTL controls caching.
  13. HTTP/1.1 = text, one request at a time per connection. HTTP/2 = binary frames multiplexed on one TCP connection, HPACK. HTTP/3 = HTTP over QUIC (UDP), no TCP head-of-line blocking, 0/1-RTT setup.
  14. TLS 1.3: 1-RTT handshake, ECDHE key exchange only (forward secrecy), AEAD ciphers only. Asymmetric crypto authenticates and agrees a key; fast symmetric crypto encrypts the data.
  15. Forward proxy acts for clients; reverse proxy acts for servers (TLS termination, caching, load balancing). L4 LBs route by IP:port, L7 LBs by HTTP content. CDNs cache at the edge near users.
  16. Attacks: DDoS (volumetric, SYN flood, L7 floods), MITM (ARP spoofing, rogue Wi-Fi; stopped by TLS + HSTS), DNS spoofing/cache poisoning (stopped by DNSSEC, random ports and IDs, DoH/DoT).

Foundations & models

Network types & topologies

Networks are classified by size (PAN, LAN, MAN, WAN) and by how nodes are wired together (topology).

  • LAN covers a home, office or building. It is owned by one organisation, fast and low latency (Ethernet, Wi-Fi).
  • MAN spans a city or campus (for example a city fibre ring). WAN spans countries; the Internet is the biggest WAN. WANs usually run over leased lines, MPLS or the public Internet with VPNs.
  • PAN is a few metres (Bluetooth). WLAN is a wireless LAN. SAN is a storage network.
  • Physical topology is how cables run; logical topology is how data flows. Modern Ethernet is a physical star around a switch.
  • Key trade-off: more redundant links (mesh) means better fault tolerance but more cost and complexity.

Interview questions

  • Difference between LAN, MAN and WAN?
  • How many links does a full mesh of n nodes need?
  • Which topology does a typical office network use?

OSI vs TCP/IP models & encapsulation

OSI is a 7-layer teaching model; TCP/IP is the 4-layer model the Internet really uses. Each layer wraps the data from the layer above in its own header.

  • Each layer offers a service to the layer above and uses the one below. Peers at the same layer on two hosts “talk” through their headers.
  • Encapsulation: data → TCP adds a header (segment) → IP adds a header (packet) → Ethernet adds header + trailer (frame) → bits on the wire. The receiver decapsulates in reverse.
  • PDU names: Application = data/message, Transport = segment (TCP) or datagram (UDP), Network = packet, Data link = frame, Physical = bits.
  • TCP/IP merges OSI layers 5–7 into Application and layers 1–2 into Link (network access). Some books show a 5-layer hybrid that keeps Physical separate.
  • Mnemonic (top-down): All People Seem To Need Data Processing.
  • TLS does not fit neatly: it sits between TCP and HTTP, so people place it at layer 5/6 or call it part of the application layer.

Interview questions

  • Difference between the OSI and TCP/IP models?
  • What is encapsulation?
  • What is MTU and MSS?

Hub vs switch vs router vs gateway

A hub repeats bits, a switch forwards frames by MAC, a router forwards packets by IP, and a gateway connects different networks or protocols.

  • Hub (L1): repeats every signal out of every port. Half duplex, one big collision domain. Obsolete.
  • Switch (L2): learns which MAC is on which port (MAC / CAM table), forwards frames only to that port, floods unknown and broadcast frames. Each port is its own collision domain; all ports share one broadcast domain per VLAN.
  • Router (L3): looks up the destination IP in its routing table (longest prefix match), decrements TTL and forwards. Each interface is a separate broadcast domain.
  • Gateway: any node that connects two different networks. The default gateway is the router a host sends to for non-local destinations. Protocol gateways translate (e.g. VoIP to PSTN).
  • L3 switch = switch hardware that also routes between VLANs at wire speed. Bridge = an early 2-port switch. Access point = bridges Wi-Fi to Ethernet.
  • VLANs split one physical switch into separate L2 networks; trunk ports carry several VLANs with 802.1Q tags.

Interview questions

  • Difference between a hub, a switch and a router?
  • What is a default gateway?
  • Collision domain vs broadcast domain?

Addressing & the network layer

MAC vs IP addresses & ARP

MAC addresses deliver frames on one link; IP addresses deliver packets end to end; ARP finds the MAC for an IP on the local network.

  • MAC: 48 bits written as 6 hex bytes (3c:22:fb:12:34:56). The first 3 bytes are the vendor OUI. It is burned into the NIC but can be changed (phones randomise it per Wi-Fi network for privacy).
  • IP: logical, hierarchical (network + host part) and assigned by configuration or DHCP, so it can be routed and summarised.
  • ARP: the host broadcasts “who has 192.168.1.1?” to ff:ff:ff:ff:ff:ff; the owner replies by unicast with its MAC. The answer is cached in the ARP table for a short time.
  • For a remote destination the host ARPs for the default gateway, not for the remote host.
  • Gratuitous ARP: a host announces its own IP→MAC mapping (used after failover and to detect duplicate IPs). IPv6 replaces ARP with NDP (Neighbor Solicitation/Advertisement over ICMPv6 multicast).
  • ARP has no authentication, which makes ARP spoofing possible.

Interview questions

  • Why do we need both MAC and IP addresses?
  • How does ARP work?
  • What is ARP spoofing and how do you defend against it?

IPv4 vs IPv6

IPv6 replaces 32-bit addresses with 128-bit ones and simplifies the header; both run side by side today (dual stack).

  • IPv4 has about 4.3 billion addresses and has run out at the registries; NAT and CGNAT stretch it.
  • IPv6 addresses are 8 groups of 16-bit hex. Drop leading zeros and replace one run of zero groups with :: (2001:db8::ff00:42:8329).
  • IPv6 has no broadcast (it uses multicast and anycast), and hosts can configure themselves with SLAAC from router advertisements, or use DHCPv6.
  • IPv6 header is a fixed 40 bytes with no checksum and no router fragmentation; options moved to extension headers. IPv4's header is 20–60 bytes.
  • Common IPv6 prefixes: ::1 loopback, fe80::/10 link-local, fc00::/7 unique local (private-like), 2000::/3 global unicast. A LAN subnet is normally a /64.
  • Transition: dual stack (both), tunnelling (6in4) and translation (NAT64/DNS64). Browsers use Happy Eyeballs to race IPv6 and IPv4 connections.

Interview questions

  • Main differences between IPv4 and IPv6?
  • Why was the IPv6 header checksum removed?
  • How does a host get an IPv6 address without DHCP?

IP classes, CIDR, subnetting & private ranges

CIDR writes a network as address/prefix; subnetting borrows host bits to make smaller networks, and the mask tells a host what is local.

  • Classful (historic): A 0–127 /8, B 128–191 /16, C 192–223 /24, D 224–239 multicast, E 240–255 reserved. Replaced by CIDR in 1993 because fixed sizes wasted addresses.
  • /n means the first n bits are the network. Addresses = 2^(32−n); usable hosts = 2^(32−n) − 2 (network and broadcast addresses are reserved). /31 is allowed for point-to-point links and /32 is a single host.
  • Network address = IP AND mask. Broadcast = network OR wildcard (inverted mask).
  • Subnetting: borrowing b host bits gives 2^b subnets. Supernetting / summarisation merges contiguous networks into one route (four /24s → one /22). VLSM uses different prefix lengths in one design.
  • Private (RFC 1918): 10.0.0.0/8, 172.16.0.0/12 (172.16–172.31), 192.168.0.0/16. Not routed on the Internet, so they need NAT.
  • Other special ranges: 127.0.0.0/8 loopback, 169.254.0.0/16 link-local (APIPA, when DHCP fails), 100.64.0.0/10 carrier-grade NAT shared space, 0.0.0.0/0 default route.

Interview questions

  • How many usable hosts are in a /27, and what is its mask?
  • Split 192.168.1.0/24 into 4 equal subnets.
  • What is CIDR and why was it introduced?
  • What is longest prefix match?

NAT, PAT & DHCP (DORA)

NAT lets many private hosts share public IPs by rewriting addresses; DHCP gives hosts their IP, mask, gateway and DNS automatically.

  • Static NAT: one private IP ↔ one public IP (to expose a server). Dynamic NAT: private IPs take public IPs from a pool.
  • PAT / NAT overload / NAPT: many private hosts share one public IP; the router tells flows apart by rewriting the source port and keeping a translation table. This is what every home router does.
  • Inbound traffic works only for flows that started inside, unless you configure port forwarding. This side effect acts like a basic firewall but is not a security feature.
  • NAT breaks end-to-end addressing: peer-to-peer apps need STUN/TURN/ICE (WebRTC) to traverse it. CGNAT adds another NAT layer at the ISP.
  • DHCP DORA: Discover (client broadcast) → Offer (server proposes an IP) → Request (client broadcasts which offer it takes) → Ack (server confirms). UDP ports 67 (server) and 68 (client).
  • Leases expire. The client renews at T1 = 50% of the lease directly with its server and at T2 = 87.5% with any server. A DHCP relay (ip helper-address) forwards broadcasts to a server on another subnet.

Interview questions

  • Difference between NAT and PAT?
  • Explain the DHCP process.
  • Why can't an outside client connect to a server behind NAT, and how do you fix it?

ICMP, ping & traceroute

ICMP is IP's error and diagnostics protocol; ping uses Echo messages and traceroute uses TTL expiry to map the path.

  • ICMP runs directly on IP (protocol number 1; ICMPv6 is 58). It has no ports. Messages have a type and a code.
  • Common types: 0 Echo Reply, 3 Destination Unreachable (code 3 = port unreachable, code 4 = fragmentation needed), 8 Echo Request, 11 Time Exceeded.
  • ping sends Echo Requests and measures round-trip time and loss. No reply does not prove the host is down; firewalls often block ICMP.
  • traceroute sends probes with TTL = 1, 2, 3 … Each router that drops a probe with TTL 0 returns Time Exceeded, revealing itself. Linux/macOS send UDP probes to high ports by default; Windows tracert uses ICMP Echo.
  • ICMP is required for Path MTU Discovery. Blocking all ICMP can cause “black hole” connections that hang on large packets.
  • ICMP, IP, TCP and UDP headers all use the same 16-bit one's-complement Internet checksum.

Interview questions

  • How does traceroute work?
  • Which layer does ping work at, and does it use a port?
  • A host does not answer ping but its website loads. Why?

Routing: static vs dynamic, RIP, OSPF, BGP

Routers pick next hops from a routing table filled by static entries or dynamic protocols: distance vector, link state inside a network, and BGP between networks.

  • Static routes are configured by hand: simple and predictable, but they do not adapt to failures. Dynamic protocols learn routes and converge after changes.
  • Distance vector (RIP): each router tells its neighbours its distances (“routing by rumour”), using Bellman-Ford. RIP's metric is hop count, max 15 (16 = unreachable), updates every 30 s. Problem: slow convergence and count to infinity, reduced by split horizon, poison reverse and hold-down timers.
  • Link state (OSPF, IS-IS): each router floods link-state advertisements so everyone has the same full map, then runs Dijkstra (shortest path first). It converges fast and scales with areas (area 0 is the backbone). OSPF's metric is cost based on bandwidth.
  • IGP vs EGP: RIP, OSPF, IS-IS and EIGRP route inside an autonomous system (AS). BGP is the EGP that routes between ASes and holds the Internet together.
  • BGP is a path-vector protocol over TCP 179. It chooses routes by policy (local preference, AS path length, MED and so on), not just shortest path. eBGP runs between ASes, iBGP within one.
  • Administrative distance decides between protocols for the same prefix (on Cisco: connected 0, static 1, eBGP 20, OSPF 110, RIP 120). Inside a protocol, the lower metric wins.

Interview questions

  • Difference between distance vector and link state routing?
  • What is the count-to-infinity problem?
  • Why does the Internet use BGP instead of OSPF between providers?

Transport layer: TCP & UDP

TCP vs UDP, ports & sockets

TCP gives a reliable, ordered byte stream over a connection; UDP sends independent datagrams with almost no overhead. Ports and sockets identify the process.

  • Port: 16-bit number that identifies a process on a host. Well-known 0–1023 (need root to bind on Unix), registered 1024–49151, dynamic/ephemeral 49152–65535 (Linux uses 32768–60999 by default).
  • A TCP connection is identified by the 5-tuple: protocol, source IP, source port, destination IP, destination port. That is why one server port (443) can hold many thousands of connections.
  • Socket = an OS endpoint for one side (IP + port + protocol). A listening TCP socket creates a new socket per accepted connection.
  • TCP is a byte stream: message boundaries are not kept, so apps need framing (length prefixes, delimiters, HTTP headers). UDP keeps datagram boundaries.
  • Use UDP when latency beats reliability or the app does its own reliability: DNS, VoIP, video calls, games, DHCP, and QUIC (HTTP/3).

Interview questions

  • Difference between TCP and UDP?
  • Why does DNS use UDP?
  • How can a server handle 10,000 clients on port 443?

TCP 3-way handshake, 4-way termination & TIME_WAIT

SYN, SYN-ACK, ACK opens a connection and syncs sequence numbers; FIN/ACK in each direction closes it; the active closer waits in TIME_WAIT.

  • Handshake: client sends SYN (seq = x) → server replies SYN-ACK (seq = y, ack = x+1) → client sends ACK (ack = y+1). Both sides now know each other's initial sequence number (ISN), window and options (MSS, window scale, SACK, timestamps).
  • ISNs are random to stop attackers guessing them and to avoid confusion with old segments. Three messages are the minimum for both sides to confirm both ISNs.
  • Termination: each direction is closed separately (TCP is full duplex). FIN → ACK, then FIN → ACK. The middle two can be combined into FIN-ACK, making it 3 segments. Half-close: one side can stop sending but still receive.
  • TIME_WAIT (active closer): waits 2 × MSL so (1) the final ACK can be resent if lost and (2) delayed old segments die before the same 5-tuple is reused. Linux uses a fixed 60 s.
  • CLOSE_WAIT (passive closer): the peer has sent FIN and the app has not called close() yet. Many CLOSE_WAIT sockets = an application bug (leaked connections).
  • RST aborts a connection at once: sent to a closed port, by a firewall, or when an app closes with unread data. SYN flood attacks fill the half-open queue; SYN cookies defend against it.

Interview questions

  • Explain the TCP 3-way handshake.
  • Why three messages and not two?
  • Why is termination four steps?
  • What is TIME_WAIT and why does it exist?
  • Your server shows thousands of CLOSE_WAIT sockets. What's wrong?

TCP reliability & flow control (sliding window)

Sequence numbers, cumulative ACKs, timers and retransmission make TCP reliable; the receiver's advertised window stops a fast sender from overflowing it.

  • Every byte has a sequence number. The ACK number is the next byte expected (cumulative), so one ACK confirms everything before it.
  • Retransmission timeout (RTO) is computed from smoothed RTT and its variance (SRTT + 4×RTTVAR) and doubles on each timeout (exponential backoff).
  • Fast retransmit: 3 duplicate ACKs mean a segment was probably lost while later ones arrived, so resend it without waiting for the RTO. SACK tells the sender exactly which blocks arrived.
  • Sliding window: the sender may have up to min(rwnd, cwnd) unacknowledged bytes in flight. As ACKs arrive, the window slides forward. Go-Back-N resends everything after a loss; Selective Repeat (what TCP with SACK effectively does) resends only the gaps.
  • Flow control: the receiver advertises rwnd (free buffer space) in every ACK. rwnd = 0 stops the sender, which then sends window probes. The window scale option lifts the 64 KB header limit to about 1 GB.
  • Efficiency tweaks: delayed ACKs (ACK every 2nd segment or after a short delay) and Nagle's algorithm (merge small writes while data is unacknowledged). Their combination can add latency, so interactive apps set TCP_NODELAY.

Interview questions

  • How does TCP guarantee reliable delivery?
  • What is the sliding window protocol?
  • Go-Back-N vs Selective Repeat?

Congestion control & bandwidth-delay product

TCP probes for capacity with a congestion window: exponential slow start, then additive increase, and multiplicative decrease on loss (AIMD). CUBIC and BBR are modern variants.

  • cwnd limits data in flight from the sender's view of the network. Effective window = min(cwnd, rwnd). Initial window is usually 10 MSS (RFC 6928).
  • Slow start: cwnd doubles every RTT (+1 MSS per ACK) until it reaches ssthresh. Congestion avoidance: +1 MSS per RTT (additive increase).
  • On 3 duplicate ACKs (mild loss): ssthresh = cwnd/2, cwnd ≈ ssthresh (fast recovery, Reno). On timeout (severe): ssthresh = cwnd/2, cwnd = 1, back to slow start.
  • AIMD (additive increase, multiplicative decrease) makes competing flows converge to a fair share.
  • CUBIC (Linux default, RFC 9438) grows cwnd as a cubic function of time since the last loss, so it refills big, high-latency pipes quickly. BBR (Google) is model-based: it estimates bottleneck bandwidth and min RTT instead of treating loss as the signal, which helps on lossy links and avoids filling buffers (bufferbloat).
  • ECN lets routers mark packets instead of dropping them, so senders slow down without loss.
  • Bandwidth-delay product (BDP) = bandwidth × RTT = bytes that must be in flight to fill the link. Max throughput of one flow ≈ window / RTT.

Interview questions

  • Difference between flow control and congestion control?
  • Explain slow start and AIMD.
  • What is the bandwidth-delay product and why does it matter?
  • How is BBR different from CUBIC?

Application layer: DNS, HTTP, TLS & WebSockets

DNS: resolution, records, caching & TTL

DNS is the Internet's distributed, cached phone book: a recursive resolver walks root → TLD → authoritative servers and caches each answer for its TTL.

  • Stub resolver (your OS) asks a recursive resolver (ISP, 8.8.8.8, 1.1.1.1), which does the work. It asks the root servers (13 named letters, hundreds of anycast instances), then the TLD servers (.com), then the domain's authoritative server.
  • Recursive query: “give me the final answer”. Iterative query: “tell me who to ask next” (what resolvers do with root and TLD servers).
  • Caching happens everywhere: browser, OS, router, resolver. Each record has a TTL in seconds. Low TTL = faster changes, more queries; high TTL = fewer queries, slower failover. Negative answers (NXDOMAIN) are cached too, per the SOA.
  • Uses UDP/TCP 53. Privacy-focused variants: DoT (TLS, port 853) and DoH (HTTPS, 443).
  • DNSSEC signs records so resolvers can verify they came from the zone owner. It gives integrity, not confidentiality.
  • DNS also powers load balancing and failover: multiple A records (round robin), GeoDNS / latency-based routing, and anycast resolvers.

Interview questions

  • How does DNS resolution work?
  • Difference between A and CNAME records?
  • Recursive vs iterative DNS queries?
  • You changed a DNS record but some users still hit the old server. Why?

HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)

Same HTTP semantics, different wire formats: HTTP/1.1 is text over TCP, HTTP/2 multiplexes binary streams over one TCP connection, and HTTP/3 does it over QUIC on UDP.

  • Semantics (methods, status codes, headers, caching) are shared by all versions (RFC 9110/9111). Only the framing and transport differ.
  • HTTP/1.1: text, persistent connections (keep-alive) by default, but one outstanding request per connection in practice. This causes head-of-line (HOL) blocking, so browsers open ~6 connections per host.
  • HTTP/2: binary frames on many streams in one TCP connection (multiplexing), HPACK header compression, stream priorities. Server push existed but browsers have dropped it; 103 Early Hints replaces it. Browsers require TLS for it (ALPN h2).
  • HTTP/2 still suffers TCP-level HOL blocking: one lost TCP segment stalls every stream until it is retransmitted.
  • HTTP/3 runs on QUIC (RFC 9000/9114): UDP-based, TLS 1.3 built in, streams are independent so loss affects only one stream, 1-RTT setup (0-RTT on resumption), connection migration by connection ID (Wi-Fi → mobile), QPACK headers.
  • Discovery: servers advertise HTTP/3 with an Alt-Svc header or an HTTPS DNS record; clients fall back to HTTP/2 if UDP is blocked.

Interview questions

  • Main differences between HTTP/1.1 and HTTP/2?
  • Why was HTTP/3 built on UDP?
  • What is head-of-line blocking?

HTTPS, TLS 1.3, certificates & crypto basics

HTTPS is HTTP over TLS. TLS uses asymmetric crypto and certificates to authenticate the server and agree a key, then encrypts data with fast symmetric ciphers.

  • Symmetric crypto (AES-GCM, ChaCha20-Poly1305) uses one shared key: fast, used for bulk data. Asymmetric crypto (RSA, ECDSA, Ed25519, ECDHE) uses a public/private key pair: slow, used for key exchange and signatures. TLS combines them.
  • TLS 1.3 (RFC 8446): 1-RTT full handshake, optional 0-RTT on resumption (replayable, so only for idempotent requests). Removed RSA key transport, CBC, RC4, SHA-1 and renegotiation. Key exchange is always (EC)DHE, so it always has forward secrecy.
  • Certificate = the server's public key + domain names (SAN) + validity, signed by a CA. The client builds a chain (leaf → intermediate → root in its trust store) and checks signatures, dates, hostname and revocation (OCSP/CRL).
  • PKI = CAs, trust stores, issuance and revocation. Certificate Transparency logs make every issued cert public. Free automated certs come from ACME CAs like Let's Encrypt; CA/Browser Forum rules are cutting maximum certificate lifetimes in steps, so automate renewal.
  • SNI sends the hostname in the ClientHello so one IP can serve many certs; ALPN negotiates h2 or http/1.1. ECH (Encrypted ClientHello) hides SNI where supported.
  • mTLS: the client also presents a certificate. Common for service-to-service auth (service meshes, zero trust).
  • HSTS tells browsers to always use HTTPS for a domain, blocking SSL-stripping downgrades.

Interview questions

  • Walk through the TLS 1.3 handshake.
  • Symmetric vs asymmetric encryption: why does TLS use both?
  • What is forward secrecy?
  • How does a browser know a certificate is valid?

WebSockets, polling & SSE

WebSocket upgrades an HTTP connection into a long-lived, full-duplex message channel, the usual choice for real-time two-way features.

  • The client sends a normal HTTP/1.1 GET with Upgrade: websocket, Connection: Upgrade and a random Sec-WebSocket-Key. The server answers 101 Switching Protocols with Sec-WebSocket-Accept (a SHA-1/Base64 of key + fixed GUID).
  • After that the TCP connection carries frames (text, binary, ping/pong, close) in both directions. Client-to-server frames are masked to protect against cache poisoning in old proxies.
  • URLs use ws:// and wss:// (TLS, ports 80/443). Always use wss in production.
  • Alternatives: short polling (repeat requests), long polling (server holds the request until data arrives), SSE (text/event-stream, server → client only, auto-reconnect, works well with HTTP/2), WebTransport (over HTTP/3).
  • Scaling concerns: connections are stateful and long-lived, so load balancers need WebSocket support and long idle timeouts, and you need a pub/sub backbone (Redis, Kafka) to fan out messages across server instances.
  • Browsers do not enforce CORS on WebSockets; servers must check the Origin header and authenticate (cookie or token).

Interview questions

  • How does a WebSocket connection start?
  • WebSocket vs HTTP polling vs SSE: when do you use which?
  • How do you scale WebSocket servers horizontally?

Infrastructure, security & the big picture

Proxies, load balancers & CDNs

A forward proxy acts for clients, a reverse proxy acts for servers; load balancers spread traffic over servers; CDNs cache content at edges close to users.

  • Forward proxy: clients are configured to send traffic through it. Used for corporate filtering, egress control, anonymity and caching. The server sees the proxy's IP.
  • Reverse proxy (Nginx, HAProxy, Envoy): clients think it is the server. Used for TLS termination, load balancing, caching, compression, rate limiting, WAF and hiding backends. The original client IP is passed in X-Forwarded-For / Forwarded or the PROXY protocol.
  • L4 load balancer routes by IP and port (TCP/UDP), very fast, does not see HTTP. L7 load balancer reads HTTP (path, host, headers, cookies) for smart routing, retries and sticky sessions.
  • Algorithms: round robin, weighted round robin, least connections, least response time, IP hash and consistent hashing (stickiness that survives scaling). Health checks remove bad backends.
  • CDN: a global network of edge servers (anycast or GeoDNS) that cache static and cacheable content close to users, cutting latency and origin load and absorbing DDoS. Controlled by Cache-Control, TTLs and purges.
  • Global load balancing uses DNS (GeoDNS, latency-based) or anycast (same IP announced from many locations with BGP).

Interview questions

  • Difference between a forward proxy and a reverse proxy?
  • L4 vs L7 load balancing?
  • How does a CDN make a site faster?

VPN, firewalls & common network attacks

Firewalls filter traffic, VPNs tunnel it securely across untrusted networks, and the classic attacks (DDoS, MITM, DNS spoofing) target availability, confidentiality and name resolution.

  • Firewall types: stateless packet filter (rules on IP/port/protocol, e.g. cloud NACLs), stateful (tracks connections so return traffic is allowed automatically, e.g. security groups, iptables conntrack), application / NGFW (inspects L7, app awareness, IPS), WAF (HTTP-specific: SQLi, XSS rules).
  • VPN: an encrypted tunnel that makes a remote network look local. Site-to-site links offices or a VPC; remote access connects a laptop. Protocols: IPsec (L3, IKEv2), WireGuard (UDP, modern, small), OpenVPN / TLS VPNs. Zero-trust access (ZTNA) increasingly replaces broad VPN access.
  • DDoS: volumetric (UDP floods, amplification via DNS/NTP/memcached reflection with spoofed source IPs), protocol (SYN flood), application (HTTP floods). Mitigation: anycast scrubbing/CDN, rate limiting, SYN cookies, autoscaling, BCP 38 egress filtering at ISPs.
  • MITM: attacker relays and reads traffic, via ARP spoofing, rogue Wi-Fi/evil twin, malicious proxies or BGP hijacks. Defence: TLS with certificate validation, HSTS, mTLS, DAI on switches.
  • DNS spoofing / cache poisoning: forged responses make a resolver cache a wrong IP (Kaminsky attack). Defence: random source ports + transaction IDs, DNSSEC, DoH/DoT to trusted resolvers.
  • Others to name: IP spoofing, port scanning (nmap), session hijacking, SSL stripping, BGP hijacking (RPKI helps).

Interview questions

  • Difference between a stateful and a stateless firewall?
  • What is a VPN and how does it work?
  • How would you protect a public API from DDoS?
  • What is DNS spoofing and how is it prevented?

What happens when you type a URL

Parse the URL, resolve the name with DNS, open TCP (or QUIC) and TLS, send the HTTP request through the network stack and routers, then receive, parse and render the response.

  • 1. Browser input: decide if it is a URL or a search; apply HSTS (upgrade to https); check the service worker and HTTP cache.
  • 2. DNS: browser cache → OS cache / hosts file → recursive resolver → root → TLD → authoritative. The result may be a CDN edge IP.
  • 3. Connection: ARP for the default gateway, then the packets are routed hop by hop (NAT at the home router). TCP 3-way handshake to port 443, then TLS 1.3 (SNI, certificate check, ALPN picks h2). With HTTP/3, a single QUIC handshake does both.
  • 4. Request: GET /path with Host, cookies and headers. It passes the CDN / load balancer / reverse proxy, then reaches the app server, which may hit caches and databases.
  • 5. Response: status, headers (Cache-Control, Set-Cookie, Content-Type), compressed body. Redirects (301/302) restart the flow.
  • 6. Render: parse HTML → DOM, CSS → CSSOM, run JS, build the render tree, layout, paint, composite. Extra resources reuse the same HTTP/2 connection.

Interview questions

  • What happens when you type a URL and press Enter?
  • How many round trips before the first byte of HTML?
  • The page is slow to load. How do you find which step is slow?