Guide / System design Fundamentals
1.2 Networking and protocols
TCP vs UDP, HTTP/1.1 to HTTP/3, DNS, TLS and the real-time options (polling, SSE, WebSockets, WebRTC): what each one costs, when to pick it, and how to say it in an interview.
Interviewers rarely ask “explain TCP”. They ask “why did you pick X here?” and expect one sentence on the trade-off. Every protocol choice in this page is therefore framed as: what it guarantees, what it costs, when you reach for it.
Fundamentals#
1.2.1 What happens when a client calls your API#
A cold request pays for every layer. Knowing the order lets you point at exactly where latency goes.
| Step | What happens | Round trips (RTT) | Why you care |
|---|---|---|---|
| 1. DNS lookup | Name to IP address (browser cache, OS, resolver, authoritative server) | 0 if cached, else 1–3 | TTL controls how fast a failover reaches users |
| 2. TCP handshake | SYN → SYN-ACK → ACK | 1 | A new connection costs a full RTT before any data moves |
| 3. TLS handshake | Agree on keys, verify the certificate | 1 (TLS 1.3), 2 (TLS 1.2) | The reason for keep-alive and connection pools |
| 4. HTTP request/response | Request bytes out, response bytes back | 1 | The only step that does useful work |
On a 150 ms cross-continent link a cold HTTPS request therefore costs roughly 150 (TCP) + 150 (TLS 1.3) + 150 (HTTP) ≈ 450 ms before your code even matters. That single calculation justifies CDNs, regional deployments, connection reuse, HTTP/2 and HTTP/3.
Rule to remember: reuse connections. A warm keep-alive connection pays only step 4.
1.2.2 TCP — reliable, ordered byte stream#
TCP gives the application the illusion of a perfect pipe on top of an unreliable network.
What TCP does for you:
- Connection setup (3-way handshake): client
SYN, serverSYN-ACK, clientACK. Both sides agree on starting sequence numbers. - Reliability: every byte is numbered; the receiver acknowledges; the sender retransmits what is not acknowledged (timeout or three duplicate ACKs).
- Ordering: out-of-order segments are held back and delivered to the application in sequence.
- Flow control: the receiver advertises a window so a fast sender cannot overflow a slow receiver.
- Congestion control: the sender starts slowly (slow start) and grows its sending window until packet loss signals congestion, then backs off. A brand new connection is therefore slow for its first few round trips, which is another reason to keep connections warm.
- Teardown:
FIN/ACKexchange. The side that closes first keeps the socket inTIME_WAIT(typically 60 s) so stray packets are not misread by a new connection.
What it costs:
| Cost | Consequence | Mitigation |
|---|---|---|
| Handshake RTT | Slow first request | Keep-alive, connection pooling, TLS session resumption |
| Head-of-line (HOL) blocking | One lost packet stalls everything behind it, even data that already arrived | HTTP/3 over QUIC, or several connections |
| Per-connection state in the kernel | Millions of idle connections cost memory | Event-driven servers (epoll), tuned limits |
TIME_WAIT / ephemeral-port exhaustion | A client opening and closing thousands of short connections to one server runs out of ports (about 28K–64K per destination) | Connection pooling, keep-alive, widen port range |
| Nagle’s algorithm + delayed ACK | Small writes can be delayed ~40 ms | Set TCP_NODELAY for latency-sensitive RPC |
Operational details interviewers like: a SYN flood attack fills the half-open queue (mitigation: SYN cookies, rate limiting at the edge); TCP keepalive probes detect dead peers behind NATs that silently drop idle connections.
1.2.3 UDP — fire-and-forget datagrams#
UDP adds only ports and a checksum on top of IP. No handshake, no retransmission, no ordering, no congestion control. Each datagram stands alone and may be lost, duplicated or reordered.
What that buys you:
- No connection setup: the first packet already carries data.
- No head-of-line blocking: a lost packet only affects itself.
- Lower overhead (8-byte header versus 20+ for TCP) and message boundaries (one send = one datagram).
- Multicast and broadcast are possible.
- Full control: you can implement exactly the reliability you need on top (this is how QUIC, game netcode and some telemetry systems work).
What you give up: delivery, order, congestion control (an unthrottled UDP sender can flood a link), and NAT or firewall friendliness (many corporate networks block or time out UDP, which is why you need a TCP fallback for WebRTC and QUIC).
1.2.4 TCP vs UDP — the decision#
| Question | TCP | UDP |
|---|---|---|
| Can I lose a message? | No | Yes, or I handle it myself |
| Does order matter? | Yes | No or I add sequence numbers |
| Is a late packet worse than a lost packet? | No | Yes (live audio, video, game state) |
| Do I need many tiny independent messages with no setup? | Wasteful | Good (DNS, metrics) |
| Do I need fairness to other traffic on the network? | Built in | Must build it |
One-line interview rule: use TCP when correctness matters more than freshness; use UDP when freshness matters more than correctness.
| Use case | Protocol | Why |
|---|---|---|
| REST/gRPC APIs, database connections, SSH, SMTP | TCP | Every byte must arrive in order |
| File transfer, S3 downloads | TCP | Integrity over latency |
| DNS queries | UDP (TCP for large responses or zone transfers) | One tiny request and reply; retry is cheaper than a handshake |
| Live video call, voice (WebRTC, VoIP) | UDP (SRTP) | A retransmitted audio frame arrives too late to play; skipping it is better |
| Online games (player position) | UDP | The newest position replaces the old one, so old losses do not matter |
| Video streaming (HLS/DASH) | TCP (HTTP) | Buffering hides latency and CDNs speak HTTP |
| Live streaming at very low latency | UDP-based (WebRTC, SRT, QUIC) | Seconds of buffer are not acceptable |
| Metrics, logs (StatsD) | UDP | Losing 0.1% of samples is fine, and the app must never block |
| HTTP/3 (QUIC) | UDP | Reliability reimplemented per stream without TCP’s HOL blocking |
| Service discovery and gossip (Cassandra, Consul) | UDP/TCP | Small periodic messages tolerate loss |
1.2.5 HTTP: 1.1, 2, 3#
| Version | Transport | Key idea | Weakness |
|---|---|---|---|
| HTTP/1.1 | TCP | Text protocol, keep-alive, one request at a time per connection (browsers open ~6 connections per host) | Application-level head-of-line blocking; large repeated headers |
| HTTP/2 | TCP + TLS (in practice) | Binary framing, multiplexed streams on one connection, header compression (HPACK), server push (rarely used now) | One lost TCP packet stalls all streams (TCP HOL blocking) |
| HTTP/3 | QUIC over UDP | Streams are independent; TLS 1.3 built in (1 RTT, 0-RTT on resume); connection ID survives IP changes (Wi-Fi to 5G) | UDP may be blocked or throttled; more CPU in user space |
Practical advice: terminate HTTP/2 or HTTP/3 at the edge (CDN or load balancer) for clients, and talk HTTP/1.1 or HTTP/2 to backends inside the datacenter. gRPC requires HTTP/2.
1.2.6 DNS#
DNS maps names to addresses. Resolution order: browser cache → OS cache → recursive resolver (ISP or 8.8.8.8) → root → TLD (.com) → authoritative name server.
| Record | Purpose |
|---|---|
| A / AAAA | Name to IPv4 / IPv6 address |
| CNAME | Alias to another name (not allowed at the zone apex) |
| ALIAS / ANAME | CNAME-like at the apex (provider-specific, used for CDNs and load balancers) |
| MX, TXT, NS, SRV | Mail, verification and SPF text, delegation, service location |
Interview-relevant points:
- TTL is the failover speed limit. A 300 s TTL means some clients keep hitting a dead IP for up to five minutes (and some resolvers ignore low TTLs). Lower the TTL before a planned migration, not during an outage.
- DNS load balancing (several A records, round robin) is coarse: no health awareness unless the DNS provider runs health checks, and clients cache.
- GeoDNS / latency-based routing returns the nearest region’s IP. Anycast advertises the same IP from many locations and lets BGP route users to the closest one (used by CDNs and DNS providers).
- DNS is a single point of failure for everything: use two providers for critical domains.
1.2.7 TLS#
TLS gives confidentiality, integrity and server identity. The client verifies the server’s certificate chain, then both sides derive session keys.
- TLS 1.3 needs one round trip (two for 1.2) and supports 0-RTT resumption for repeat visitors (replay risk: only for idempotent requests).
- TLS termination at the load balancer or CDN offloads CPU and centralises certificate rotation. Traffic inside the VPC is then plain HTTP, or re-encrypted to the backend when compliance requires encryption in transit.
- TLS passthrough (L4 load balancer forwards encrypted bytes) keeps end-to-end encryption but the balancer cannot read HTTP.
- mTLS (both sides present certificates) authenticates services to each other; usually provided by a service mesh (Istio, Linkerd).
- Session resumption (tickets) avoids full handshakes for returning clients.
1.2.8 Real-time communication options#
| Option | Direction | Transport | Choose it for | Limits at scale |
|---|---|---|---|---|
| Short polling | Client pulls every N seconds | Plain HTTP | Dashboards where 10–30 s staleness is fine | Wasteful: most responses are empty; load grows with clients, not with events |
| Long polling | Client pulls; server holds the request until data exists | Plain HTTP | Fallback when WebSockets are blocked | A held connection per client; reconnect storm after each event |
| SSE (Server-Sent Events) | Server → client | One long HTTP response, text/event-stream | LLM token streaming, notifications, live scores, progress bars | Text only, one direction, built-in auto-reconnect with Last-Event-ID; passes proxies easily |
| WebSocket | Both directions | HTTP Upgrade, then TCP frames | Chat, collaborative editing, multiplayer, live carts | Stateful: each server holds sockets, so load balancing needs connection-aware routing, heartbeats, and a pub/sub backplane |
| WebRTC | Peer to peer | UDP (SRTP/DTLS) plus signalling over WebSocket/HTTP, STUN/TURN for NAT traversal | Voice and video calls | TURN relays cost bandwidth; group calls need an SFU/MCU media server |
| gRPC streaming | Either/both | HTTP/2 | Internal service streams | Browsers need gRPC-Web |
| MQTT | Pub/sub | TCP, tiny headers | IoT devices on bad networks | Needs a broker cluster |
Decision rule: server only talks → SSE. Both sides talk frequently → WebSocket. Media with sub-second latency → WebRTC. Everything else → plain HTTP with caching.
Scaling WebSockets (asked in chat and notification designs): a connection registry (user_id → gateway node) in Redis, a pub/sub or Kafka layer so any service can reach any user, heartbeats (ping/pong, 20–30 s) to detect dead sockets, reconnect with exponential backoff plus jitter (otherwise 1M clients reconnect in the same second after a deploy), and per-node connection limits (a tuned server holds hundreds of thousands of idle sockets; memory per connection, not CPU, is the limit).
1.2.9 Other terms worth one sentence each#
- Keep-alive and connection pooling: reuse TCP and TLS sessions across requests; the cheapest latency win.
- Proxy vs reverse proxy: a forward proxy sits in front of clients (egress control), a reverse proxy in front of servers (load balancing, TLS, caching).
- NAT: many private hosts share one public IP; it is why servers cannot call back into clients and why long-lived idle connections die without keepalives.
- CDN: caches responses near the user; see Scaling patterns.
- Bandwidth vs latency: bandwidth is how much per second, latency is how long one trip takes. Small API calls are latency-bound; file transfers are bandwidth-bound. More bandwidth does not fix a 150 ms RTT.
Most asked questions#
1. TCP or UDP for a video call, and why? UDP (via WebRTC). Late audio and video are useless, so retransmission is harmful: TCP would stall the whole stream behind one lost packet (head-of-line blocking) and the conversation would lag. The application tolerates small losses with codecs that conceal missing frames, uses sequence numbers and a small jitter buffer, and adapts bitrate from loss and delay feedback. Keep a TCP/TLS fallback (TURN over TCP 443) for networks that block UDP. Signalling (who is calling whom, SDP offers) goes over WebSocket/HTTP, which does need reliability.
2. Why does HTTP/3 run on UDP? TCP is implemented in operating system kernels and middleboxes, so it cannot be changed quickly. HTTP/2 multiplexes streams over one TCP connection, but one lost packet blocks all streams. QUIC rebuilds reliability and congestion control in user space on top of UDP, per stream, so a loss only affects its own stream. It also merges the transport and TLS handshakes (1 RTT, 0 RTT on resume) and uses connection IDs so a phone switching Wi-Fi to cellular keeps its connection.
3. How would you push live updates to a web page? Start from the requirement. Server-to-client only (notifications, order tracking, LLM streaming): SSE, because it is simple, works through proxies and reconnects automatically. Bidirectional low latency (chat, collaborative editing): WebSocket. Updates every 30 s are fine: polling with caching is simplest and scales best. State the scaling cost: stateful connections need a registry and a pub/sub backplane.
4. What happens when you type a URL and press Enter? DNS resolution (cache, resolver, authoritative), TCP handshake, TLS handshake, HTTP request to a CDN or load balancer, which routes to an app server; the app may hit a cache and database; the response flows back, then the browser parses HTML and fetches sub-resources (mostly over an existing HTTP/2 connection). Strong answers add where each layer is cached (DNS cache, CDN, browser cache) and which steps are skipped when connections are warm.
5. Why use keep-alive and connection pools? Each new connection costs a TCP handshake plus a TLS handshake (1–3 RTT) and starts with a small congestion window. Reusing connections removes that cost, and a pool bounds the number of connections to a database or downstream service so you do not exhaust its limits (for Postgres, each connection is a process).
6. How does DNS failover work and how fast is it? Health-checked DNS removes a dead endpoint from answers, but clients and resolvers cache the old answer for the TTL, so recovery is bounded by TTL (often minutes). For fast failover use anycast or a load balancer with a stable IP in front, and use DNS only for coarse regional routing.
7. WebSocket vs SSE? SSE is one-directional (server to client) over plain HTTP, text only, auto-reconnects and works through most proxies and HTTP/2. WebSocket is full-duplex, supports binary, but is stateful, needs sticky routing or a registry, and custom reconnect logic. Pick SSE unless the client really needs to send frequent messages on the same channel (the client can still use normal HTTP POSTs alongside SSE).
8. What is the difference between L4 and L7? L4 works on TCP/UDP connections (IP and port, no knowledge of HTTP); L7 understands HTTP and can route by path, header or cookie. Detailed treatment in Load balancing.
Senior-level questions#
1. “We deploy and 1M WebSocket clients reconnect at once and take the gateway down. What do you change?”
Exponential backoff with full jitter on the client, a server-sent retry-after/drain hint, connection draining during deploys (stop accepting, close sockets gradually with a close code that tells clients to wait), rolling deploys by small percentages, and admission control at the gateway so excess reconnects get a fast rejection rather than a slow overload. Expensive per-connection setup (auth, loading the last N messages) should be cheap or cached because it happens at the reconnect peak.
2. “Our service calls another service over HTTP and p99 is 3× p50. Where do you look?”
New-connection cost (are connections pooled and kept warm, and is the pool large enough or contended?), DNS resolution on every call, TIME_WAIT and ephemeral port exhaustion, retransmits from packet loss (look at TCP retransmit counters), Nagle/delayed ACK interplay (TCP_NODELAY), TLS handshakes after idle timeouts (the load balancer closes idle connections at 60 s while your pool keeps them for 120 s, so the first request after an idle period fails or reconnects: set the client idle timeout below the load balancer’s), and slow starts from congestion control on cold connections.
3. “Why might a load balancer return 502 intermittently under no load?” A classic keep-alive race: the backend closes an idle connection exactly as the balancer reuses it. Set the backend’s keep-alive timeout longer than the balancer’s idle timeout.
4. “Design for users on mobile networks in regions with 400 ms RTT and frequent packet loss.” Minimise round trips (HTTP/3 or at least HTTP/2, TLS 1.3 with 0-RTT, a regional edge/CDN terminating TLS close to the user), batch requests, compress payloads (gzip/brotli, protobuf), make writes idempotent so retries are safe, use offline-first clients with a sync queue, resumable uploads (chunked, e.g. tus protocol), and adaptive bitrate for media. Measure with real-user monitoring by region.
5. “When would you choose gRPC over REST internally, and what breaks?”
gRPC gives a strict schema (protobuf), compact binary encoding, streaming and generated clients over HTTP/2: good for high-volume internal calls. Costs: not browser-native (needs gRPC-Web/proxy), harder to debug with curl, and L4 load balancers balance connections, not requests: because HTTP/2 multiplexes everything onto one long-lived connection, all requests from a client stick to one backend. You need an L7/gRPC-aware balancer, client-side balancing, or periodic connection recycling (max_connection_age).
6. “Why is UDP dangerous to expose publicly?” Amplification DDoS: attackers spoof the victim’s IP in small requests to services that send large replies (DNS, NTP, memcached over UDP). Mitigate by disabling UDP where unneeded, response rate limiting, source validation (QUIC requires address validation before sending large replies) and scrubbing at the edge.
7. “How do you do zero-downtime certificate rotation and DNS migration?” Certificates: overlapping validity, automated issuance (ACME), hot-reload in the proxy, alerts at 30/14/7 days. DNS: lower TTL days in advance, bring up the new endpoint, shift weighted records gradually, keep the old endpoint serving until traffic drains, then raise TTL back.
8. “Your API is behind a CDN. A user changes their password and still sees the old login page state.”
Authenticated and personalised responses must be Cache-Control: private or no-store (and varied correctly with Vary). Cache only what is identical for many users. See Caching.
Quiz#
Answer out loud first, then open the answer.
1. Why does a cold HTTPS request need about three round trips before the response arrives?
One RTT for the TCP handshake, one for the TLS 1.3 handshake (two for TLS 1.2) and one for the HTTP request and response. HTTP/3 on QUIC merges the transport and TLS handshakes; connection reuse removes the handshakes entirely.
2. Give three things TCP provides that UDP does not.
Reliable delivery (acks and retransmission), in-order delivery, and flow and congestion control. It also has connection setup and teardown.
3. A multiplayer game sends player positions 30 times per second. TCP or UDP?
UDP. Each update supersedes the previous one, so a lost packet does not need to be retransmitted, and TCP’s head-of-line blocking would delay fresh data behind a lost old packet. Critical events such as purchases or chat go over a reliable channel.
4. What is head-of-line blocking and which protocol versions suffer from it?
A lost or delayed packet at the front of a queue blocks everything behind it. HTTP/1.1 suffers at the request level, HTTP/2 at the TCP level (all streams share one ordered byte stream), and HTTP/3 avoids it because QUIC streams are independent.
5. SSE or WebSocket for streaming LLM tokens to a browser?
SSE: the traffic is server to client only, it is plain HTTP, reconnects automatically and passes through proxies. The prompt is sent with a normal POST.
6. Why must clients add jitter to reconnect backoff?
Without jitter, all clients that disconnected together retry at the same instants (1 s, 2 s, 4 s…), creating synchronized waves (thundering herd) that overload the server again. Randomising the delay spreads the retries.
7. What does a DNS TTL of 300 seconds mean for failover?
Resolvers and clients may keep using the old IP for up to five minutes after you change the record, so DNS alone gives slow, imprecise failover. Use a stable-IP load balancer or anycast for fast failover.
8. Why do gRPC services often need an L7 load balancer?
gRPC multiplexes all calls over one long-lived HTTP/2 connection. An L4 balancer picks a backend per connection, so one backend receives all of a client’s calls. An L7 or gRPC-aware balancer (or client-side balancing) distributes per request.
9. Where does TLS usually terminate, and what are the trade-offs?
At the CDN or load balancer: it centralises certificates and saves backend CPU, but traffic behind it is plain unless you re-encrypt. Passthrough or mTLS to the backend keeps encryption end to end at the cost of the balancer being unable to inspect or route by HTTP content.
10. Name two reasons a client opening many short connections to one server fails after a while.
Ephemeral port exhaustion from sockets stuck in TIME_WAIT, and the server’s or load balancer’s connection limits. Fix with keep-alive and connection pooling.