PrepStack › Backend › Backend & HTTP Fundamentals

Backend & HTTP Fundamentals interview cheat sheet

HTTP, caching, load balancing, rate limiting, resilience and service design

This is the language-agnostic core of every backend interview. Interviewers check that you understand HTTP properly (methods, status codes, headers, caching, cookies), know what sits between the client and your code (DNS, TLS, CDN, load balancer, reverse proxy), and can keep a service healthy under load and failure (rate limiting, idempotency, retries, timeouts, circuit breakers). Read the 15-minute revision first, then work through the groups in order and answer the Q&As out loud.

15-minute revision

  1. HTTP is a stateless request/response protocol. A request is a start line (METHOD target version), headers, a blank line and an optional body. A response has a status line, headers and a body.
  2. Safe methods do not change server state (GET HEAD OPTIONS TRACE). Idempotent = repeating the request has the same effect as doing it once: safe methods plus PUT and DELETE. POST and PATCH are neither by default.
  3. Status classes: 1xx info, 2xx success, 3xx redirect, 4xx client error, 5xx server error. Know 200 201 204 301 302 304 307 308 400 401 403 404 409 422 429 500 502 503 504.
  4. 401 = not authenticated (who are you?). 403 = authenticated but not allowed. 502 = bad answer from upstream. 504 = upstream too slow. 503 = overloaded or down, often with Retry-After.
  5. Content negotiation: client sends Accept, Accept-Encoding, Accept-Language; server answers with Content-Type, Content-Encoding and Vary so caches key on those headers.
  6. CORS is enforced by the browser, not the server. Non-simple requests get an OPTIONS preflight; Access-Control-Allow-Origin: * cannot be used with credentials.
  7. HTTP/1.1 = text, one request at a time per connection, keep-alive by default. HTTP/2 = binary frames, multiplexed streams on one TCP connection, HPACK. HTTP/3 = HTTP over QUIC (UDP), no TCP head-of-line blocking, built-in TLS 1.3.
  8. Cookies carry state over a stateless protocol. Session cookies should be HttpOnly; Secure; SameSite=Lax (or Strict). Server sessions = id in cookie, data on server; tokens (JWT) = data in the token.
  9. Cache-Control: no-cache means store but revalidate; no-store means never store. max-age for browsers, s-maxage for shared caches. ETag + If-None-Match gives 304 Not Modified.
  10. A reverse proxy sits in front of servers (TLS termination, caching, compression, routing). A CDN is a geo-distributed reverse-proxy cache. A load balancer spreads traffic across healthy instances.
  11. L4 load balancers route by IP/port (fast, content-blind). L7 load balancers read HTTP (path, host, header and cookie routing). Algorithms: round robin, weighted, least connections, IP hash, consistent hashing.
  12. Rate limiting: token bucket allows bursts up to capacity, leaky bucket smooths output to a fixed rate, fixed window is simple but bursts at edges, sliding window fixes that. Reply 429 + Retry-After.
  13. Idempotency keys make POST safe to retry: the server stores key → result and replays the result for duplicates. Retry only idempotent work, with exponential backoff + jitter and a retry budget.
  14. Every remote call needs a timeout. A circuit breaker (closed → open → half-open) stops calling a failing dependency so failures do not cascade.
  15. Monolith first for small teams; microservices buy independent deploys and scaling at the cost of network calls, distributed data and ops. Use queues for slow or spiky work and return 202 Accepted.
  16. 12-factor highlights: config in env vars, stateless processes, backing services as attached resources, logs to stdout, fast startup and graceful shutdown, dev/prod parity.

HTTP Foundations

Client–server model & the web stack

Clients send requests, servers own the data and logic and send responses, all over TCP/IP (or QUIC) with HTTP on top.

  • Client–server: the client (browser, mobile app, another service) starts every exchange; the server listens on a port and answers. The server never pushes on plain HTTP unless the client opened a channel (SSE, WebSocket).
  • Layers you should name: DNS (name → IP), TCP or QUIC (reliable transport), TLS (encryption and server identity), HTTP (request/response semantics).
  • A backend usually means: an HTTP layer (routing, validation, auth), business logic, and data access (database, cache, queue, other services).
  • Servers are concurrent: thread-per-request (classic Java/Spring MVC), an event loop with non-blocking I/O (Node.js), or async workers (Python ASGI, Go goroutines).
  • Scale vertically (bigger machine) until it hurts, then horizontally (more instances behind a load balancer). Horizontal scale needs stateless app servers.
  • Other models exist: peer-to-peer (no central server), pub/sub (producers and consumers via a broker) and RPC styles like gRPC, which still runs over HTTP/2.

Interview questions

  • What is the client–server model?
  • What is the difference between a web server and an application server?
  • How do servers handle many requests at once?

HTTP request & response anatomy

A message is a start line, headers, a blank line, and an optional body.

  • Request start line: METHOD request-target HTTP-version, e.g. GET /api/users?page=2 HTTP/1.1. The Host header is required in HTTP/1.1.
  • Response status line: HTTP/1.1 200 OK. The reason phrase is informational only; HTTP/2 and HTTP/3 drop it and send only the code.
  • Headers are case-insensitive Name: value pairs. Split them into request headers (Accept, Authorization, User-Agent), response headers (Server, Set-Cookie, Location) and content headers (Content-Type, Content-Length, Content-Encoding).
  • The body length is given by Content-Length or by Transfer-Encoding: chunked (HTTP/1.1). HTTP/2 and HTTP/3 use frames instead.
  • URL parts: scheme://host:port/path?query#fragment. The fragment is never sent to the server.
  • In HTTP/2 and HTTP/3 the start line becomes pseudo-headers: :method, :scheme, :authority, :path and :status.

Interview questions

  • What does an HTTP request contain?
  • What is the difference between query parameters, path parameters and the body?
  • What is chunked transfer encoding?

Methods, safety & idempotency

Safe means read-only; idempotent means repeating it has the same effect as doing it once.

  • GET reads, HEAD is GET without a body, POST creates or triggers processing, PUT replaces the whole resource, PATCH changes part of it, DELETE removes it, OPTIONS asks what is allowed (used by CORS preflight).
  • Safe = the client does not ask for any state change. Servers may still log or count, but crawlers and prefetchers assume safe methods are harmless.
  • Idempotent is about the effect on the server, not the response. A second DELETE /users/1 may return 404, but the state is the same, so it is idempotent.
  • Idempotency matters for retries: proxies and clients may automatically retry idempotent requests after a network error. Retrying POST can create duplicates.
  • PATCH can be made idempotent (e.g. set a field) or not (e.g. increment a counter). PUT to a known URL is idempotent; POST to a collection is not.
  • QUERY is a newer method (IETF draft) for safe, idempotent queries with a request body, for search requests too large or complex for a URL.

Interview questions

  • What is the difference between safe and idempotent methods?
  • Difference between PUT and PATCH?
  • Difference between PUT and POST?
  • Is DELETE idempotent if the second call returns 404?

Status codes you must know

The first digit gives the class; pick the most specific code so clients and proxies can react correctly.

  • 2xx: 200 OK, 201 Created (+ Location), 202 Accepted (queued for later), 204 No Content, 206 Partial Content (range requests).
  • 3xx: 301/308 permanent, 302/307 temporary, 303 See Other (go GET this after a POST), 304 Not Modified (cache revalidation). 307 and 308 keep the method and body; 301/302 may be turned into GET by clients.
  • 4xx: 400 malformed, 401 unauthenticated, 403 forbidden, 404 not found, 405 method not allowed (+ Allow), 409 conflict, 410 gone, 412 precondition failed, 413 body too large, 415 unsupported media type, 422 validation failed, 429 too many requests.
  • 5xx: 500 bug, 501 not implemented, 502 bad gateway (upstream sent garbage or refused), 503 unavailable (overload or maintenance), 504 gateway timeout.
  • Gateways and load balancers produce most 502/504 responses. Seeing them tells you which hop failed.
  • Clients should treat unknown codes as the x00 of their class (an unknown 4xx is handled like 400).

Interview questions

  • Difference between 401 and 403?
  • What is the difference between 502, 503 and 504?
  • Which status code for a validation error?
  • What should an async endpoint return?
  • Why do 307 and 308 exist when we have 302 and 301?

Headers: negotiation, CORS & friends

Headers carry metadata: content format, auth, caching, cookies, CORS and tracing.

  • Content negotiation: client sends Accept (with q weights), Accept-Encoding (gzip, br, zstd), Accept-Language. Server picks and replies with Content-Type, Content-Encoding, Content-Language, or 406 Not Acceptable.
  • Vary: Accept-Encoding tells caches the response depends on that request header, so they store a separate copy per value.
  • CORS relaxes the browser's same-origin policy. Origin = scheme + host + port. The server opts in with Access-Control-Allow-Origin, -Allow-Methods, -Allow-Headers, -Allow-Credentials, -Max-Age.
  • Simple requests (GET/HEAD/POST with safe headers and form or text content types) go straight through. Others (PUT, DELETE, Content-Type: application/json, custom headers) trigger an OPTIONS preflight first.
  • Useful others: Authorization, Location, Retry-After, X-Request-ID / traceparent (tracing), Forwarded / X-Forwarded-For (client IP behind proxies), Strict-Transport-Security.
  • Custom headers no longer need an X- prefix (RFC 6648), but many existing ones keep it.

Interview questions

  • What is CORS and why does it exist?
  • When does a browser send a preflight request?
  • What is content negotiation?
  • How do you get the real client IP behind a load balancer?

Connections, Protocols & State

HTTP/1.1 vs HTTP/2 vs HTTP/3 & keep-alive

Same semantics, different wire formats: text over TCP, binary multiplexed frames over TCP, then frames over QUIC/UDP.

  • Keep-alive (persistent connections) is the default in HTTP/1.1: one TCP + TLS handshake serves many requests. Connection: close ends it. HTTP/1.0 needed Connection: keep-alive.
  • HTTP/1.1 sends one request at a time per connection. Pipelining existed but was broken in practice, so browsers open ~6 connections per host.
  • HTTP/2 (RFC 9113): binary framing, many streams multiplexed on one connection, HPACK header compression, stream priorities. Server push was dropped by browsers (Chrome removed it in 2022); use 103 Early Hints instead.
  • HTTP/2 fixes HTTP-level head-of-line blocking but not TCP head-of-line blocking: one lost packet stalls every stream on that connection.
  • HTTP/3 (RFC 9114) runs on QUIC over UDP: per-stream loss recovery, TLS 1.3 built in, 1-RTT setup (0-RTT on resumption), QPACK compression, and connection migration (Wi-Fi → mobile keeps the connection).
  • Browsers learn about HTTP/3 through the Alt-Svc header or DNS HTTPS records, then switch. HTTP/2 is negotiated during TLS with ALPN (h2).

Interview questions

  • What are the main differences between HTTP/1.1, HTTP/2 and HTTP/3?
  • What is head-of-line blocking?
  • What is HTTP keep-alive and why does it matter?
  • Why was HTTP/2 server push abandoned?

Cookies, sessions & tokens

Cookies let a stateless protocol remember a client; the session data lives either on the server or inside a signed token.

  • The server sets a cookie with Set-Cookie; the browser sends it back in Cookie on matching requests (domain, path, secure, SameSite rules).
  • Attributes: HttpOnly (no JS access, limits XSS theft), Secure (HTTPS only), SameSite=Strict|Lax|None (CSRF defence), Max-Age/Expires (persistent vs session cookie), Domain, Path. The __Host- prefix forces Secure, no Domain, and Path=/.
  • Browsers treat a cookie with no SameSite as Lax (Chrome and others); SameSite=None requires Secure.
  • Server-side session: cookie holds a random id, data lives in memory/Redis/DB. Easy to revoke; needs a shared store when you have many instances.
  • Token (e.g. JWT): signed claims sent in a cookie or the Authorization: Bearer header. Stateless to verify, but hard to revoke before expiry, so keep access tokens short-lived with refresh tokens.
  • Regenerate the session id at login to prevent session fixation.

Interview questions

  • What is the difference between cookies and sessions?
  • Session-based auth vs JWT: which would you choose?
  • What do HttpOnly, Secure and SameSite do?

Statelessness & horizontal scaling

Each request carries everything needed to handle it, so any instance can serve it.

  • HTTP is stateless: the protocol does not remember earlier requests. Stateless services keep no per-client data in process memory between requests.
  • State still exists; it moves to shared backing services: database, Redis, object storage, or into the client (tokens).
  • Benefits: add or remove instances freely, roll deploys without losing users, recover from crashes, and any load balancer algorithm works.
  • Sticky sessions (session affinity) pin a user to one instance. They are a stopgap: uneven load, and users lose state when that instance dies.
  • In-memory caches per instance are fine as long as they are only an optimisation and can be rebuilt; they must not be the source of truth.
  • Stateful components (databases, brokers, WebSocket gateways) scale differently: sharding, replication, or connection-aware routing.

Interview questions

  • What does it mean for a service to be stateless?
  • What are sticky sessions and why are they usually avoided?
  • Is REST stateless? Then how do logged-in users work?

Caching, Proxies & Load Balancing

HTTP caching: Cache-Control & ETag

Freshness (max-age) decides when to reuse without asking; validation (ETag, Last-Modified) makes asking cheap.

  • Caches: the browser (private), plus shared caches (CDN, reverse proxy). private keeps a response out of shared caches; public allows it.
  • Freshness: max-age=N (seconds), s-maxage=N (shared caches only, overrides max-age). While fresh, the cache answers without contacting the origin.
  • Validation: when stale, the cache sends If-None-Match: <etag> or If-Modified-Since: <date>. If unchanged, the server returns 304 Not Modified with no body.
  • no-cache = may store, but must revalidate before every use. no-store = never store (sensitive data). must-revalidate = do not serve stale after expiry.
  • immutable + long max-age for fingerprinted assets (app.3f9a1c.js). stale-while-revalidate=N serves stale while refreshing in the background.
  • Strong ETags ("abc") mean byte-identical; weak ETags (W/"abc") mean semantically equal. ETags also enable optimistic locking with If-Match → 412 Precondition Failed.

Interview questions

  • What is the difference between no-cache and no-store?
  • How do ETags work?
  • How would you cache static assets so users always get new versions after a deploy?
  • What is the difference between max-age and s-maxage?

Reverse proxies, API gateways & CDNs

A reverse proxy fronts your servers; a CDN is a worldwide network of caching reverse proxies.

  • Forward proxy acts for clients (corporate proxy, hides the client). Reverse proxy acts for servers (Nginx, Envoy, HAProxy, Caddy), and clients think they are talking to the origin.
  • Reverse proxy jobs: TLS termination, load balancing, caching, compression, request buffering (protects slow app servers from slow clients), rate limiting, routing by path or host, and hiding internal topology.
  • API gateway = reverse proxy plus API concerns: auth, API keys, quotas, request transformation, routing to microservices, versioning.
  • CDN (Cloudflare, CloudFront, Fastly, Akamai): edge servers (PoPs) near users cache content, cut latency and absorb DDoS. Cache misses go to the origin, often via a shield tier.
  • CDNs can cache API responses too, if they are public and have a sensible s-maxage. Invalidation is by purge (URL, tag/surrogate key) or by changing URLs.
  • Edge compute (Workers, Lambda@Edge) runs small pieces of logic at the PoP: redirects, auth checks, A/B routing.

Interview questions

  • What is the difference between a forward proxy and a reverse proxy?
  • How does a CDN speed up a site?
  • What is an API gateway and how is it different from a load balancer?

Load balancers: L4 vs L7 & algorithms

L4 routes connections by IP and port; L7 routes requests by HTTP content. The algorithm decides which healthy backend gets the next one.

  • L4 (transport): sees TCP/UDP 4-tuples, forwards packets or connections. Very fast, protocol-agnostic, cannot route by URL. Examples: AWS NLB, LVS, HAProxy in TCP mode.
  • L7 (application): terminates HTTP, can route by host, path, header or cookie, rewrite, retry, add headers, do TLS termination and gRPC per-request balancing. Examples: AWS ALB, Nginx, Envoy.
  • Health checks (active probes and passive error tracking) remove bad backends. Connection draining lets in-flight requests finish before an instance leaves.
  • Algorithms: round robin, weighted round robin, least connections, least response time, IP/hash-based (affinity), consistent hashing (cache-friendly, minimal remapping), power of two choices (pick 2 random, take the less loaded).
  • Avoid the LB itself being a single point of failure: run it as a pair (active/passive with a floating IP) or use a managed, multi-zone LB. DNS and anycast spread load across regions.
  • Long-lived connections (HTTP/2, gRPC, WebSockets) defeat per-connection L4 balancing; use L7 or client-side balancing.

Interview questions

  • What is the difference between an L4 and an L7 load balancer?
  • Which load balancing algorithm would you choose?
  • Why consistent hashing instead of hash mod N?
  • How does a load balancer know a server is unhealthy?

Reliability: Limits, Retries & Failures

Rate limiting algorithms

Token bucket allows controlled bursts, leaky bucket smooths output, and sliding windows fix fixed-window edge bursts.

  • Why: protect capacity, ensure fairness between tenants, stop abuse (brute force, scraping) and control cost. Limit by API key, user, IP or route.
  • Token bucket: tokens refill at rate r up to capacity b; each request takes one. Allows bursts up to b, average rate r. Used by AWS API Gateway, Stripe-style limiters, Nginx burst.
  • Leaky bucket: requests enter a queue that drains at a fixed rate; if the queue is full, drop. Output is perfectly smooth (traffic shaping), but bursts wait.
  • Fixed window counter: count per clock window (e.g. per minute). Cheap, but a client can send 2×limit across a window boundary.
  • Sliding window log: keep timestamps of recent requests; exact but uses memory per request. Sliding window counter: weight the previous window's count by overlap; close to exact with two counters.
  • Distributed: keep counters in Redis with atomic ops (INCR + EXPIRE, or a Lua script) so all instances share limits. Respond with 429 Too Many Requests and Retry-After.

Interview questions

  • Explain the token bucket algorithm.
  • Token bucket vs leaky bucket?
  • What is the problem with a fixed window counter?
  • How would you design a distributed rate limiter?
  • Rate limiting vs throttling vs load shedding?

Idempotency keys & exactly-once effects

The client sends a unique key with a non-idempotent request; the server stores the outcome and replays it for duplicates.

  • Problem: a POST /payments times out. Did it succeed? Retrying might charge twice; not retrying might lose the payment.
  • Fix: the client generates a unique key (UUID v4) per logical operation and sends Idempotency-Key: <key>. Retries reuse the same key.
  • Server: look up the key. Not seen → process and save (key, request hash, status, response). Seen and finished → return the saved response. Seen and in progress → 409 Conflict (or wait).
  • Store the key atomically with the business write (same DB transaction, or a unique constraint) so a crash can't leave the effect without the record.
  • Reject a reused key with a different payload (422) to catch client bugs. Expire keys after a period (Stripe keeps them about 24 hours).
  • Networks deliver at least once; 'exactly once' really means at-least-once delivery + idempotent processing (dedupe by id). The same idea applies to queue consumers and webhooks.

Interview questions

  • What is an idempotency key and why is it needed?
  • How do you implement idempotency keys safely under concurrency?
  • Can you get exactly-once delivery in a distributed system?

Retries, exponential backoff & jitter

Retry only transient failures on idempotent calls, wait exponentially longer each time, add randomness, and cap the total.

  • Retry transient errors: connection resets, timeouts, 502, 503, 504, 429. Do not retry 400, 401, 403, 404, 422: they will fail again.
  • Exponential backoff: wait base × 2^attempt, capped at a maximum. Gives the dependency room to recover.
  • Jitter spreads retries in time so thousands of clients don't hit the server at the same moment (thundering herd). AWS's analysis recommends full jitter: sleep = random(0, min(cap, base × 2^attempt)).
  • Honour Retry-After when the server sends it (429, 503).
  • Cap retries (3–5) and use a retry budget (e.g. retries ≤ 10% of requests). Retry at one layer only: 3 retries at each of 3 layers is 27× load (retry storm).
  • Only retry idempotent operations, or non-idempotent ones protected by an idempotency key.

Interview questions

  • Why add jitter to exponential backoff?
  • Which errors should you retry?
  • What is a retry storm and how do you prevent it?

Timeouts, circuit breakers & bulkheads

Never wait forever: bound every call with a timeout, stop calling broken dependencies, and isolate resources so one failure can't sink everything.

  • Without timeouts, a slow dependency ties up threads and connections until the caller runs out and fails too: a cascading failure.
  • Set connect and read/request timeouts on every HTTP client, DB driver and pool. Base them on the dependency's p99 latency, not on guesses.
  • Deadline propagation: pass the remaining time budget downstream (gRPC deadlines, a header) so inner calls don't keep working after the caller gave up.
  • Circuit breaker: closed (calls pass, failures counted) → open after a failure threshold (calls fail fast, no network) → half-open after a cool-down (a few trial calls) → closed on success, open again on failure.
  • Bulkheads: separate thread/connection pools per dependency, so a slow payment service can't eat the pool used for search.
  • Fallbacks when open: cached data, defaults, a degraded feature, or a clear error. Libraries: Resilience4j (Java), Polly (.NET), opossum (Node); service meshes (Envoy/Istio) do outlier detection at the proxy.

Interview questions

  • What is the circuit breaker pattern?
  • Why are timeouts so important in a microservice architecture?
  • What is the bulkhead pattern?
  • Your service's p99 latency spikes when a downstream dependency slows. What do you do?

Architecture & Processing

Monolith vs microservices

Microservices trade in-process simplicity for independent deploys and scaling; choose them for organisational scale, not fashion.

  • Monolith: one deployable unit, one process, usually one database. Simple to build, test, debug and deploy; in-process calls are fast and transactional.
  • Modular monolith: one deployable, but strict module boundaries inside. A good default and an easy path to extracting services later.
  • Microservices: small services around business capabilities, each owning its own data, deployed independently, talking over the network (REST, gRPC, events).
  • Costs: network latency and failures, distributed transactions (sagas instead of ACID across services), eventual consistency, tracing and ops overhead, versioned contracts.
  • Conway's law: system structure mirrors team structure. Microservices pay off when many teams need to ship independently.
  • Anti-patterns: a distributed monolith (services must deploy together), shared databases between services, chatty synchronous call chains.

Interview questions

  • Monolith vs microservices: when would you choose each?
  • How do you handle a transaction that spans multiple services?
  • What is a distributed monolith?
  • How do services find and talk to each other?

Synchronous vs asynchronous processing

Do the minimum in the request; push slow, spiky or failure-prone work to a queue and process it in the background.

  • Synchronous: the client waits while the server does all the work. Simple, consistent, immediate errors, but latency adds up and failures propagate.
  • Asynchronous: the server validates, stores a job or publishes an event, returns 202 Accepted (or 201 for the record), and workers do the rest.
  • Good async candidates: emails, image/video processing, reports, webhooks to third parties, search indexing, anything slow or rate-limited downstream.
  • Queues (RabbitMQ, SQS) buffer spikes (load levelling), decouple producers from consumers, and allow retries with a dead-letter queue (DLQ) for poison messages.
  • Delivery is usually at-least-once, so consumers must be idempotent. Ordering is often only per partition/key.
  • Clients learn the result by polling a status URL, webhooks, WebSockets or SSE.

Interview questions

  • When would you make an operation asynchronous?
  • What happens if a message is processed twice?
  • What is a dead-letter queue?
  • Message queue vs event stream (RabbitMQ vs Kafka)?

The Twelve-Factor App

A checklist for building portable, scalable, cloud-friendly services: config in env, stateless processes, disposable instances.

  • I Codebase: one repo per app, many deploys. II Dependencies: declare and isolate them (lock files, no system-wide installs).
  • III Config: anything that varies per environment goes in environment variables, never in code. IV Backing services: DBs, caches, queues are attached resources swapped by changing config.
  • V Build, release, run: separate stages; a release = build + config, immutable and versioned. VI Processes: stateless, share-nothing; state in backing services.
  • VII Port binding: the app is self-contained and exports HTTP by binding a port. VIII Concurrency: scale out by running more processes.
  • IX Disposability: fast startup, graceful shutdown on SIGTERM. X Dev/prod parity: keep environments similar (same backing services).
  • XI Logs: write to stdout as an event stream; the platform collects them. XII Admin processes: run one-off tasks (migrations) as separate processes with the same code and config.

Interview questions

  • What is the Twelve-Factor App?
  • Why should config be stored in environment variables?
  • What does 'disposability' mean and how do you implement it?

What happens when a request hits your server

DNS, TCP/QUIC and TLS, edge/CDN, load balancer, reverse proxy, the app's middleware and handler, data stores, then the response travels back.

  • DNS: browser/OS cache, then a recursive resolver, then root → TLD → authoritative servers. Result: an IP (often an anycast CDN or LB address).
  • Connection: TCP 3-way handshake + TLS 1.3 handshake (1 RTT; cert checked, ALPN picks h2) — or one QUIC handshake for HTTP/3.
  • Edge: CDN/WAF checks cache, blocks attacks, may serve the response. On a miss it forwards to the origin load balancer, which picks a healthy instance.
  • Server: the kernel accepts the socket into a backlog; the runtime (thread pool / event loop) reads it; the framework parses HTTP and runs middleware (logging, request id, auth, rate limit, body parsing, validation) then the router finds the handler.
  • Handler: business logic, cache lookups, DB queries over a connection pool, calls to other services (with timeouts). Then serialise, set headers (status, caching, cookies), compress, write.
  • Response goes back through the same chain; access logs, metrics and traces are recorded at each hop. Keep-alive keeps the connection open for the next request.

Interview questions

  • What happens when you type a URL and press Enter?
  • Walk through what happens inside the server when a request arrives.
  • A user says the API is slow. How do you find out where the time goes?
  • How would you design an API to handle 10× traffic tomorrow?