Interview Handbook by Sayed Elmahdy العربية

Topic 24 · Engineering foundations

HTTP & networking

The life of a request, DNS, TCP, TLS, HTTP/1.1 vs 2 vs 3, headers, cookies, proxies.

16 questionsJunior · 6Mid · 6Senior · 410 quiz

Concepts

What you will learn: When a page fails to load or an is slow, the journey from to response: name lookup, connection, , then application. This helps distinguish a timeout from a server rejection and choose a diagnostic tool or communication style for the actual problem.

Before you start: A client sends a request to a server and receives a response; a URL identifies the protocol, host, and path. An address locates a network endpoint, and a port selects a service on that machine. No networking background is required; terms are introduced as the journey unfolds.

Select a term with a dotted underline for its meaning, then continue reading from the same place.

#From typing a URL to rendering a page

A worked example
  1. You enter a store . The browser first needs a destination: resolves the name to records including server addresses, potentially from cache.
  2. On a common -over- path, a connection is established and protects it and authenticates the endpoint before the exchange. Reused connections can avoid setup steps.
  3. The browser receives the response and may fetch more resources. HTTP/3 uses over , so this example is not a mandatory TCP sequence for every HTTP version.

When a page is slow, “the network is slow” is too broad a diagnosis. Separate DNS, connection establishment, server processing and rendering. This is a typical TCP-based HTTPS journey; connection reuse and caches can skip stages, and HTTP/3 uses QUIC instead of TCP.

  1. The browser parses the scheme, host, port and path, checking caches and policies such as and any service worker.
  2. DNS checks local caches and a recursive resolver. Without a cached answer, the resolver may ask a root server about the TLD, the TLD about the authoritative nameserver, and that server for the record, following aliases. This chain is not repeated on every visit.
  3. TCP exchanges SYN, SYN- and ACK. The client generally uses an ephemeral port and HTTPS usually targets port 443.
  4. In TLS 1.3, ClientHello offers capabilities and a key share. The server returns its selection, key share, certificate and authentication messages. The client validates hostname and trust, and both derive encryption keys. ALPN negotiates the HTTP protocol.
  5. The client sends an encrypted HTTP request and a server or proxy returns status, headers and body.
  6. The browser parses and CSS, builds DOM and CSSOM, fetches resources, executes JavaScript, and performs layout and paint. Some work overlaps rather than waiting for every resource.
A full TLS 1.3 handshake typically adds one TLS round trip above a new TCP connection. Resumption and 0-RTT can reduce startup, but early data has replay risks and is unsuitable for an unsafe-to-repeat payment operation.

#Layers, TCP, UDP and sockets

Layers separate responsibilities and explain why successful ping does not prove works. OSI names seven layers: Physical, Data link, Network, Transport, Session, Presentation and Application. A practical / model commonly groups these into Link, Internet, Transport and Application. does not need a forced one-to-one layer mapping.

TCP
DataReliable, ordered byte stream without message boundariesBounded datagrams without delivery or ordering guarantees
ControlRetransmission, flow control and congestion controlNo equivalent delivery guarantees; protocols above it can add them
Examples/1.1 and HTTP/2 commonly, and media protocols

A port is a logical transport endpoint number; a socket is an communication abstraction. A TCP connection is distinguished by source IP, source port, destination IP and destination port together with the protocol. One server can serve many connections on 443 because their client endpoints differ.

One TCP read need not equal one application message; applications need framing. UDP is not always faster; QUIC adds reliable streams and congestion control above it. DNS can also use TCP, so do not reduce a protocol to one port and transport combination.

#HTTP requests, methods and status codes

semantics express intent rather than shape. GET and HEAD are safe and . PUT and DELETE are idempotent in intended effect, not necessarily response. POST is not inherently idempotent; PATCH depends on its operation and design. Safe means no requested business-state change, not an absence of logging or metrics.

FamilyMeaning and examples
1xxInterim information, such as 100 Continue
2xx200 success, 201 created, 202 accepted for later processing, 204 without a body
3xxRedirection or cache validation; 304 does not redirect to a new location
4xx400 invalid request, 401 missing or invalid credentials, 403 forbidden, 404 not found, 409 conflict, 429 rate limit
5xx500 internal failure, 502 invalid upstream response, 503 unavailable, 504 upstream timeout

This raw HTTP/1.1 example illustrates the format; actual wire data needs CRLF and transport for a protected endpoint. Content-Type describes the sent body; Accept describes acceptable response media types.

GET /products/42 HTTP/1.1
Host: store.example.com
Accept: application/json
If-None-Match: "product-v7"

HTTP/1.1 304 Not Modified
ETag: "product-v7"
Cache-Control: public, max-age=60

The client already has the representation matching the ETag, so the server returns 304 without a body. Header names are case-insensitive. Do not blindly retry a POST after timeout: it may have completed while its response was lost. Use an explicitly defined idempotency-key contract when retry must avoid duplicate effects.

#HTTP/1.1, HTTP/2 and HTTP/3 in Kestrel

Loading many resources on one connection benefits from multiplexing. /2 removes HTTP-level , but a lost packet can still stall every stream until recovery. HTTP/3 carries streams over , so loss in one stream need not prevent delivery on another.

HTTP/1.1HTTP/2HTTP/3
TransportTCPTCPQUIC over
RequestsPersistent connections; limited practical pipeliningBinary frames and multiplexed streamsMultiplexed QUIC streams
HeadersText without HPACKHPACKQPACK
LossTCP ordering delays later dataTCP head-of-line blocking across streamsLess cross-stream transport blocking, still shared congestion

This complete Program.cs targets an 10 web project with a configured default certificate. HTTP/3 additionally needs a supported platform and MsQuic, plus an open UDP port.

using Microsoft.AspNetCore.Server.Kestrel.Core;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(5001, listen =>
    {
        listen.Protocols = HttpProtocols.Http1AndHttp2AndHttp3; // (1)
        listen.UseHttps(); // (2)
    });
});
var app = builder.Build();
app.MapGet("/", (HttpContext context) => context.Request.Protocol); // (3)
app.Run();
🧾 Code walkthrough
  1. (1) Protocols are allowed, but the client, proxy and must support them.
  2. (2) supports negotiation; HTTP/3 uses TLS 1.3 within QUIC. Keep certificate passwords outside source.
  3. (3) The result verifies the protocol seen by Kestrel. A public edge may use HTTP/3 with the client and HTTP/1.1 with the application.

HTTP semantics remain consistent across versions. HTTP/3 is not universally faster, and some networks block UDP, so fallback matters. See the HTTP/3 specification and Kestrel requirements.

#Keep-alive, connection pooling and socket exhaustion

and handshakes cost time. /1.1 reuses connections by default, while HTTP/2 can share a connection across streams. HTTP keep-alive differs from TCP keepalive probes used to detect dead idle connections. Creating a new HttpClient and handler per request wastes pools and can exhaust ephemeral ports under load.

This registration assumes a 10 application with and Microsoft.Extensions.Http. Resolve clients through the factory; do not retain a factory-created client indefinitely if relying on handler rotation for refresh.

builder.Services.AddHttpClient("catalog", client =>
{
    client.BaseAddress = new Uri("https://catalog.example.com");
    client.Timeout = TimeSpan.FromSeconds(10); // (1)
}).ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(5), // (2)
    MaxConnectionsPerServer = 20 // (3)
});

// Inside a service receiving IHttpClientFactory factory:
using var client = factory.CreateClient("catalog");
using var response = await client.GetAsync("/products/42", cancellationToken);
response.EnsureSuccessStatusCode();
🧾 Code walkthrough
  1. (1) A timeout bounds waiting, alongside caller cancellation.
  2. (2) Aging connections retire so new connections resolve DNS again. HttpClient does not track DNS per request; five minutes is illustrative and environment dependent.
  3. (3) This caps connections, not necessarily requests when multiplexing is used. Apply appropriate concurrency limits too.

A long-lived HttpClient with a suitable SocketsHttpHandler connection lifetime is another valid pattern. Complete or dispose responses, especially streaming ones, to release resources. Keep retries bounded and safe for side effects rather than treating every timeout as automatically retryable. See HttpClient guidelines.

#Cookies, tokens and CORS

A cookie is a browser storage and transport mechanism; a represents identity or authority and can itself be stored in a cookie. They are not mutually exclusive alternatives. Secure restricts cookie transmission to , HttpOnly prevents JavaScript reads, and SameSite constrains cross-site sending. HttpOnly does not stop from issuing requests with the user's privileges.

This raw response header uses a placeholder session value; the actual value must come from authentication infrastructure.

Set-Cookie: session=SESSION_VALUE; Path=/; Secure; HttpOnly; SameSite=Lax

Modern browsers require Secure with SameSite=None, and third-party-cookie policies may still prevent sending. Cookie authentication needs appropriate defenses. An explicit bearer Authorization header is not automatically attached in the same way, but JavaScript-readable token storage increases XSS exposure.

is a browser policy governing cross-origin response access. An origin is scheme, host and port, which differs from a site. This registration and belong after routing and before authorization.

builder.Services.AddCors(options => options.AddPolicy("store", policy =>
    policy.WithOrigins("https://shop.example.com") // (1)
        .WithMethods("GET", "POST")
        .WithHeaders("Content-Type")
        .AllowCredentials())); // (2)

// After builder.Build() and routing:
app.UseCors("store");
🧾 Code walkthrough
  1. (1) Use an explicit allowlist rather than reflecting arbitrary origins.
  2. (2) Credentialed requests require an explicit origin rather than a wildcard. The browser must opt into credentials, and cookie policies still apply.

A preflight is usually an OPTIONS request before a non-simple request. CORS is not authentication or a firewall: curl and server clients are not constrained by it, and some cross-origin requests reach the server even when the browser cannot read their responses. See the CORS protocol.

#Caching headers and compression

Correct caching reduces and server load; incorrect caching can expose user data. max-age defines freshness, public allows shared caching, and private restricts storage to a private user cache. no-cache requires revalidation before reuse rather than forbidding storage; no-store forbids storage. ETag with If-None-Match can produce a bodyless 304.

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public, max-age=60
ETag: "catalog-v8"
Vary: Accept-Encoding
Content-Encoding: br

[Brotli-compressed representation bytes]

This schematic response describes a public catalog; the shown body describes bytes rather than sendable . Vary identifies request headers that affect representation selection and cache keys. Accept-Encoding negotiates compression; br or gzip saves bandwidth at cost, while already compressed images often gain little.

Do not put authenticated invoices in a public cache. Configure keys for queries, locale and tenant where content varies. Compressing responses that mix secrets with attacker-controlled input can create a side channel; assess this rather than compressing everything indiscriminately.

no-store does not erase previously cached copies. Invalidation and browser/ policy need a coherent design. See the HTTP caching specification.

#Proxies, load balancers and CDNs

A forward proxy represents clients on outbound requests; a represents servers to clients. A load balancer distributes connections or requests; a brings delivery closer to users and may provide caching and edge execution.

L4 load balancingL7 load balancing
Decision, port and transport connection host, path and headers after protocol inspection
May pass through; product behavior variesOften terminates TLS, then uses new TLS or HTTP upstream
UseGeneral traffic, not necessarily HTTP routing and header policies

TLS termination creates a trust boundary between proxy and application. Configure trusted forwarded headers, body limits, timeouts and . CDN caching helps static assets, but cookies, Authorization and queries need deliberate cache-key handling to prevent leakage. Sticky sessions do not replace shared state, and a load balancer cannot guarantee a payment executes exactly once.

#DNS records, TTL, IPv4, IPv6 and NAT

maps names to information, not simply URLs to IPs. bounds record caching; it is neither connection lifetime nor a guarantee that every client switches simultaneously.

RecordMeaning
AName to IPv4 address
AAAAName to IPv6 address
CNAMEAlias to another name, not a or redirect
MXMail servers and preference
TXTText such as verification and SPF policy

IPv4 uses 32-bit addresses; IPv6 uses 128 bits. Private IPv4 ranges are 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Loopback such as 127.0.0.1 differs from private LAN space. IPv6 includes loopback ::1, unique-local space fc00::/7 and link-local space fe80::/10.

translates addresses; PAT shares a public using ports. Neither is encryption or a replacement for a firewall. IPv6 still requires access policies. Test both address families in dual-stack environments; a broken AAAA path can delay requests even when A works. Lowering TTL before failover helps but does not close existing pooled connections.

#WebSockets, SSE and diagnostic tools

Repeated polling wastes requests when nothing changes. WebSockets provide a long-lived bidirectional message channel; provides server-to-client text events using text/event-stream, with browser reconnection through EventSource. WebSockets are not universally restricted to /1.1 Upgrade; newer HTTP versions have mechanisms where supported by the stack.

NeedSuitable choice
Server-pushed order statusSSE if one direction is enough
Interactive messages both waysWebSocket or a SignalR abstraction
Rare, noncritical updatesSimple polling may suffice

10 provides TypedResults.ServerSentEvents. For any stream, configure cancellation, , heartbeats, proxy buffering and idle timeouts. Reconnection needs event IDs and a replay policy when lost events are unacceptable.

These Bash commands use illustrative endpoints, not a service running here. Flags such as HTTP/3 require a suitably built curl; inspect curl --version.

curl -I https://store.example.com/products/42       # (1)
curl -v --http2 https://store.example.com/products/42 # (2)
curl --compressed https://store.example.com/products/42
curl -N -H 'Accept: text/event-stream' \
  https://store.example.com/orders/42/events        # (3)
curl --resolve store.example.com:443:192.0.2.10 \
  https://store.example.com/products/42             # (4)
🧾 Code walkthrough
  1. (1) HEAD requests metadata without a response body.
  2. (2) Verbose output exposes negotiation and headers; do not share credentials in logs. Inspect the actual negotiated protocol rather than only the flag.
  3. (3) -N disables curl output buffering so arriving events are visible immediately.
  4. (4) Override with a documentation address while preserving hostname and verification. Substitute a real test address to diagnose routing.

curl is not a browser: success does not validate browser or cookie behavior. Diagnose DNS, TLS, HTTP and application behavior separately.

Interview questions

Check your reasoning

Why does this choice fit? When would it fail? What changes under higher load or a dependency failure?

24.1What happens when you type an HTTPS URL into a browser?Junior
Model answer

I break it into stages. The browser parses the and checks relevant caches, resolves the hostname, establishes a connection if one cannot be reused, and negotiates for . It sends the request, receives headers and content, then parses resources and performs rendering. For -based HTTPS there is a TCP handshake before TLS; HTTP/3 uses instead. Caching and connection reuse can skip substantial parts of this sequence.

24.2How do TCP and UDP differ?Junior
Model answer

I use when I need a reliable ordered byte stream, understanding that application messages still require framing. preserves datagram boundaries but does not itself guarantee delivery or ordering. That can suit protocols that manage loss differently, such as real-time media or . I do not equate UDP with always faster or TCP with one packet per message; performance and correctness depend on the protocol built above the transport and the network conditions.

24.3What is the TCP three-way handshake?Junior
Model answer

I describe it as the exchange of SYN, SYN- and ACK to establish connection state and synchronize sequence numbers in both directions. It lets each endpoint confirm communication with the other before normal stream exchange. It does not encrypt the connection or authenticate an application user. For , adds encryption and server authentication above TCP. Reusing an established connection avoids repeating this startup work for every request.

24.4What does TLS 1.3 provide?Mid
Model answer

I rely on 1.3 for confidentiality, integrity and authentication of the server through certificate validation, with client authentication available when configured. The peers negotiate parameters and derive traffic keys rather than sending a shared secret in plaintext. A typical full handshake adds one TLS round trip over a new connection. TLS does not authorize business operations, and disabling certificate validation defeats a central part of its security even if traffic remains encrypted.

24.5How do HTTP/2 and HTTP/3 improve on HTTP/1.1?Mid
Model answer

I see /2's main improvements as binary framing, multiplexed streams and HPACK header compression over . That reduces HTTP-level , but TCP loss can still block progress across streams. HTTP/3 moves to over and uses QPACK, reducing that cross-stream transport blocking. It still has congestion and flow control, and is not automatically faster in every environment. I verify support through clients, proxies, firewalls and the server before enabling it.

24.6What does idempotent mean in HTTP?Junior
Model answer

I call an operation when repeating the same request has the same intended server-side effect as performing it once. Responses can differ: deleting an already deleted resource might return a different status without violating that property. PUT and DELETE have idempotent semantics, while POST does not inherently. For retryable payment creation, I define an idempotency-key contract and persist its outcome because a timeout cannot tell the client whether the first attempt completed.

24.7Why can creating HttpClient per request cause problems?Mid
Model answer

I avoid creating a new HttpClient and handler for every request because each handler owns connection pools. Repeated disposal wastes connections and can exhaust ephemeral ports under load. I use IHttpClientFactory for pooled handler management or a long-lived client with a suitable SocketsHttpHandler connection lifetime. I also bound requests and release response resources. Simply making the client static is incomplete if connections never refresh and changes need to be picked up.

24.8How does HttpClient react to DNS changes?Senior
Model answer

I assume is resolved when a connection is established rather than before every request. Existing pooled connections can continue using the old destination after records change. PooledConnectionLifetime or suitable handler rotation allows new connections to resolve again, with an interval chosen for the environment. I also avoid indefinitely retaining factory clients when relying on rotation. Lowering DNS alone does not move traffic already traveling through an established connection.

24.9Is CORS a security boundary for an API?Mid
Model answer

I treat as a browser-enforced policy for cross-origin response access, not authentication or a network firewall. Non-browser clients can call the endpoint regardless, and some requests can reach the server even when a browser blocks access to the response. I therefore enforce authorization and appropriate defenses independently. For credentialed browser requests I allow explicit trusted origins, methods and headers rather than combining wildcard origins with credentials.

24.10How do Secure, HttpOnly and SameSite cookies differ?Mid
Model answer

I use Secure to restrict cookie transmission to , HttpOnly to prevent JavaScript from reading the cookie, and SameSite to control cross-site sending. None is complete protection by itself: HttpOnly does not stop malicious script from issuing authenticated requests, and SameSite does not replace every defense. Cross-site cookies using SameSite=None need Secure in modern browsers, and third-party-cookie policies can still block them. I test the actual browser flow rather than relying on curl.

24.11What is the difference between no-cache and no-store?Junior
Model answer

I use no-cache when a stored response must be revalidated before reuse, often through an ETag and a conditional request. I use no-store when the response should not be stored. They are not synonyms. I also distinguish private caching from shared caching: private limits where the response may be cached but does not encrypt it. For sensitive user data I review the full browser and policy rather than adding one directive without checking existing cache behavior.

24.12How does an ETag help caching?Mid
Model answer

I use an ETag as a validator for a selected representation. A client sends it in If-None-Match, and the server can return 304 without a body if the representation is still valid. That saves transfer while still involving a validation request. I ensure the tag reflects the content and that cache keys account for meaningful variants. I also distinguish weak and strong validators when exact byte equality or conditional update semantics matter.

24.13How do L4 and L7 load balancers differ?Senior
Model answer

I use L4 balancing for transport-level distribution based on addresses, ports and connections. L7 balancing understands application protocols and can route by host, path or headers. That enables richer policies but usually introduces additional application-level configuration and often termination. I check where encryption ends and how client information is forwarded. Neither type removes the need for readiness, graceful draining or application-level when requests fail during a connection change.

24.14When would you choose SSE over WebSockets?Senior
Model answer

I choose for a server-to-client event stream such as order-status updates when bidirectional messaging is unnecessary. Browser EventSource provides reconnection behavior, but reliable recovery still needs event identifiers and a replay policy. I choose WebSockets when the client and server both need interactive messages. For either approach I test proxy buffering, idle timeouts, cancellation, and authentication lifecycle rather than assuming a persistent connection automatically guarantees reliable message delivery.

24.15What do A, AAAA and CNAME DNS records mean?Junior
Model answer

I use A records to map a name to an IPv4 address and AAAA records for IPv6. A CNAME aliases one name to another name; it does not contain a path or issue an redirect. Resolution can follow that alias to address records. I also consider and existing connection pools during changes, because publishing a new record does not mean every resolver and connected client immediately uses the new destination.

24.16A request works in curl but fails in the browser. What do you inspect?Senior
Model answer

I compare the exact requests and inspect the browser network and console output. I check origin, preflight, allowed headers, credentials mode, cookie attributes and third-party-cookie policy, along with mixed-content and certificate errors. I also verify whether the server received the request or only a preflight. curl does not enforce browser rules, so its success establishes reachability and an response, not correctness of the browser security and authentication flow.

Test yourself

Quiz answers and completed-topic marks are saved in this browser; they do not sync across devices.

Score: 0 / 0

Which sequence describes the TCP three-way handshake?

This establishes ; follows for TCP-based .

HTTP/3 uses which transport?

provides reliable streams and uses 1.3.

Which directive requires validation before reuse but permits storage?

no-store is the directive that forbids storage.

CORS primarily controls what?

Authentication, and network policy are separate responsibilities.

What does HttpOnly prevent?

A script may issue requests even when it cannot read the cookie.

What does a 304 response normally omit?

The client reuses its stored representation after validation.

Which record maps a hostname to IPv6?

A addresses IPv4; AAAA addresses IPv6.

Why can HTTP/2 streams stall together after packet loss?

head-of-line blocking remains beneath multiplexing.

An HTTP POST timed out. What is safe to assume?

Execution may have completed while the response was lost; matters.

What does lowering DNS TTL fail to do by itself?

caching and connection pooling are different mechanisms.