Computer Networks

15 Core Networking Concepts — From TCP handshakes to how Google.com loads. Know these, own any networking question.

TCP vs UDP

CoreMost Asked4 min
TCP = reliable, ordered, connection-oriented (phone call). UDP = fast, unordered, connectionless (shouting across the room). TCP guarantees delivery; UDP doesn't care — it just sends.

TCP (Transmission Control Protocol): Before sending data, it sets up a connection (3-way handshake). Every packet is numbered and acknowledged. If a packet is lost, it's retransmitted. Data arrives in order. Think of it as a registered letter — you know it arrived.

UDP (User Datagram Protocol): No connection setup. Just fire packets and hope they arrive. No ordering, no retransmission, no acknowledgement. Think of it as throwing a paper airplane — fast, but no guarantee. Perfect when speed matters more than reliability (video calls, gaming, DNS).

AspectTCPUDP
ConnectionConnection-oriented (handshake)Connectionless
ReliabilityGuaranteed delivery + ACKNo guarantee
OrderingOrdered (sequence numbers)No ordering
SpeedSlower (overhead)Faster (no overhead)
Flow ControlYes (sliding window)No
Header Size20-60 bytes8 bytes
Use CasesHTTP, FTP, Email, SSHDNS, Video, Gaming, VoIP

Key Interview Points

  • TCP uses sequence numbers to order packets and detect loss
  • TCP has congestion control (slow start, congestion avoidance) — prevents flooding the network
  • UDP is used for DNS because queries are small (single packet) and speed matters
  • Video streaming uses UDP because a dropped frame is better than waiting (buffering)
  • HTTP/3 (QUIC) is built on UDP but adds reliability — best of both worlds

Competitive Edge

Mention QUIC protocol (HTTP/3) — Google's answer to TCP's limitations. Built on UDP but adds reliability, multiplexing, and 0-RTT connection setup. It's what YouTube and Google Search actually use today.

OSI Model

CoreTheory5 min
7 layers of networking: Physical → Data Link → Network → Transport → Session → Presentation → Application. Each layer handles a specific job and talks to layers above and below it.
7 Application HTTP, FTP, DNS, SMTP 6 Presentation SSL/TLS, Encryption, JPEG 5 Session Session mgmt, Auth 4 Transport TCP, UDP — Port numbers 3 Network IP, Routers — IP addresses 2 Data Link Ethernet, WiFi — MAC addr 1 Physical Cables, signals, bits Software Layers Hardware Layers

Mnemonic: "Please Do Not Throw Sausage Pizza Away" (bottom to top)

Key Interview Points

  • Layer 4 (Transport): TCP/UDP — identifies processes via port numbers
  • Layer 3 (Network): IP — routing between networks via IP addresses
  • Layer 2 (Data Link): MAC addresses — communication within a local network (switch)
  • Data goes DOWN the stack on sender (encapsulation), UP the stack on receiver (decapsulation)
  • Each layer adds its own header: Application data → Segment → Packet → Frame → Bits

Trap

OSI is a reference model — real internet uses TCP/IP model (4 layers). Nobody implements "pure" OSI. But interviewers love asking about it because it cleanly separates concerns.

TCP/IP Model

Core3 min
The practical model that the real internet uses. 4 layers: Network Access → Internet → Transport → Application. Maps to OSI but combines some layers. This is what actually runs.
TCP/IP LayerOSI EquivalentProtocolsData Unit
ApplicationLayers 5, 6, 7HTTP, DNS, FTP, SMTPData/Message
TransportLayer 4TCP, UDPSegment/Datagram
InternetLayer 3IP, ICMP, ARPPacket
Network AccessLayers 1, 2Ethernet, WiFiFrame

Key Difference from OSI

  • TCP/IP is practical (implemented). OSI is theoretical (reference).
  • TCP/IP merges Session + Presentation + Application into one layer.
  • TCP/IP merges Physical + Data Link into Network Access.
  • TCP/IP was designed first, OSI came later as a generalized model.

Three-Way Handshake

CoreMust Draw4 min
TCP connection setup in 3 steps: SYN → SYN-ACK → ACK. Client says "Hey, let's talk" (SYN), server says "Sure, I'm ready too" (SYN-ACK), client says "Great, let's go" (ACK). Now the connection is established.
CLIENT SERVER 1. SYN (seq=x) 2. SYN-ACK (seq=y, ack=x+1) 3. ACK (ack=y+1) ✓ CONNECTION ESTABLISHED

Both sides exchange sequence numbers so they can track data later.

Key Interview Points

  • SYN: Client picks random sequence number (x), sends to server.
  • SYN-ACK: Server picks its own seq number (y), acknowledges client's with ack=x+1.
  • ACK: Client acknowledges server with ack=y+1. Connection is now full-duplex.
  • Sequence numbers prevent packet confusion and enable ordered delivery.

Competitive Edge

Know SYN flood attack: attacker sends millions of SYNs without completing handshake, filling server's half-open connection table. Defense: SYN cookies — server doesn't store state until ACK is received.

Four-Way Connection Termination

Core3 min
TCP closes connection in 4 steps: FIN → ACK → FIN → ACK. Each side must independently say "I'm done sending." It's 4 steps (not 3) because each direction closes separately — TCP is full-duplex.
CLIENT SERVER 1. FIN 2. ACK Server may still send data 3. FIN 4. ACK ✓ CONNECTION CLOSED

4 steps because each side closes independently. Server may still send data between steps 2 and 3 (half-close).

Key Points

  • After sending FIN, sender enters FIN_WAIT state — can still receive data.
  • After final ACK, client enters TIME_WAIT (2×MSL ≈ 60 sec) to handle delayed packets.
  • This is why you see "address already in use" error — port is still in TIME_WAIT.

HTTP vs HTTPS

Core3 min
HTTP sends data in plaintext — anyone can read it. HTTPS = HTTP + TLS encryption — data is encrypted in transit. HTTPS uses port 443, HTTP uses port 80. No HTTPS = no modern web (browsers mark HTTP as "Not Secure").
AspectHTTPHTTPS
EncryptionNone — plaintextTLS/SSL encrypted
Port80443
CertificateNot neededSSL certificate required
SpeedSlightly fasterTLS handshake adds ~1 RTT
SEOPenalizedGoogle ranks higher
URLhttp://https:// (lock icon)

What HTTPS Protects Against

  • Eavesdropping: Can't read data in transit (encryption)
  • Tampering: Can't modify data without detection (integrity)
  • Impersonation: Certificate proves server identity (authentication)

DNS Working

CoreImportant4 min
DNS = Domain Name System. Translates human-readable domain names (google.com) to IP addresses (142.250.80.46). It's the internet's phone book. Without DNS, you'd memorize IP addresses.

Resolution flow: Browser cache → OS cache → Router cache → ISP's Recursive Resolver → Root DNS → TLD DNS (.com) → Authoritative DNS → IP address returned.

Browser Recursive Resolver Root DNS .com TLD Authoritative google.com 1 2 3 4 5 IP returned 6

Recursive resolver does the heavy lifting — queries Root → TLD → Authoritative on your behalf.

Key Interview Points

  • DNS uses UDP (port 53) because queries are small and speed matters. Falls back to TCP for large responses (zone transfers).
  • TTL (Time To Live): How long DNS records are cached. Low TTL = faster updates, more queries.
  • Record types: A (IPv4), AAAA (IPv6), CNAME (alias), MX (email), NS (nameserver).
  • There are only 13 root server addresses — but hundreds of physical servers via anycast.

Load Balancer

Concept3 min
Distributes incoming traffic across multiple servers so no single server gets overwhelmed. Improves availability, reliability, and scalability. If one server dies, LB routes traffic to healthy ones.

Load Balancing Algorithms

  • Round Robin: Rotate through servers sequentially. Simple, works for equal-capacity servers.
  • Weighted Round Robin: More powerful servers get more requests.
  • Least Connections: Send to server with fewest active connections.
  • IP Hash: Same client IP always goes to same server (session affinity).
  • Layer 4 (Transport): Routes based on IP + port. Fast, no packet inspection.
  • Layer 7 (Application): Routes based on URL, headers, cookies. Smarter but slower.

Competitive Edge

Know the difference between Layer 4 and Layer 7 load balancers. L4 is faster (just forwards TCP connections). L7 understands HTTP (can route /api to backend servers, /images to CDN). AWS ALB = Layer 7, NLB = Layer 4.

Reverse Proxy

Concept3 min
Sits in front of backend servers and forwards client requests to them. Client talks to proxy, proxy talks to server. Client never knows the real server. Used for: load balancing, caching, SSL termination, security.
AspectForward ProxyReverse Proxy
Sits in front ofClientsServers
HidesClient identity from serverServer identity from client
Use caseVPN, anonymity, content filteringLoad balancing, caching, SSL, security
ExampleVPN service, corporate proxyNginx, HAProxy, Cloudflare

Why Use Reverse Proxy

  • SSL Termination: Handle HTTPS at proxy, send plain HTTP to backend (faster for backends).
  • Caching: Cache responses to reduce backend load.
  • Security: Backend servers not exposed to internet. DDoS protection.
  • Compression: Gzip/Brotli responses before sending to client.

SSL/TLS

CoreSecurity4 min
TLS (Transport Layer Security) encrypts data between client and server. SSL is the old name (deprecated). TLS handshake: exchange certificates, agree on encryption method, create session keys. All HTTPS traffic uses TLS.

TLS Handshake flow: (1) Client Hello — supported cipher suites, random number. (2) Server Hello — chosen cipher, server certificate (contains public key). (3) Client verifies certificate with CA. (4) Client sends pre-master secret encrypted with server's public key. (5) Both derive session key. (6) Encrypted communication begins.

Uses asymmetric encryption (RSA/ECDSA) for handshake (slow, secure for key exchange) and symmetric encryption (AES) for actual data transfer (fast).

Key Interview Points

  • SSL is dead. SSL 3.0 was deprecated in 2015. We use TLS 1.2 or TLS 1.3 today.
  • TLS 1.3 reduced handshake from 2-RTT to 1-RTT (and 0-RTT for repeat connections).
  • Certificate Authority (CA) — trusted third party (Let's Encrypt, DigiCert) that vouches for server identity.
  • Asymmetric for key exchange, symmetric for data = best of both worlds.

Cookies vs Sessions

Core3 min
Cookies are stored on the CLIENT (browser). Sessions are stored on the SERVER. Cookie = your movie ticket stub (you carry it). Session = restaurant reservation (restaurant remembers you by your reservation number).
AspectCookiesSessions
StorageClient-side (browser)Server-side (memory/DB/Redis)
Size Limit~4KB per cookieNo practical limit
SecurityLess secure (user can modify)More secure (server-controlled)
ExpirySet by Expires/Max-AgeServer decides (timeout)
ScalabilityStateless (scales easily)Requires shared session store

How They Work Together

  • Server creates session → generates session ID → stores data server-side.
  • Session ID sent to client as a cookie (Set-Cookie: sessionId=abc123).
  • Client sends cookie with every request → server looks up session data.
  • JWT tokens are an alternative — all data in the cookie itself, no server-side storage.

REST APIs

CorePractical3 min
REST = Representational State Transfer. An architectural style for designing APIs using standard HTTP methods. Resources identified by URLs, actions by HTTP verbs (GET, POST, PUT, DELETE). Stateless — each request contains all needed info.
HTTP MethodCRUDExampleIdempotent?
GETReadGET /users/123Yes
POSTCreatePOST /usersNo
PUTUpdate (full)PUT /users/123Yes
PATCHUpdate (partial)PATCH /users/123No
DELETEDeleteDELETE /users/123Yes

REST Principles

  • Stateless: Server stores no client state. Each request is independent.
  • Resource-based: URLs represent resources (/users, /orders), not actions.
  • Use HTTP status codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Server Error.
  • Idempotent: GET, PUT, DELETE give same result when called multiple times.

Trap

POST is NOT idempotent — calling POST /users twice creates TWO users. PUT IS idempotent — calling PUT /users/123 twice produces the same result. This distinction is asked frequently.

WebSocket

Core3 min
Full-duplex, persistent connection between client and server. Unlike HTTP (request-response), WebSocket lets both sides send messages anytime without polling. Starts as HTTP upgrade, then switches protocol.
AspectHTTPWebSocket
CommunicationRequest-Response (half-duplex)Full-duplex (both ways anytime)
ConnectionNew connection per request (or keep-alive)Persistent single connection
OverheadHeaders sent every requestMinimal after handshake
Use CaseREST APIs, web pagesChat, live scores, gaming, trading
Protocolhttp:// or https://ws:// or wss://

Key Points

  • Starts with HTTP Upgrade request: Connection: Upgrade, Upgrade: websocket
  • After upgrade, it's a raw TCP connection — no HTTP overhead.
  • Server can PUSH data without client asking — no polling needed.
  • Use cases: real-time chat, live dashboards, multiplayer games, stock tickers.

Competitive Edge

Know SSE (Server-Sent Events) as alternative — server pushes to client only (one-way), uses regular HTTP, auto-reconnects. Simpler than WebSocket for use cases like live feeds. WebSocket is needed when client must also send frequently (chat, gaming).

CDN (Content Delivery Network)

Concept3 min
Network of servers distributed worldwide that cache and serve content from locations close to users. Instead of every user hitting your origin server in US, users in India get content from a server in Mumbai. Less latency, less origin load.

What CDN Caches

  • Static assets: Images, CSS, JS, fonts, videos — perfect for CDN.
  • Dynamic content: Some CDNs cache API responses with short TTL.
  • Edge computing: Modern CDNs (Cloudflare Workers) run code at edge nodes.

How CDN Works

  • User requests image → DNS resolves to nearest CDN edge server (via anycast/GeoDNS).
  • Cache HIT: Edge has the file → serve instantly. Super fast.
  • Cache MISS: Edge fetches from origin, caches it, then serves. Next user gets cache hit.
  • Providers: Cloudflare, AWS CloudFront, Akamai, Fastly.

Competitive Edge

Know cache invalidation strategies: TTL-based (expire after time), versioned URLs (main.abc123.js — change hash to force new version), purge API (manually invalidate). Versioned URLs are best — infinite cache + instant updates.

How Browser Opens Google.com

CoreThe Big One6 min
This single question tests your knowledge of DNS, TCP, TLS, HTTP, rendering — everything. The answer walks through every layer of networking. Master this, and you've demonstrated complete understanding.

Step 1 — URL Parsing: Browser parses "https://www.google.com" → protocol (HTTPS), host (www.google.com), path (/).

Step 2 — DNS Resolution: Browser needs IP for google.com. Checks: browser cache → OS cache → router cache → ISP resolver → root DNS → .com TLD → Google's authoritative DNS. Gets back something like 142.250.80.46.

Step 3 — TCP Connection: Browser initiates 3-way handshake (SYN → SYN-ACK → ACK) with Google's server on port 443.

Step 4 — TLS Handshake: Since it's HTTPS, TLS handshake happens: exchange certificates, verify server identity, agree on cipher, create session keys. Now all data is encrypted.

Step 5 — HTTP Request: Browser sends GET / HTTP/2 with headers (User-Agent, Accept, Cookies, etc.).

Step 6 — Server Processing: Google's load balancer routes to a backend server. Server processes request, generates HTML response.

Step 7 — HTTP Response: Server sends back 200 OK with HTML content, headers (Content-Type, Cache-Control, etc.).

Step 8 — Browser Rendering: Parse HTML → build DOM tree. Parse CSS → build CSSOM. Combine → Render tree. Layout (calculate positions) → Paint (draw pixels) → Composite (layer management).

Step 9 — Sub-resources: Browser discovers images, CSS, JS files → makes parallel requests for each. JS execution may modify DOM (more rendering).

Step 10 — Page Interactive: All critical resources loaded, JavaScript executed, event listeners attached. Page is fully interactive.

URL Parse + Check HSTS DNS → IP TCP 3-way TLS encrypt HTTP GET / Server Process Render DOM+CSSOM → Pixels Total: ~200-500ms for first meaningful paint

Each step takes milliseconds. The whole flow completes in under a second for cached resources.

Bonus Points to Mention

  • HSTS: Browser remembers sites that require HTTPS — auto-redirects even before DNS.
  • HTTP/2 Multiplexing: Multiple requests over single TCP connection — no head-of-line blocking for resources.
  • Preconnect/Prefetch: Browser may pre-resolve DNS and pre-connect to frequently used domains.
  • Service Workers: Can intercept requests and serve from cache — instant loads for repeat visits.
  • Critical Rendering Path: HTML → DOM, CSS → CSSOM, JS blocks rendering (use async/defer).

Follow-ups

What if the domain is already cached?
DNS step is skipped entirely (saves ~20-100ms). Browser goes straight to TCP connection with cached IP. This is why repeat visits are faster.
What's the difference between HTTP/1.1 and HTTP/2?
HTTP/1.1: One request per TCP connection (or pipelining, poorly supported). HTTP/2: Multiplexing (many requests on one connection), header compression (HPACK), server push. HTTP/3: Uses QUIC (UDP-based), 0-RTT connection, no head-of-line blocking at transport layer.
What happens when you type IP address directly?
DNS step is completely skipped. Browser goes directly to TCP handshake with that IP. But HTTPS may still fail if the certificate doesn't match the IP (certificates are issued for domain names, not IPs usually).

Competitive Edge

When you answer this, draw the flow on a whiteboard. Start with "There are roughly 10 steps" and walk through each. Mention performance optimizations at each step: DNS prefetch, TCP fast open, TLS 1.3 0-RTT, HTTP/2 multiplexing, CDN caching, browser cache, service workers. This shows you don't just know the theory — you think about real-world performance.

Ready to test Networks?

Practice protocols, layers, and browser-flow questions in quiz mode.

Start practice
Home 01. DBMS 02. OOPs 03. Computer Networks 04. Operating System 05. C++ Core 05. Java Core 05. Python Core 06. Puzzles 07. Linux 08. Git 09. SQL 10. Projects 11. System Design 12. DSA Concepts