06 - Networking Deep Dive
Why This Matters for Temple
Temple (ex-Zomato founding team) builds real-time food delivery infrastructure -- live order tracking, payment webhooks, restaurant dashboards streaming updates. Networking fundamentals (TCP, HTTP evolution, WebSockets, DNS) are not abstract theory here; they directly affect latency, reliability, and user experience at scale.
Quick Reference
Scan this table in 5 minutes before your interview.
| Topic | Key Points | Interview Tip |
|---|---|---|
| TCP/IP Stack | 5 layers: Application -> Transport -> Network -> Data Link -> Physical; data is encapsulated down and decapsulated up | Walk through "what happens when you type a URL" layer by layer |
| TCP vs UDP | TCP: reliable, ordered, connection-oriented; UDP: fast, no guarantee, connectionless | Name concrete use cases -- TCP for HTTP/payments, UDP for video streaming/gaming |
| TCP Handshake | 3-way: SYN -> SYN-ACK -> ACK; teardown: FIN -> ACK -> FIN -> ACK | Draw the diagram from memory; mention TIME_WAIT state |
| HTTP Methods | GET (read), POST (create), PUT (replace), PATCH (partial), DELETE (remove); know idempotency | GET, PUT, DELETE are idempotent; POST and PATCH are not |
| Status Codes | 2xx success, 3xx redirect, 4xx client error, 5xx server error | Know 200, 201, 204, 301, 304, 401, 403, 404, 429, 500, 502, 503 |
| HTTP/1.1 vs 2 vs 3 | 1.1: persistent + HOL blocking; 2: multiplexing + HPACK; 3: QUIC (UDP-based) | Explain HOL blocking at both HTTP and TCP levels |
| HTTPS / TLS 1.3 | Client Hello -> Server Hello + cert -> key exchange (DH) -> encrypted | TLS 1.3 is 1-RTT (down from 2-RTT in TLS 1.2) |
| WebSockets | HTTP upgrade -> full-duplex persistent connection | Compare with SSE (server-only push) and long polling (legacy) |
| DNS Resolution | Browser cache -> OS cache -> Resolver -> Root NS -> TLD NS -> Authoritative NS | Mention TTL, caching layers, and DNS record types (A, AAAA, CNAME) |
1. TCP/IP Stack
The Five Layers
Layer Protocol Examples Data Unit
─────────────────────────────────────────────────────
5. Application HTTP, WebSocket, DNS Data (message)
4. Transport TCP, UDP Segment (TCP) / Datagram (UDP)
3. Network IP (IPv4, IPv6) Packet
2. Data Link Ethernet, Wi-Fi Frame
1. Physical Cables, radio waves BitsEncapsulation: What Happens When You Send Data
Each layer wraps the data from the layer above with its own header.
Application: [ HTTP Request Data ]
|
Transport: [ TCP Hdr | HTTP Request Data ]
|
Network: [ IP Hdr | TCP Hdr | HTTP Data ]
|
Data Link: [ ETH Hdr | IP | TCP | HTTP | ETH Trailer ]
|
Physical: 01101001 01010010 ... (bits on the wire)On the receiving end, each layer strips its header (decapsulation) and passes the payload up.
What Happens at Each Layer
| Layer | Role | Key Detail |
|---|---|---|
| Application | Creates the message (HTTP request, DNS query) | Defines the protocol semantics (methods, headers, body) |
| Transport | Reliable delivery (TCP) or fast delivery (UDP) | Port numbers identify the application; TCP adds sequencing + ack |
| Network | Routing across networks | IP addresses; routers make hop-by-hop forwarding decisions |
| Data Link | Node-to-node delivery on the same network | MAC addresses; switches operate here |
| Physical | Raw bit transmission | Cables, fiber optics, radio signals |
2. TCP vs UDP
Comparison Table
| Dimension | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake required) | Connectionless (fire and forget) |
| Reliability | Guaranteed delivery (retransmission) | No guarantee; packets may be lost |
| Ordering | Ordered (sequence numbers) | No ordering guarantee |
| Flow Control | Yes (sliding window) | No |
| Congestion Control | Yes (slow start, congestion avoidance) | No |
| Overhead | Higher (20-byte header minimum) | Lower (8-byte header) |
| Speed | Slower (reliability costs latency) | Faster (no ack waiting) |
| Use Cases | HTTP, HTTPS, SSH, FTP, SMTP, database connections | Video streaming, VoIP, DNS lookups, online gaming, QUIC |
TCP 3-Way Handshake
Establishes a connection before any data is sent.
Client Server
| |
| ---- SYN (seq=x) ----------> | 1. Client sends SYN with initial sequence number
| |
| <--- SYN-ACK (seq=y, ack=x+1) | 2. Server responds with SYN-ACK
| |
| ---- ACK (ack=y+1) --------> | 3. Client acknowledges; connection established
| |
| ====== DATA TRANSFER ====== |Why 3 steps? Both sides must agree on initial sequence numbers to track data ordering and detect lost packets. Two steps would not confirm that the client received the server's sequence number.
TCP 4-Way Teardown
Either side can initiate the close. Both directions must be closed independently (half-close).
Client Server
| |
| ---- FIN ------------------> | 1. Client says "I'm done sending"
| |
| <--- ACK ------------------- | 2. Server acknowledges
| |
| <--- FIN ------------------- | 3. Server says "I'm done sending too"
| |
| ---- ACK ------------------> | 4. Client acknowledges; connection closed
| |
| [TIME_WAIT: 2*MSL] | Client waits to handle any delayed packetsTIME_WAIT: The client remains in TIME_WAIT for 2x Maximum Segment Lifetime (typically 60s) to ensure any delayed ACK packets are handled. This prevents old packets from a previous connection being misinterpreted in a new one on the same port.
3. HTTP Methods & Status Codes
HTTP Methods
| Method | Purpose | Idempotent | Safe (read-only) | Request Body |
|---|---|---|---|---|
| GET | Retrieve a resource | Yes | Yes | No |
| POST | Create a resource / trigger action | No | No | Yes |
| PUT | Replace a resource entirely | Yes | No | Yes |
| PATCH | Partial update of a resource | No | No | Yes |
| DELETE | Remove a resource | Yes | No | Optional |
| HEAD | GET without body (metadata only) | Yes | Yes | No |
| OPTIONS | Discover allowed methods (CORS preflight) | Yes | Yes | No |
Idempotent means calling the same request multiple times produces the same result. PUT /orders/123 {status: "shipped"} is idempotent -- doing it 10 times still results in status "shipped". POST /orders is not -- doing it 10 times creates 10 orders.
Key Status Codes
| Code | Name | Meaning | When You See It |
|---|---|---|---|
| 200 | OK | Request succeeded | Standard success response |
| 201 | Created | Resource created | After a successful POST |
| 204 | No Content | Success, nothing to return | After a DELETE |
| 301 | Moved Permanently | URL changed forever | SEO redirects, HTTP -> HTTPS |
| 302 | Found | Temporary redirect | Login redirects, A/B testing |
| 304 | Not Modified | Use cached version | If-None-Match / ETag validation |
| 400 | Bad Request | Malformed request | Missing required fields, invalid JSON |
| 401 | Unauthorized | Not authenticated | Missing or invalid auth token |
| 403 | Forbidden | Authenticated but not authorized | User lacks permission for this resource |
| 404 | Not Found | Resource does not exist | Wrong URL or deleted resource |
| 409 | Conflict | State conflict | Duplicate creation, version mismatch |
| 429 | Too Many Requests | Rate limited | Client exceeded rate limit; check Retry-After header |
| 500 | Internal Server Error | Server bug | Unhandled exception |
| 502 | Bad Gateway | Upstream server failed | Reverse proxy (Nginx) got bad response from app server |
| 503 | Service Unavailable | Server overloaded or in maintenance | Deploy in progress, circuit breaker open |
HTTP/1.1 vs HTTP/2 vs HTTP/3
| Feature | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP-based) |
| Connections | Multiple TCP connections per host (6 typical) | Single TCP connection, multiplexed streams | Single QUIC connection, multiplexed streams |
| Head-of-Line Blocking | Yes (request queuing per connection) | Solved at HTTP level, still at TCP level | Fully solved (independent streams in QUIC) |
| Header Compression | None | HPACK (static + dynamic table) | QPACK (adapted for out-of-order delivery) |
| Server Push | No | Yes (server can push resources before client requests) | Removed in practice |
| Binary | No (text-based) | Yes (binary framing layer) | Yes |
| Connection Setup | TCP handshake + TLS handshake (2-3 RTT) | Same as 1.1 | 0-RTT or 1-RTT (QUIC merges transport + TLS) |
Head-of-Line (HOL) Blocking explained:
HTTP/1.1 — Request-level HOL blocking:
┌─────────────────────────────────────┐
│ Connection 1: GET /a → wait → GET /b → wait → GET /c (queued)
│ Connection 2: GET /d → wait → GET /e (queued)
└─────────────────────────────────────┘
HTTP/2 — Multiplexed streams, but TCP-level HOL blocking:
┌─────────────────────────────────────┐
│ Single TCP connection: │
│ Stream 1: [a1][a2][a3] │
│ Stream 2: [b1][b2] ← interleaved on same connection │
│ Stream 3: [c1][c2][c3] │
│ │
│ If TCP packet for [a2] is lost, ALL streams stall │
│ (TCP sees one ordered byte stream) │
└─────────────────────────────────────┘
HTTP/3 — QUIC eliminates TCP HOL blocking:
┌─────────────────────────────────────┐
│ Stream 1: [a1][a2][a3] ← independent, own sequence numbers │
│ Stream 2: [b1][b2] ← loss in stream 1 does NOT block │
│ Stream 3: [c1][c2][c3] stream 2 or 3 │
└─────────────────────────────────────┘4. HTTPS & TLS Handshake
Why HTTPS
| Property | What It Protects Against |
|---|---|
| Encryption | Eavesdropping -- attackers cannot read the data in transit |
| Integrity | Tampering -- data cannot be modified without detection |
| Authentication | Impersonation -- certificate proves the server is who it claims to be |
TLS 1.3 Handshake (Simplified)
TLS 1.3 reduced the handshake from 2 RTT (TLS 1.2) to 1 RTT by combining steps.
Client Server
| |
| ---- Client Hello ----------------> |
| - Supported cipher suites |
| - Client key share (DH) |
| - Supported TLS versions |
| |
| <--- Server Hello + Certificate --- |
| - Chosen cipher suite |
| - Server key share (DH) |
| - Server certificate |
| - Certificate Verify |
| - Finished |
| |
| [Client verifies certificate] |
| [Both derive shared secret from |
| DH key exchange] |
| |
| ---- Finished (encrypted) --------> |
| |
| ======= ENCRYPTED DATA ========= |Step by step:
Client Hello: The client sends supported cipher suites, its Diffie-Hellman key share, and supported TLS versions. In TLS 1.3, the client optimistically sends key material upfront (this is what saves a round trip).
Server Hello + Certificate: The server picks a cipher suite, sends its DH key share, its X.509 certificate (signed by a Certificate Authority), and a
CertificateVerifymessage (proves it owns the private key for the certificate).Key Derivation: Both sides independently compute the same shared secret using the Diffie-Hellman key shares. No secret is ever sent over the wire.
Finished: Both sides send a
Finishedmessage encrypted with the derived keys, confirming the handshake was not tampered with.
TLS 1.3 improvements over TLS 1.2:
- 1-RTT handshake (vs 2-RTT)
- 0-RTT resumption for returning clients (with replay protection trade-offs)
- Removed insecure algorithms (RSA key exchange, CBC mode, RC4, SHA-1)
- Forward secrecy is mandatory (always uses ephemeral DH)
5. WebSockets
How It Works
WebSocket starts as an HTTP request and upgrades to a persistent, full-duplex TCP connection.
Client Server
| |
| GET /chat HTTP/1.1 |
| Upgrade: websocket |
| Connection: Upgrade |
| Sec-WebSocket-Key: x3JJHMb... |
| ----------------------------------->
| |
| HTTP/1.1 101 Switching Protocols |
| Upgrade: websocket |
| Sec-WebSocket-Accept: HSmrc0... |
| <-----------------------------------
| |
| ===== Full-duplex frames ====== |
| <-------- server push ---------- |
| --------- client send --------> |
| <-------- server push ---------- |
| |
| --------- close frame --------> |
| <-------- close frame ---------- |Lifecycle
- Open: HTTP upgrade handshake completes,
onopenfires - Message: Either side can send frames at any time,
onmessagefires on each - Close: Either side sends a close frame,
onclosefires; connection terminates
WebSocket vs SSE vs Long Polling
| Feature | WebSocket | SSE (Server-Sent Events) | Long Polling |
|---|---|---|---|
| Direction | Full-duplex (both ways) | Server to client only | Simulated bidirectional |
| Transport | Upgraded TCP connection | Regular HTTP (text/event-stream) | Repeated HTTP requests |
| Protocol | ws:// / wss:// | Standard HTTP | Standard HTTP |
| Reconnection | Manual (implement heartbeat) | Built-in auto-reconnect | Built-in (new request) |
| Binary Data | Yes | No (text only) | Yes (base64 in JSON) |
| Browser Support | All modern browsers | All modern (no IE) | Universal |
| Overhead | Low (2-byte frame header) | Low (persistent connection) | High (new HTTP request each time) |
| Load Balancer | Needs sticky sessions or WS-aware LB | Standard HTTP LB works | Standard HTTP LB works |
| Best For | Chat, collaborative editing, gaming | Notifications, live feeds, stock tickers | Legacy systems, simple updates |
When to Use Each
- WebSocket: Bidirectional real-time -- chat apps, multiplayer games, collaborative editing, live order tracking with driver sending location updates
- SSE: Server-only push -- notification feeds, live scores, stock prices, CI/CD build logs
- Long Polling: Legacy fallback when WebSocket/SSE are not available, or simple low-frequency updates
Code Example
Server (Node.js with ws library):
import { WebSocketServer, WebSocket } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws: WebSocket) => {
console.log('Client connected');
// Send a welcome message
ws.send(JSON.stringify({ type: 'welcome', message: 'Connected to order tracking' }));
// Handle incoming messages from client
ws.on('message', (data: Buffer) => {
const parsed = JSON.parse(data.toString());
if (parsed.type === 'subscribe_order') {
// In production: register this client for order updates
console.log(`Client subscribed to order ${parsed.orderId}`);
}
});
// Handle disconnect
ws.on('close', () => {
console.log('Client disconnected');
});
// Simulate order status updates
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'location_update',
lat: 19.076 + Math.random() * 0.01,
lng: 72.877 + Math.random() * 0.01,
}));
}
}, 3000);
ws.on('close', () => clearInterval(interval));
});Client (Browser):
const ws = new WebSocket('wss://api.temple.io/tracking');
ws.onopen = () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'subscribe_order', orderId: '12345' }));
};
ws.onmessage = (event: MessageEvent) => {
const data = JSON.parse(event.data);
switch (data.type) {
case 'welcome':
console.log(data.message);
break;
case 'location_update':
updateMapMarker(data.lat, data.lng);
break;
}
};
ws.onclose = (event: CloseEvent) => {
console.log(`Disconnected: code=${event.code} reason=${event.reason}`);
// Implement reconnection with exponential backoff
setTimeout(() => reconnect(), 1000);
};
ws.onerror = (error: Event) => {
console.error('WebSocket error:', error);
};6. DNS Resolution Flow
Step-by-Step Resolution
When you type app.temple.io in the browser:
- Browser cache: Check if this domain was recently resolved (Chrome:
chrome://net-internals/#dns) - OS cache: Check the operating system's DNS cache (
/etc/hostsfile is also checked) - Recursive resolver: Query the ISP's or configured DNS resolver (e.g.,
8.8.8.8,1.1.1.1) - Root nameserver: Resolver asks one of 13 root nameservers "Who handles
.io?" - TLD nameserver: Root points to the
.ioTLD nameserver, which answers "Who handlestemple.io?" - Authoritative nameserver: TLD points to Temple's authoritative NS, which returns the final IP address
Full Flow Diagram
Browser OS Recursive Root TLD (.io) Authoritative
Resolver NS NS NS (temple.io)
| | | | | |
|-- cache miss ----->| | | | |
| |-- cache miss -->| | | |
| | |-- "who has | | |
| | | .io?" ---->| | |
| | | | | |
| | |<-- "ask TLD | | |
| | | at x.x.x"--| | |
| | | | |
| | |-- "who has | |
| | | temple.io?" -------->| |
| | | | |
| | |<-- "ask auth | |
| | | at y.y.y" -----------| |
| | | |
| | |-- "IP for app.temple.io?" --------->|
| | | |
| | |<-- "93.184.216.34" ------------------|
| | |
| |<-- 93.184.216.34| (resolver caches for TTL)
| |
|<-- 93.184.216.34 --| (OS caches)
|
| (browser caches, connects to 93.184.216.34)DNS Record Types
| Type | Name | Value | Example |
|---|---|---|---|
| A | Address | IPv4 address | app.temple.io -> 93.184.216.34 |
| AAAA | IPv6 Address | IPv6 address | app.temple.io -> 2606:2800:220:1:... |
| CNAME | Canonical Name | Alias to another domain | www.temple.io -> app.temple.io |
| MX | Mail Exchange | Mail server for the domain | temple.io -> mail.temple.io (priority 10) |
| NS | Nameserver | Authoritative nameserver | temple.io -> ns1.cloudflare.com |
| TXT | Text | Arbitrary text (verification, SPF, DKIM) | temple.io -> "v=spf1 include:_spf.google.com" |
TTL and Caching
TTL (Time To Live) is set by the authoritative nameserver and tells resolvers how long to cache the record.
| TTL Value | Use Case |
|---|---|
| 60s (short) | Frequently changing IPs, failover scenarios, during migrations |
| 300s (5 min) | Good balance for most applications |
| 3600s (1 hour) | Stable services that rarely change IP |
| 86400s (1 day) | Static infrastructure (MX records, NS records) |
Caching layers:
- Browser: Respects TTL, typically caps at a few minutes
- OS: System-level cache (
systemd-resolvedon Linux,dscacheutilon macOS) - Recursive resolver: Respects TTL, may serve stale records with
serve-staleextensions - CDN edge: CDNs like Cloudflare cache DNS at the edge for faster global resolution
Interview gotcha: If you lower TTL to 60s for a migration, do it 24-48 hours before the actual switch. Old TTL values are still cached by resolvers -- a resolver that cached the record when TTL was 3600s will hold it for up to an hour regardless of the new TTL.
Cross-References
- CORS, caching headers, stale-while-revalidate: See Networking & Caching for browser-level caching strategies,
Cache-Controlheaders, and CORS preflight details.
Interview Tips Summary
- "What happens when you type a URL?" -- Walk through DNS -> TCP handshake -> TLS handshake -> HTTP request -> response -> rendering. This question tests every section in this document.
- TCP vs UDP: Always pair the comparison with concrete use cases. "TCP for payments because we cannot lose data; UDP for live driver location pings where a dropped packet is acceptable."
- HTTP/2 vs HTTP/3: The key insight is that HTTP/2 solved HOL blocking at the HTTP level but not at TCP level. HTTP/3 (QUIC) solves both by using UDP with per-stream sequencing.
- TLS questions: Emphasize that TLS 1.3 achieves 1-RTT, forward secrecy is mandatory, and no secret key is ever transmitted (Diffie-Hellman).
- WebSocket vs SSE: If the interviewer asks about real-time, clarify the direction of communication first. Server-only push = SSE is simpler. Bidirectional = WebSocket.
- DNS: Mention the caching hierarchy and TTL. A common follow-up is "how would you do zero-downtime DNS migration?" -- answer: lower TTL days in advance, switch, monitor, raise TTL back.