Episode 1 — Fundamentals / 1.2 — Client Server Architecture

1.2.c — How HTTP Request and Response Cycle Works

Big Picture: Every click, form submit, and API call is a structured message: the client sends an HTTP request, the server sends an HTTP response. Understanding that cycle — methods, headers, status codes, and TLS — is the foundation for debugging, building APIs, and reasoning about the web.

Navigation: ← 1.2.b — Client vs Server · 1.2.d — What Happens When You Visit a Website →


1. What is HTTP?

HTTP stands for HyperText Transfer Protocol. It is the application-layer protocol (roughly Layer 7 in the OSI model) that web clients and servers use to exchange resources such as HTML pages, images, JSON APIs, and uploads.

PropertyWhat it means
Application layerHTTP sits on top of transport protocols (usually TCP, or UDP with QUIC in HTTP/3). It defines what is said, not how bits cross the wire.
Text-based (historically)Classic HTTP/1.x messages are human-readable lines of ASCII text (headers as Name: value). HTTP/2 and HTTP/3 frame the same semantics in binary structures.
StatelessEach request is independent: the server does not inherently remember past requests. State is added with cookies, tokens, sessions, or application design.
Request–responseThe client sends a request; the server returns one response per request (with nuances for HTTP/2+ streams).

2. HTTP Versions

VersionEra / notesHighlights
HTTP/0.91991Single line (GET /path), only GET, response was raw HTML — no headers.
HTTP/1.01996 (RFC 1945)Full request/response with headers; one request per TCP connection typical (connection closed after response).
HTTP/1.11997+ (RFC 9110 family)Persistent connections (Connection: keep-alive), pipelining (limited in practice), chunked transfer, Host header required, many semantics we use today.
HTTP/22015 (RFC 9113)Binary framing, multiplexing many streams on one connection, header compression (HPACK), optional server push (deprecated in practice for many stacks).
HTTP/32022 (RFC 9114)Runs over QUIC (UDP-based): faster handshakes, better loss recovery, connection migration; same HTTP semantics, different transport.

Mental model: HTTP/1.1 = one long conversation on one wire with strict ordering per connection; HTTP/2 = many parallel “lanes” on one connection; HTTP/3 = same idea but QUIC handles reliability and encryption differently from TCP+TLS.


3. The Request–Response Cycle

Below is an end-to-end flow from a user agent to an origin server (simplified; real stacks add DNS cache, CDNs, proxies, and connection reuse).

┌──────────────┐                                    ┌──────────────┐
│   USER /     │  1. User action (URL, click, form) │              │
│   BROWSER    │ ─────────────────────────────────► │   (app       │
│   (client)   │                                    │    builds    │
└──────┬───────┘                                    │    request)  │
       │                                            └──────┬───────┘
       │  2. Resolve host (DNS) if needed                     │
       │     Open transport: TCP (+ TLS for HTTPS)             │
       │                                                        │
       │  3. Serialize HTTP REQUEST (method, path, headers,     │
       │     optional body) ───────────────────────────────────► │
       │                              ┌────────────────────────┴────────┐
       │                              │  ORIGIN SERVER (or proxy/CDN)      │
       │                              │  4. Parse request                  │
       │                              │  5. Route to handler (static file, │
       │                              │     app server, API, etc.)         │
       │                              │  6. Build HTTP RESPONSE (status,    │
       │                              │     headers, body)                 │
       │                              └────────────────────────┬────────┘
       │  7. Response bytes on wire ◄──────────────────────────┘
       │
       │  8. Parse response; apply caching rules; run CORS (if browser)
       │  9. Render HTML / run JS / update UI
       ▼
   Page / data shown to user

   Optional: 10. Follow redirects (3xx), fetch subresources (more cycles),
              WebSockets upgrade (different pattern), HTTP/2 server push (rare)

One cycle = one logical exchange: request in, response out (HTTP/2 and HTTP/3 may interleave many such exchanges on one connection).


4. Anatomy of an HTTP Request

4.1 Request line

METHOD SP request-target SP HTTP-version CRLF

Example: GET /index.html HTTP/1.1

4.2 Headers

Metadata as Header-Name: value lines, ended by a blank line before the body.

Header (examples)Role
HostWhich site on a shared IP (required in HTTP/1.1 for named hosts).
User-AgentClient software identity (browser, bot, library).
AcceptWhat content types the client prefers (e.g. text/html, application/json).
Content-TypeMedia type of the body (e.g. application/json; charset=utf-8).
AuthorizationCredentials (e.g. Bearer …, Basic …).
CookiePreviously stored cookies for this origin.

4.3 Body

Optional. Used with POST, PUT, PATCH, and some others — carries form data, JSON, file uploads, etc.

4.4 Complete raw HTTP/1.1 request example

POST /api/login HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (compatible; LearningBot/1.0)
Accept: application/json
Content-Type: application/json; charset=utf-8
Content-Length: 42
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Cookie: sessionid=abc123; theme=dark

{"username":"ada","password":"not-in-production"}

The blank line after headers separates headers from the body.


5. HTTP Methods

5.1 Method reference

MethodTypical useSafe?Idempotent?
GETRead a resource (page, JSON)YesYes
POSTCreate resource, submit forms, non-idempotent actionsNoNo
PUTReplace a resource at a URL (full representation)NoYes
PATCHPartial update of a resourceNoNot guaranteed (often treated as non-idempotent)
DELETERemove a resourceNoYes
HEADSame as GET but no body (headers only)YesYes
OPTIONSCORS preflight, discover allowed methodsYesYes

5.2 Safe vs unsafe

  • Safe: Should not change server state (GET, HEAD, OPTIONS). Clients and intermediaries assume repeats are harmless.
  • Unsafe: May change state (POST, PUT, PATCH, DELETE). Must not be auto-retried blindly by caches or prefetch without care.

5.3 Idempotent vs not

  • Idempotent: Repeating the same request has the same effect as once (GET, HEAD, PUT, DELETE, OPTIONS). Network retries are safer.
  • Not idempotent: Repeating may duplicate side effects (e.g. two POSTs → two charges or two rows).

Note: “Idempotent” describes intended semantics; buggy servers can violate them. PATCH is specification-defined as non-idempotent.


6. Anatomy of an HTTP Response

6.1 Status line

HTTP-version SP status-code SP reason-phrase CRLF

Example: HTTP/1.1 200 OK

6.2 Headers

Header (examples)Role
Content-TypeType of body (text/html; charset=utf-8, application/json).
Content-LengthBody size in bytes (unless chunked encoding).
Set-CookieAsk client to store cookies for future requests.
Cache-ControlWho may cache, how long (max-age, no-store, etc.).
Access-Control-Allow-Origin (and related)CORS: which origins may read the response in browsers.

6.3 Body

HTML, JSON, images, files, or empty (e.g. 204 No Content, 304 Not Modified).

6.4 Complete raw HTTP/1.1 response example

HTTP/1.1 200 OK
Date: Sat, 11 Apr 2026 12:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 58
Cache-Control: private, max-age=0
Set-Cookie: sessionid=xyz789; Path=/; HttpOnly; Secure; SameSite=Lax
Access-Control-Allow-Origin: https://app.example.com

{"ok":true,"user":"ada","role":"engineer"}

7. HTTP Status Codes

Responses include a 3-digit status code and a short reason phrase (advisory; clients should rely on the code).

7.1 Families

FamilyMeaning
1xxInformational — request received, continue processing.
2xxSuccess.
3xxRedirection — client should look elsewhere (or use cache).
4xxClient error — bad request, auth, forbidden, etc.
5xxServer error — server failed despite valid-looking request.

7.2 Codes called out in this curriculum

CodeNameTypical meaning
200OKSuccess; body contains the resource.
201CreatedResource created; often Location header with URL.
204No ContentSuccess; no body (e.g. delete succeeded).
301Moved PermanentlyResource has a new permanent URL.
302FoundTemporary redirect (historically misused like 303).
304Not ModifiedCached copy still valid (used with conditional requests).
400Bad RequestMalformed syntax or invalid parameters.
401UnauthorizedAuthentication required or failed.
403ForbiddenAuthenticated but not allowed.
404Not FoundNo resource at this URL.
405Method Not AllowedVerb not supported for this path.
429Too Many RequestsRate limited; often Retry-After.
500Internal Server ErrorGeneric server failure.
502Bad GatewayUpstream server invalid response (proxy/gateway).
503Service UnavailableTemporary overload or maintenance.
504Gateway TimeoutUpstream did not respond in time.

8. HTTP Headers Deep Dive

8.1 Request headers (selection)

HeaderPurpose
Accept, Accept-Language, Accept-EncodingContent negotiation — preferred types, languages, compression (gzip, br).
If-None-Match / If-Modified-SinceConditional GET — enable 304 and save bandwidth.
OriginSent with CORS-sensitive requests; server echoes policy in response.
RefererWhere the user came from (privacy-sensitive; often stripped).

8.2 Response headers (selection)

HeaderPurpose
ETag / Last-ModifiedValidators for caching and conditional requests.
VaryTells caches which request headers affect the chosen representation.
Content-Security-PolicyRestricts scripts, frames, and loads (security).

8.3 Content negotiation

Client and server agree on representation: language (Accept-Language), format (Accept), encoding (Accept-Encoding). The server picks the best match and may say what it chose via Content-Type and Content-Language.

8.4 CORS (Cross-Origin Resource Sharing)

Browsers enforce the same-origin policy for reading responses from JS. For cross-origin APIs:

  • Simple requests may go out with minimal preflight.
  • “Non-simple” requests trigger OPTIONS preflight with Access-Control-Request-* headers.
  • Server responds with Access-Control-Allow-Origin (and often Methods, Headers, Credentials).

CORS is a browser constraint; command-line tools and server-to-server calls are not restricted the same way.

8.5 Caching

MechanismIdea
Cache-ControlDirectives for browsers and CDNs (max-age, s-maxage, no-store, private).
ETag / If-None-MatchRevalidate without full download.
ExpiresLegacy absolute expiry time.

9. Cookies and Sessions

HTTP is stateless, but apps need state (logged-in user, cart, preferences).

  1. Server sends Set-Cookie in a response.
  2. Browser stores name/value + attributes (Path, Domain, Expires/Max-Age, HttpOnly, Secure, SameSite).
  3. On later requests to matching URLs, browser sends Cookie header automatically.

Sessions often mean: server stores session data keyed by an opaque session id in a cookie; the cookie is the pointer, the server holds the truth. Alternatives: JWT in cookies or Authorization header, localStorage (not sent automatically — different tradeoffs).


10. HTTPS and TLS

HTTPS is HTTP over an encrypted channel: historically TLS on top of TCP; with HTTP/3, TLS 1.3 is integrated with QUIC.

10.1 What TLS gives you

  • Confidentiality — eavesdroppers cannot read payloads.
  • Integrity — tampering is detected.
  • Authentication — server proves identity via X.509 certificate chain to a trusted CA (with optional client certs).

10.2 TLS handshake (conceptual)

Modern TLS 1.3 (simplified):

Client                                    Server
   |                                         |
   |  ClientHello (cipher suites, key share) |
   | --------------------------------------> |
   |                                         |
   |  ServerHello, certificate, key share, |
   |  {encrypted extensions}                 |
   | <-------------------------------------- |
   |                                         |
   |  Finish handshake messages              |
   | <-------------------------------------> |
   |                                         |
   |  Application data (HTTP inside)         |
   | <=====================================> |

After the handshake, HTTP requests and responses flow as ciphertext. The URL path and Host are visible to some intermediaries in certain configurations; SNI reveals the hostname during handshake — ESNI/ECH improves privacy where deployed.


11. Real Example: Loading a Webpage

Scenario: User opens https://example.com/news.

11.1 First document (HTML)

Request (abbreviated raw):

GET /news HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:124.0) Gecko/20100101 Firefox/124.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Upgrade-Insecure-Requests: 1

Response (abbreviated raw):

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 512
Cache-Control: max-age=3600
Set-Cookie: sid=fe7a...; Path=/; HttpOnly; Secure; SameSite=Lax

<!DOCTYPE html>
<html lang="en">
<head><title>News</title>
<link rel="stylesheet" href="/assets/style.css">
</head>
<body><h1>News</h1>
<script src="/assets/app.js"></script>
</body></html>

11.2 Subresources

The browser parses HTML and issues additional HTTP cycles (often in parallel on HTTP/2+):

  • GET /assets/style.css200 + CSS body
  • GET /assets/app.js200 + JavaScript body
  • Images, fonts, XHR/fetch to APIs — each is its own request/response (or stream).

Trace summary:

DNS (example.com) → TCP + TLS → GET /news → 200 HTML
  → parse → GET /assets/style.css, GET /assets/app.js → 200 + 200
  → layout, paint, execute scripts → possibly more requests (APIs, images)

12. Key Takeaways

  • HTTP is the application-layer, stateless, request–response protocol for the web; versions evolved from simple text (0.9) to persistent connections (1.1), multiplexed binary (2), and QUIC (3).
  • Every request has a method, target, headers, and optional body; every response has a status, headers, and optional body.
  • Safe methods avoid state changes; idempotent methods are safe to retry from a semantics perspective.
  • Status codes tell you success, redirects, client mistakes, or server failures — learn the common ones by heart.
  • Headers drive caching, security, CORS, and content negotiation.
  • Cookies (and tokens) add state on top of a stateless protocol.
  • HTTPS wraps HTTP in TLS (or QUIC+TLS) so data is encrypted and authenticated.

Explain-It Challenge

Without looking back, explain in your own words:

  1. Why HTTP is called stateless, and how a login still “remembers” you.
  2. The difference between 401 and 403, and between 302 and 304.
  3. Why a POST is neither safe nor idempotent, and one real-world example where that matters.
  4. What problem CORS solves, and who enforces it (browser vs server vs curl).
  5. One way HTTP/2 improves on HTTP/1.1 for loading a page with many small files.

Navigation: ← 1.2.b — Client vs Server · 1.2.d — What Happens When You Visit a Website →