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.
| Property | What it means |
|---|---|
| Application layer | HTTP 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. |
| Stateless | Each request is independent: the server does not inherently remember past requests. State is added with cookies, tokens, sessions, or application design. |
| Request–response | The client sends a request; the server returns one response per request (with nuances for HTTP/2+ streams). |
2. HTTP Versions
| Version | Era / notes | Highlights |
|---|---|---|
| HTTP/0.9 | 1991 | Single line (GET /path), only GET, response was raw HTML — no headers. |
| HTTP/1.0 | 1996 (RFC 1945) | Full request/response with headers; one request per TCP connection typical (connection closed after response). |
| HTTP/1.1 | 1997+ (RFC 9110 family) | Persistent connections (Connection: keep-alive), pipelining (limited in practice), chunked transfer, Host header required, many semantics we use today. |
| HTTP/2 | 2015 (RFC 9113) | Binary framing, multiplexing many streams on one connection, header compression (HPACK), optional server push (deprecated in practice for many stacks). |
| HTTP/3 | 2022 (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 |
|---|---|
| Host | Which site on a shared IP (required in HTTP/1.1 for named hosts). |
| User-Agent | Client software identity (browser, bot, library). |
| Accept | What content types the client prefers (e.g. text/html, application/json). |
| Content-Type | Media type of the body (e.g. application/json; charset=utf-8). |
| Authorization | Credentials (e.g. Bearer …, Basic …). |
| Cookie | Previously 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
| Method | Typical use | Safe? | Idempotent? |
|---|---|---|---|
| GET | Read a resource (page, JSON) | Yes | Yes |
| POST | Create resource, submit forms, non-idempotent actions | No | No |
| PUT | Replace a resource at a URL (full representation) | No | Yes |
| PATCH | Partial update of a resource | No | Not guaranteed (often treated as non-idempotent) |
| DELETE | Remove a resource | No | Yes |
| HEAD | Same as GET but no body (headers only) | Yes | Yes |
| OPTIONS | CORS preflight, discover allowed methods | Yes | Yes |
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-Type | Type of body (text/html; charset=utf-8, application/json). |
| Content-Length | Body size in bytes (unless chunked encoding). |
| Set-Cookie | Ask client to store cookies for future requests. |
| Cache-Control | Who 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
| Family | Meaning |
|---|---|
| 1xx | Informational — request received, continue processing. |
| 2xx | Success. |
| 3xx | Redirection — client should look elsewhere (or use cache). |
| 4xx | Client error — bad request, auth, forbidden, etc. |
| 5xx | Server error — server failed despite valid-looking request. |
7.2 Codes called out in this curriculum
| Code | Name | Typical meaning |
|---|---|---|
| 200 | OK | Success; body contains the resource. |
| 201 | Created | Resource created; often Location header with URL. |
| 204 | No Content | Success; no body (e.g. delete succeeded). |
| 301 | Moved Permanently | Resource has a new permanent URL. |
| 302 | Found | Temporary redirect (historically misused like 303). |
| 304 | Not Modified | Cached copy still valid (used with conditional requests). |
| 400 | Bad Request | Malformed syntax or invalid parameters. |
| 401 | Unauthorized | Authentication required or failed. |
| 403 | Forbidden | Authenticated but not allowed. |
| 404 | Not Found | No resource at this URL. |
| 405 | Method Not Allowed | Verb not supported for this path. |
| 429 | Too Many Requests | Rate limited; often Retry-After. |
| 500 | Internal Server Error | Generic server failure. |
| 502 | Bad Gateway | Upstream server invalid response (proxy/gateway). |
| 503 | Service Unavailable | Temporary overload or maintenance. |
| 504 | Gateway Timeout | Upstream did not respond in time. |
8. HTTP Headers Deep Dive
8.1 Request headers (selection)
| Header | Purpose |
|---|---|
| Accept, Accept-Language, Accept-Encoding | Content negotiation — preferred types, languages, compression (gzip, br). |
| If-None-Match / If-Modified-Since | Conditional GET — enable 304 and save bandwidth. |
| Origin | Sent with CORS-sensitive requests; server echoes policy in response. |
| Referer | Where the user came from (privacy-sensitive; often stripped). |
8.2 Response headers (selection)
| Header | Purpose |
|---|---|
| ETag / Last-Modified | Validators for caching and conditional requests. |
| Vary | Tells caches which request headers affect the chosen representation. |
| Content-Security-Policy | Restricts 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
| Mechanism | Idea |
|---|---|
| Cache-Control | Directives for browsers and CDNs (max-age, s-maxage, no-store, private). |
| ETag / If-None-Match | Revalidate without full download. |
| Expires | Legacy absolute expiry time. |
9. Cookies and Sessions
HTTP is stateless, but apps need state (logged-in user, cart, preferences).
- Server sends
Set-Cookiein a response. - Browser stores name/value + attributes (
Path,Domain,Expires/Max-Age,HttpOnly,Secure,SameSite). - On later requests to matching URLs, browser sends
Cookieheader 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.css→ 200 + CSS bodyGET /assets/app.js→ 200 + 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:
- Why HTTP is called stateless, and how a login still “remembers” you.
- The difference between 401 and 403, and between 302 and 304.
- Why a POST is neither safe nor idempotent, and one real-world example where that matters.
- What problem CORS solves, and who enforces it (browser vs server vs curl).
- 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 →