Skip to content

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.

TopicKey PointsInterview Tip
TCP/IP Stack5 layers: Application -> Transport -> Network -> Data Link -> Physical; data is encapsulated down and decapsulated upWalk through "what happens when you type a URL" layer by layer
TCP vs UDPTCP: reliable, ordered, connection-oriented; UDP: fast, no guarantee, connectionlessName concrete use cases -- TCP for HTTP/payments, UDP for video streaming/gaming
TCP Handshake3-way: SYN -> SYN-ACK -> ACK; teardown: FIN -> ACK -> FIN -> ACKDraw the diagram from memory; mention TIME_WAIT state
HTTP MethodsGET (read), POST (create), PUT (replace), PATCH (partial), DELETE (remove); know idempotencyGET, PUT, DELETE are idempotent; POST and PATCH are not
Status Codes2xx success, 3xx redirect, 4xx client error, 5xx server errorKnow 200, 201, 204, 301, 304, 401, 403, 404, 429, 500, 502, 503
HTTP/1.1 vs 2 vs 31.1: persistent + HOL blocking; 2: multiplexing + HPACK; 3: QUIC (UDP-based)Explain HOL blocking at both HTTP and TCP levels
HTTPS / TLS 1.3Client Hello -> Server Hello + cert -> key exchange (DH) -> encryptedTLS 1.3 is 1-RTT (down from 2-RTT in TLS 1.2)
WebSocketsHTTP upgrade -> full-duplex persistent connectionCompare with SSE (server-only push) and long polling (legacy)
DNS ResolutionBrowser cache -> OS cache -> Resolver -> Root NS -> TLD NS -> Authoritative NSMention 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      Bits

Encapsulation: 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

LayerRoleKey Detail
ApplicationCreates the message (HTTP request, DNS query)Defines the protocol semantics (methods, headers, body)
TransportReliable delivery (TCP) or fast delivery (UDP)Port numbers identify the application; TCP adds sequencing + ack
NetworkRouting across networksIP addresses; routers make hop-by-hop forwarding decisions
Data LinkNode-to-node delivery on the same networkMAC addresses; switches operate here
PhysicalRaw bit transmissionCables, fiber optics, radio signals

2. TCP vs UDP

Comparison Table

DimensionTCPUDP
ConnectionConnection-oriented (handshake required)Connectionless (fire and forget)
ReliabilityGuaranteed delivery (retransmission)No guarantee; packets may be lost
OrderingOrdered (sequence numbers)No ordering guarantee
Flow ControlYes (sliding window)No
Congestion ControlYes (slow start, congestion avoidance)No
OverheadHigher (20-byte header minimum)Lower (8-byte header)
SpeedSlower (reliability costs latency)Faster (no ack waiting)
Use CasesHTTP, HTTPS, SSH, FTP, SMTP, database connectionsVideo 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 packets

TIME_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

MethodPurposeIdempotentSafe (read-only)Request Body
GETRetrieve a resourceYesYesNo
POSTCreate a resource / trigger actionNoNoYes
PUTReplace a resource entirelyYesNoYes
PATCHPartial update of a resourceNoNoYes
DELETERemove a resourceYesNoOptional
HEADGET without body (metadata only)YesYesNo
OPTIONSDiscover allowed methods (CORS preflight)YesYesNo

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

CodeNameMeaningWhen You See It
200OKRequest succeededStandard success response
201CreatedResource createdAfter a successful POST
204No ContentSuccess, nothing to returnAfter a DELETE
301Moved PermanentlyURL changed foreverSEO redirects, HTTP -> HTTPS
302FoundTemporary redirectLogin redirects, A/B testing
304Not ModifiedUse cached versionIf-None-Match / ETag validation
400Bad RequestMalformed requestMissing required fields, invalid JSON
401UnauthorizedNot authenticatedMissing or invalid auth token
403ForbiddenAuthenticated but not authorizedUser lacks permission for this resource
404Not FoundResource does not existWrong URL or deleted resource
409ConflictState conflictDuplicate creation, version mismatch
429Too Many RequestsRate limitedClient exceeded rate limit; check Retry-After header
500Internal Server ErrorServer bugUnhandled exception
502Bad GatewayUpstream server failedReverse proxy (Nginx) got bad response from app server
503Service UnavailableServer overloaded or in maintenanceDeploy in progress, circuit breaker open

HTTP/1.1 vs HTTP/2 vs HTTP/3

FeatureHTTP/1.1HTTP/2HTTP/3
TransportTCPTCPQUIC (UDP-based)
ConnectionsMultiple TCP connections per host (6 typical)Single TCP connection, multiplexed streamsSingle QUIC connection, multiplexed streams
Head-of-Line BlockingYes (request queuing per connection)Solved at HTTP level, still at TCP levelFully solved (independent streams in QUIC)
Header CompressionNoneHPACK (static + dynamic table)QPACK (adapted for out-of-order delivery)
Server PushNoYes (server can push resources before client requests)Removed in practice
BinaryNo (text-based)Yes (binary framing layer)Yes
Connection SetupTCP handshake + TLS handshake (2-3 RTT)Same as 1.10-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

PropertyWhat It Protects Against
EncryptionEavesdropping -- attackers cannot read the data in transit
IntegrityTampering -- data cannot be modified without detection
AuthenticationImpersonation -- 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:

  1. 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).

  2. 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 CertificateVerify message (proves it owns the private key for the certificate).

  3. Key Derivation: Both sides independently compute the same shared secret using the Diffie-Hellman key shares. No secret is ever sent over the wire.

  4. Finished: Both sides send a Finished message 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

  1. Open: HTTP upgrade handshake completes, onopen fires
  2. Message: Either side can send frames at any time, onmessage fires on each
  3. Close: Either side sends a close frame, onclose fires; connection terminates

WebSocket vs SSE vs Long Polling

FeatureWebSocketSSE (Server-Sent Events)Long Polling
DirectionFull-duplex (both ways)Server to client onlySimulated bidirectional
TransportUpgraded TCP connectionRegular HTTP (text/event-stream)Repeated HTTP requests
Protocolws:// / wss://Standard HTTPStandard HTTP
ReconnectionManual (implement heartbeat)Built-in auto-reconnectBuilt-in (new request)
Binary DataYesNo (text only)Yes (base64 in JSON)
Browser SupportAll modern browsersAll modern (no IE)Universal
OverheadLow (2-byte frame header)Low (persistent connection)High (new HTTP request each time)
Load BalancerNeeds sticky sessions or WS-aware LBStandard HTTP LB worksStandard HTTP LB works
Best ForChat, collaborative editing, gamingNotifications, live feeds, stock tickersLegacy 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):

ts
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):

ts
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:

  1. Browser cache: Check if this domain was recently resolved (Chrome: chrome://net-internals/#dns)
  2. OS cache: Check the operating system's DNS cache (/etc/hosts file is also checked)
  3. Recursive resolver: Query the ISP's or configured DNS resolver (e.g., 8.8.8.8, 1.1.1.1)
  4. Root nameserver: Resolver asks one of 13 root nameservers "Who handles .io?"
  5. TLD nameserver: Root points to the .io TLD nameserver, which answers "Who handles temple.io?"
  6. 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

TypeNameValueExample
AAddressIPv4 addressapp.temple.io -> 93.184.216.34
AAAAIPv6 AddressIPv6 addressapp.temple.io -> 2606:2800:220:1:...
CNAMECanonical NameAlias to another domainwww.temple.io -> app.temple.io
MXMail ExchangeMail server for the domaintemple.io -> mail.temple.io (priority 10)
NSNameserverAuthoritative nameservertemple.io -> ns1.cloudflare.com
TXTTextArbitrary 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 ValueUse 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-resolved on Linux, dscacheutil on macOS)
  • Recursive resolver: Respects TTL, may serve stale records with serve-stale extensions
  • 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-Control headers, and CORS preflight details.

Interview Tips Summary

  1. "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.
  2. 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."
  3. 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.
  4. TLS questions: Emphasize that TLS 1.3 achieves 1-RTT, forward secrecy is mandatory, and no secret key is ever transmitted (Diffie-Hellman).
  5. WebSocket vs SSE: If the interviewer asks about real-time, clarify the direction of communication first. Server-only push = SSE is simpler. Bidirectional = WebSocket.
  6. 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.

Frontend interview preparation reference.