CNComputer Networks

Block D · Topics 18–21

Application

The protocols you actually build on. DNS and HTTP get asked in every backend interview, and the questions are usually practical: why is this slow, why is this blocked, why did this cache the wrong thing.

18

DNS

recursive resolutionrecord typesTTLcaching
Why it exists

Humans can't remember 142.250.183.14, and more importantly servers move. DNS is a layer of indirection between a stable name and a changeable address — which is what makes load balancing, failover and CDNs possible at all. It's also the world's largest distributed, hierarchically-delegated, cache-everything database, which is why it's a good system-design case study in its own right.

Your OS stub resolver Recursive resolver ISP / 8.8.8.8 · caches Root (13 clusters) "ask the .com servers" .com TLD "ask ns1.google.com" Authoritative NS "A = 142.250.183.14" The whole point: the resolver caches every step for its TTL, so this full walk is rare 1 2 3 Cache layers checked in order: browser → OS → hosts file → recursive resolver → the walk above. "Recursive" = the resolver does the work for you. Those three queries are ITERATIVE — each server returns a referral, not an answer, until the authoritative one does.
Two words that get confused: your query to the resolver is recursive; the resolver's queries outward are iterative.

Record types worth knowing

TypeMapsNote
AName → IPv4The common case
AAAAName → IPv6"Quad A"
CNAMEName → another nameCannot exist at the zone apex — you can't CNAME example.com itself, only www.example.com. Providers offer ALIAS/ANAME as a workaround.
MXDomain → mail serverHas a priority; lower number wins
NSZone → its authoritative serversHow delegation works
TXTArbitrary textSPF, DKIM, DMARC, domain-ownership verification
SOAZone metadataSerial number, refresh intervals, negative-cache TTL
PTRIP → nameReverse lookup; mail servers check it for spam scoring
SRVService → host + portService discovery (SIP, XMPP, Kubernetes)
CAAWhich CAs may issue certsA real defence against mis-issuance

TTL — the whole operational story

A short TTL (60 s) means fast failover and fast changes, but far more query load and slower page loads on cache misses.
A long TTL (24 h) means efficient caching, but you cannot move that server for a day.

The standard practice: lower the TTL to 60 s a day before a planned migration, make the change, verify, then raise it again. And know the limit — resolvers and browsers sometimes ignore short TTLs, so DNS is not a reliable failover mechanism. That's why anycast and health-checked load balancers exist.

DNS is also used as infrastructure plumbing constantly: multiple A records for crude round-robin, GeoDNS returning the nearest region, weighted records for canary rollouts, and CNAMEs pointing at a CDN. Worth mentioning that DNS traditionally runs over UDP port 53, falling back to TCP for large responses or zone transfers — and that DoT/DoH (DNS over TLS/HTTPS) now encrypt it, since plaintext DNS leaked every site you visited to anyone on the path.

Say this

"DNS is a hierarchical, delegated, cache-everything system. Your stub resolver asks a recursive resolver, which — if nothing is cached — asks a root server, gets referred to the .com servers, gets referred to the authoritative name server, and caches every step for its TTL. Your query is recursive; the resolver's are iterative. The operationally important part is TTL: it's the dial between fast failover and query load, and because resolvers sometimes ignore it, DNS should not be your failover mechanism — use anycast or a health-checked load balancer."

19

HTTP/1.1 → 2 → 3

head-of-line blockingmultiplexingHPACKmethods
The through-line

Every HTTP version is an attack on head-of-line blocking at a different layer. Understand that one sentence and the whole evolution is derivable rather than memorised.

HTTP/1.1HTTP/2HTTP/3
Year199720152022
TransportTCPTCPQUIC over UDP
FormatTextBinary framesBinary frames
ConcurrencyOne request at a time per connection → browsers open 6 connections per originMultiplexed streams on one connectionMultiplexed, independent streams
Header compressionNone — cookies resent in full every requestHPACKQPACK
HOL blockingAt the HTTP layerFixed at HTTP, remains at TCPGone at both
Server pushNoYes — and it was removed from browsers, because it usually pushed things already cached. Superseded by 103 Early Hints.Deprecated too
Head-of-line blocking at three layers — the answer that scores

HTTP/1.1: a connection handles one request at a time. Pipelining was specified but broken in practice because responses had to return in order, so a slow first response blocked the rest. Browsers worked around it by opening ~6 parallel connections per origin — which is why "domain sharding" was a real optimisation.

HTTP/2: multiplexes many streams over one connection, so requests no longer queue at the HTTP layer. But TCP delivers a single ordered byte stream, so one lost packet stalls every multiplexed stream until it's retransmitted. Under loss, HTTP/2 can be worse than HTTP/1.1's six independent connections.

HTTP/3: QUIC gives each stream independent loss recovery, so a lost packet only stalls its own stream. That's the whole reason HTTP/3 abandoned TCP.

Methods and semantics

MethodSafeIdempotentCacheable
GETYesYesYes
HEADYesYesYes
OPTIONSYesYesNo
POSTNoNoRarely
PUTNoYesNo
PATCHNoNot inherentlyNo
DELETENoYesNo

Safe means no intended side effect. Idempotent means doing it twice equals doing it once — which is what makes a request safe to retry. Status code classes: 1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error. The ones worth knowing precisely: 301 permanent vs 302/307 temporary (307 preserves the method, 302 historically didn't), 304 Not Modified for conditional requests, 401 unauthenticated vs 403 unauthorised, 429 rate limited, 502 bad gateway vs 504 gateway timeout.

20

Web plumbing

cookiesCORScaching headersWebSocketCDN
Why these four

Cookies, CORS, caching and WebSockets are where networking meets everyday application work — and they're the topics where a wrong mental model produces real bugs. Interviewers ask about them because you'll actually hit them.

Cookies and sessions

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax;
            Max-Age=3600; Path=/; Domain=example.com

HttpOnly   JavaScript cannot read it → mitigates XSS token theft
Secure     only sent over HTTPS
SameSite   Strict  never sent cross-site (strongest, breaks some flows)
           Lax     sent on top-level GET navigation (the modern default)
           None    always sent — REQUIRES Secure. Needed for third-party.
           SameSite is the main structural defence against CSRF.
Server-side sessionJWT (stateless token)
Server storesSession data, keyed by IDNothing
RevocationImmediate — delete the rowHard — valid until expiry unless you keep a denylist, which reintroduces state
ScalingNeeds shared storage (Redis)Any server can verify with the key
SizeSmall ID in the cookieWhole payload on every request
Use whenYou need real logout and session controlShort-lived access tokens across services

The honest summary: JWTs trade revocability for statelessness. The common compromise is short-lived access tokens (minutes) plus a stateful refresh token, so revocation has a bounded window.

CORS

The browser's same-origin policy stops a script on evil.com from reading responses from yourbank.com — because the browser would happily attach your cookies to that request. CORS is the mechanism by which a server opts in to being read cross-origin.

Origin = scheme + host + port. All three must match, so
  https://a.com  vs  http://a.com    → different (scheme)
  https://a.com  vs  https://b.a.com → different (host)
  https://a.com  vs  https://a.com:8080 → different (port)

Simple request (GET/POST with basic headers):
  Browser sends:  Origin: https://app.example.com
  Server replies: Access-Control-Allow-Origin: https://app.example.com
  → without that header, the browser BLOCKS THE SCRIPT FROM READING
    the response. Note the request was still sent and the server still
    processed it — CORS is not server-side access control.

Preflight (PUT/DELETE, custom headers, JSON content type):
  Browser first sends OPTIONS:
    Access-Control-Request-Method: PUT
    Access-Control-Request-Headers: authorization
  Server must reply with Allow-Methods / Allow-Headers, and
    Access-Control-Max-Age so the preflight is cached.
  → an uncached preflight adds a FULL ROUND TRIP to every request.

Two things people get wrong:
· CORS protects the BROWSER's user, not your server. `curl` ignores it
  entirely. It is not authorisation.
· With credentials (cookies) you may NOT use the wildcard
  Access-Control-Allow-Origin: * — you must echo a specific origin
  and set Access-Control-Allow-Credentials: true.

Caching headers

HeaderEffect
Cache-Control: max-age=31536000, immutableCache for a year, never revalidate. Only safe with content-hashed filenames.
Cache-Control: no-cacheConfusingly named: cache it, but revalidate before use.
Cache-Control: no-storeNever write it down anywhere. This is the one for sensitive data.
Cache-Control: privateBrowser may cache; shared caches and CDNs may not.
ETag + If-None-MatchContent fingerprint → server replies 304 with no body if unchanged.
Last-Modified + If-Modified-SinceSame idea, one-second granularity, weaker.
Vary: Accept-EncodingCache separate copies per value of that header. Forgetting Vary is how a CDN serves gzip to a client that can't decompress it.
stale-while-revalidateServe stale immediately, refresh in the background. Excellent for perceived latency.

The standard pattern: HTML gets no-cache so it's always fresh, and assets get content-hashed filenames (app.4f2a1b.js) with a one-year immutable cache. Then a deploy changes the filename, so cache invalidation never needs to happen — the classic hard problem is designed away.

WebSocket, and CDNs

GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
        ↓
HTTP/1.1 101 Switching Protocols

It starts as HTTP (so it traverses port 443 and existing proxies), then
the connection becomes a persistent bidirectional frame-based channel.
Afterwards it is NOT HTTP: no caching, no status codes, no request/response.

Note wss:// is required in practice — plain ws:// is frequently mangled
by proxies, and mixed content is blocked on HTTPS pages.

Use SSE instead when data only flows server→client: it stays plain HTTP,
reconnects automatically, and resumes via Last-Event-ID.

A CDN is the network-layer answer to propagation delay: cache content in PoPs near users, and route them there with anycast or GeoDNS. Beyond caching static files, a modern CDN terminates TLS at the edge (so the expensive handshake round trips are short) and keeps warm connections back to origin — which often speeds up uncacheable dynamic requests too. That last point is a good one to make, because most people only mention static assets.

21

Other protocols

SMTPSPF/DKIM/DMARCSSHFTPNTP

Email — three protocols and an authentication problem

ProtocolPortJob
SMTP25 (server↔server), 587 (client submission, with auth + TLS)Sending — push mail toward the recipient's server
POP3110 / 995Download and typically delete. One device.
IMAP143 / 993Keep mail on the server, sync folders and read state. Multi-device.

SMTP was designed with no authentication whatsoever — anyone can claim to be anyone. Three layered fixes, and being able to distinguish them is a good signal:

  • SPF — a DNS TXT record listing which servers may send for your domain. Checks the envelope sender.
  • DKIM — the sending server signs the message with a private key; the public key is in DNS. Proves the content wasn't altered and came from an authorised signer.
  • DMARC — a policy record saying what to do when SPF/DKIM fail (none / quarantine / reject), plus where to send reports. It also requires alignment — that the authenticated domain matches the visible From: — which is what actually stops display-name spoofing.

SSH, FTP, NTP

ProtocolPortWorth knowing
SSH22Encrypted shell plus port forwarding and SFTP. Key-based auth beats passwords. Host key verification on first connect is what prevents MITM — and blindly accepting it is the weak point. Local (-L) and remote (-R) forwarding effectively make SSH a lightweight VPN.
FTP21 control, 20 dataUses separate control and data connections, which is exactly what NAT and firewalls struggle with. Active mode has the server connect back to the client (blocked by NAT); passive mode has the client connect out (works). Plaintext — use SFTP or FTPS.
NTP123 (UDP)Hierarchical strata; measures round-trip delay to estimate offset. Matters more than it looks: certificate validation, TOTP codes, distributed logs and Kerberos all break on clock skew.
Telnet23Historical, plaintext. Still useful as a crude "is this port open" test — though nc -zv is better.
Say this

"SMTP sends, IMAP or POP3 retrieve — and SMTP has no built-in authentication, which is why spoofing was trivial. The three fixes stack: SPF lists authorised sending servers in DNS, DKIM signs the message with a key published in DNS, and DMARC declares what to do when those fail and requires the authenticated domain to align with the visible From address. Without DMARC alignment you can pass SPF for your own domain while displaying someone else's."