0% found this document useful (0 votes)
1 views16 pages

HTTP Protocol Notes

The document provides an in-depth overview of the HTTP protocol, covering its core principles, versions, request/response anatomy, methods, headers, and status codes. Key topics include statelessness, the client-server model, CORS, caching, and security measures. It serves as a comprehensive guide for understanding HTTP's functionality and its evolution over time.

Uploaded by

amarnaniharsh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views16 pages

HTTP Protocol Notes

The document provides an in-depth overview of the HTTP protocol, covering its core principles, versions, request/response anatomy, methods, headers, and status codes. Key topics include statelessness, the client-server model, CORS, caching, and security measures. It serves as a comprehensive guide for understanding HTTP's functionality and its evolution over time.

Uploaded by

amarnaniharsh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

HTTP Protocol · Notes

HTTP Protocol — Deep Dive Notes


Statelessness · Methods · Headers · CORS · Status Codes · Caching · Compression · TLS
Video walkthrough → exam-ready notes

Contents
1. The Two Core Ideas of HTTP
1.1 Statelessness
1.2 Client-Server Model
2. HTTP vs HTTPS · TCP underneath · OSI model context
3. HTTP Versions — 1.0 → 1.1 → 2.0 → 3.0
4. Anatomy of a Request and Response Message
5. HTTP Headers
5.1 The four categories
5.2 Extensibility & "remote control"
6. HTTP Methods — GET, POST, PATCH, PUT, DELETE, OPTIONS
6.1 Idempotency
7. CORS — Same-Origin Policy, Simple vs Preflight
8. HTTP Status Codes — 1xx, 2xx, 3xx, 4xx, 5xx
9. HTTP Caching — Cache-Control, ETag, Last-Modified
10. Content Negotiation — Accept, Accept-Language, Accept-Encoding
11. HTTP Compression (gzip, deflate, br, zstd)
12. Persistent Connections & Keep-Alive
13. Large Requests (multipart) & Large Responses (streaming)
14. SSL / TLS / HTTPS
15. Cheat-Sheet

1. The Two Core Ideas of HTTP

1.1 Statelessness
HTTP has no memory of past interactions. Each request carries everything the server needs to handle it; once
the response is sent, the server forgets.

Implications
• Every request is self-contained — auth tokens, cookies, params must all be re-sent.
• Server stores no session state by default.

Benefits
Benefit Why it matters

Simplicity Server doesn’t need session storage logic.

Page 1 of 16
HTTP Protocol · Notes

Benefit Why it matters

Scalability Any server in a fleet can handle any request — easy load-balancing.

Resilience If a server crashes, no in-memory session is lost; other servers continue serving.

NOTE Where state actually lives: Because HTTP itself is stateless, developers layer
state on top via cookies, sessions, and tokens (JWT, etc.) for things like logins and
shopping carts.

1.2 Client-Server Model


In every HTTP interaction there is exactly one client and one server. The client initiates; the server responds. The
reverse is never allowed in plain HTTP.
Role Responsibility

Client Initiates requests (browser, mobile app, Postman, another server). Sends URL,
method, headers, body.

Server Listens, processes incoming requests, returns a response (HTML, JSON, file, error,
etc.).

2. HTTP vs HTTPS · TCP Underneath · OSI Model


HTTP and HTTPS can be treated as interchangeable for application-level discussion — HTTPS is HTTP wrapped in
TLS encryption.

Transport layer
HTTP requires a reliable transport. Of the two big internet transport protocols (TCP and UDP), HTTP traditionally
uses TCP — connection-oriented and reliable.
Protocol Connection Reliability Used by

TCP Connection-based (3-way handshake) Reliable (ordered, HTTP 1.x / 2.0


retransmits)

UDP Connectionless Unreliable HTTP 3.0 (via QUIC),


video calls, DNS

Where backend engineers live on the OSI stack


Backend engineers spend almost all their time at Layer 7 — the Application Layer.
Layer Name Examples

7 Application HTTP, gRPC, WebSocket

Page 2 of 16
HTTP Protocol · Notes

Layer Name Examples

6 Presentation Encryption, TLS handshake

5 Session Connection management

4 Transport TCP, UDP

3 Network IP, routing

2 Data Link Ethernet, MAC

1 Physical Cables, radio

EXAM Everything you need to remember: Client and server establish a network
connection. Messages are sent and received. The plumbing below Layer 7 is
network-engineering territory — read up if curious, but not required to be a
productive backend engineer.

3. HTTP Versions — A Quick Evolution


Version Key innovation Problem it solved

HTTP/1.0 One TCP connection per request Original protocol — inefficient (handshake
per request).

HTTP/1.1 Persistent connections, chunked transfer, Reuse one TCP connection for many
caching headers requests.

HTTP/2.0 Multiplexing, binary framing, HPACK Parallel requests over one connection.
header compression, server push

HTTP/3.0 Built on QUIC over UDP — faster connect, Latency, packet loss, mobile networks.
no head-of-line blocking

NOTE Head-of-line blocking: In HTTP/2, although requests are multiplexed at the


application layer, they share a single TCP connection — so a single lost packet
stalls all streams. HTTP/3 fixes this by switching to QUIC over UDP, where each
stream is independent.

4. Anatomy of a Request and Response Message

Request message
HTTP

PUT /api/v1/users/42 HTTP/1.1

Page 3 of 16
HTTP Protocol · Notes

Host: [Link]
Authorization: Bearer eyJhbGciOiJIUzI1...
Content-Type: application/json
Content-Length: 67
Origin: [Link]

{
"name": "Suryanshi",
"bio": "Backend engineer"
}

Breakdown
Part What it is

PUT Request method (intent of the action)

/api/v1/users/42 Resource URL (which resource on the server)

HTTP/1.1 Protocol version

Host: … Domain the request is for

Other lines Request headers — metadata as key:value pairs

Blank line Separates headers from body — required

JSON block Request body — the actual data payload

Response message
HTTP

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 87
Cache-Control: max-age=10
ETag: "3141"
Last-Modified: Wed, 04 Jun 2026 12:30:00 GMT

{
"id": 42,
"name": "Suryanshi",
"updated_at": "2026-06-04T12:30:00Z"
}

Page 4 of 16
HTTP Protocol · Notes

Breakdown
Part What it is

HTTP/1.1 Protocol version

200 Status code (numeric outcome)

OK Status text (human-readable label)

Header lines Response headers — metadata

Blank line Separator

JSON block Response body — the payload

5. HTTP Headers
Headers are key-value pairs that carry metadata about the request or the response.

STORY Parcel analogy: You don’t put the recipient’s address inside a courier package —
you stick it on the outside so every handler along the route can read it without
opening the box. HTTP headers play the same role: machine-readable metadata
anyone in the pipeline (proxies, caches, browsers, servers) can act on quickly
without parsing the body.

5.1 The four header categories


① Request headers — sent by client
Header Purpose

User-Agent Identifies the client (browser, Postman, mobile app)

Authorization Auth credentials (e.g. Bearer token, Basic auth)

Accept What content types the client can handle (application/json, text/html, …)

Origin Where the request came from — used in CORS

Cookie Stored cookies sent back to the server

② General headers — used in both request and response


Header Purpose

Date Timestamp of the message

Connection keep-alive or close

Page 5 of 16
HTTP Protocol · Notes

Header Purpose

Cache-Control Caching directives (no-cache, max-age=…)

③ Representation headers — about the body


Header Purpose

Content-Type MIME type of the body (application/json, text/html, image/png)

Content-Length Size of body in bytes

Content-Encoding Compression applied (gzip, deflate, br)

ETag Unique fingerprint of the resource — used for caching

④ Security headers — defense in depth


Header Protects against

Strict-Transport-Security (HSTS) Protocol downgrade attacks — forces HTTPS only

Content-Security-Policy (CSP) Cross-site scripting (XSS) — restricts where scripts/styles/images can


load from

X-Frame-Options Clickjacking — prevents your page from being embedded in <iframe>

X-Content-Type-Options: MIME-sniffing attacks — browser won’t second-guess Content-Type


nosniff

Set-Cookie ... HttpOnly; Secure Cookie theft — HttpOnly = invisible to JS, Secure = HTTPS only

5.2 Two big ideas behind headers


① Extensibility
New headers can be added without changing the protocol — that’s how HTTP keeps evolving. You can also
define your own custom headers (e.g. X-Request-Id).

② Headers as remote control


Headers let the client influence what the server does — and vice versa — without changing the URL or body.
• Content negotiation: client sends Accept: application/json → server replies with JSON.
• Caching: server sends Cache-Control: max-age=600 → client caches for 10 minutes.
• Authentication: client sends Authorization → server decides whether to grant access.

6. HTTP Methods — Verbs of Intent


Methods express the intent of an interaction — what the client wants the server to do.

Page 6 of 16
HTTP Protocol · Notes

Method Purpose Has body? Idempotent?

GET Fetch a resource — must not modify state No Yes

POST Create a new resource Yes No

PATCH Partial update — only the fields sent are changed (merge) Yes Sometimes

PUT Full replacement — entire resource is overwritten Yes Yes

DELETE Remove a resource Optional Yes

OPTIONS Inquire about server capabilities (used by CORS preflight) No Yes

6.1 Idempotency
A method is idempotent if calling it N times has the same observable effect as calling it once.
Method Why it’s (non-)idempotent

GET Read-only. Calling 100 times = same data, no state change.

PUT Full replacement — you set the resource to X. Doing that again still leaves it at X.

DELETE After the first call the resource is gone. Subsequent calls find nothing to delete —
observable state same.

POST NOT idempotent. Two POSTs to /notes create two notes — different end state.

PATCH Depends on the patch. [Link] = "x" is idempotent. [Link] += 1 is not.

WARNING Common abuse: Developers reach for PUT to update a single field. That’s
semantically wrong — PUT replaces the whole resource. Use PATCH for partial
updates; PUT only for a true full replacement.

7. CORS — Cross-Origin Resource Sharing

Same-Origin Policy (the rule CORS exists to relax)


By default, the browser blocks JS on origin A from reading responses from origin B. "Origin" = scheme + host +
port. Different port, subdomain, or protocol → different origin.
ORIGINS

[Link] and [Link] → different


(scheme)
[Link] and [Link] → different
(subdomain → host)
[Link] and [Link] → different

Page 7 of 16
HTTP Protocol · Notes

(port)

CORS is the mechanism by which the server can opt-in to allow specific cross-origin clients.

Simple Request Flow


No preflight. The browser sends the actual request directly, then checks the response for permission to expose it
to JS.
HTTP

# Client at [Link] calls [Link]


GET /users HTTP/1.1
Host: [Link]
Origin: [Link]

# Server's response MUST include this header, or the browser blocks JS


access:
Access-Control-Allow-Origin: [Link]
# or
Access-Control-Allow-Origin: *

NOTE Important nuance: The request still reaches the server — the server already
executed it. CORS only blocks the browser from exposing the response to your JS.
Damage from non-safe requests has already happened by the time CORS rejects
them — which is exactly why preflight exists.

Preflight Request Flow


Triggered when ANY of these are true (in addition to being cross-origin):
• Method is NOT GET, POST, or HEAD (e.g. PUT, DELETE, PATCH).
• Request includes non-simple headers (e.g. Authorization, custom X- headers).
• Content-Type is anything other than application/x-www-form-urlencoded, multipart/form-data, or
text/plain. (application/json triggers preflight.)

WARNING Backend reality: In practice, almost every modern API call is JSON with an
Authorization header — so almost every cross-origin request triggers a preflight.

Step 1 — Browser sends an OPTIONS preflight


HTTP

OPTIONS /api/v1/users/42 HTTP/1.1


Host: [Link]
Origin: [Link]
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Authorization, Content-Type

Page 8 of 16
HTTP Protocol · Notes

Step 2 — Server responds with CORS capabilities


HTTP

HTTP/1.1 204 No Content


Access-Control-Allow-Origin: [Link]
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 86400 # cache this OK for 24h

Step 3 — Browser then sends the actual request


If the preflight passed every check, the original PUT/DELETE/etc fires normally. If any check fails (origin not
allowed, method not allowed, header not allowed) the browser blocks the actual request — and you see a CORS
error in DevTools.

EXAM Access-Control-Max-Age tells the browser how long it can cache the
preflight result — i.e. how long before another preflight is needed for the same
route + method + headers. Set this in production (e.g. 86400 = 1 day) to avoid
preflighting every single request.

Header Sent by Purpose

Origin Browser (request) Identifies the client origin

Access-Control-Request-Method Browser (preflight) Asks: do you allow this method?

Access-Control-Request-Headers Browser (preflight) Asks: do you allow these headers?

Access-Control-Allow-Origin Server (response) Which origins are allowed (specific


URL or *)

Access-Control-Allow-Methods Server (preflight resp) Which methods are allowed

Access-Control-Allow-Headers Server (preflight resp) Which non-simple headers are


allowed

Access-Control-Max-Age Server (preflight resp) How long browser may cache


preflight result

8. HTTP Status Codes


A 3-digit number that summarizes the result of a request in a standard, language-independent way.
Range Class Meaning

1xx Informational Request received, continuing

2xx Success Request succeeded

3xx Redirection Further action needed

Page 9 of 16
HTTP Protocol · Notes

Range Class Meaning

4xx Client error Something wrong with the request

5xx Server error Something wrong on the server

1xx — Informational (rare in app code)


Code Name Use

100 Continue Used in large uploads — "headers OK, please send body"

101 Switching Protocols Upgrade from HTTP to WebSocket

2xx — Success
Code Name Use

200 OK Generic success — GET returned data

201 Created New resource created — typically after POST

204 No Content Success but no body to return — DELETE, OPTIONS preflight

3xx — Redirection
Code Name Use

301 Moved Permanently Resource lives at new URL forever — update bookmarks.
SEO-friendly.

302 Found / Temp Redirect Temporary detour — keep using the original URL going
forward

304 Not Modified Cached version is still valid (used with ETag / Last-Modified)

4xx — Client Errors


Code Name When to use

400 Bad Request Invalid / malformed request data (wrong type, missing field,
bad format)

401 Unauthorized Missing or invalid auth credentials (no token, expired token)

403 Forbidden Authenticated but not allowed — wrong permissions

Page 10 of 16
HTTP Protocol · Notes

Code Name When to use

404 Not Found Resource doesn’t exist

405 Method Not Allowed Wrong method for this route (e.g. PUT on a read-only
endpoint)

409 Conflict State conflict — e.g. duplicate folder name, optimistic lock
failure

429 Too Many Requests Rate limit exceeded

EXAM 401 vs 403: 401 = "I don’t know who you are." 403 = "I know who you are, and
you can’t do that."

5xx — Server Errors


Code Name When it fires

500 Internal Server Error Unexpected exception, unhandled error — generic fallback

501 Not Implemented Server doesn’t (yet) support this method/feature

502 Bad Gateway Reverse proxy got an invalid response from upstream (Nginx
in front of dead app)

503 Service Unavailable Temporarily down — overload, maintenance

504 Gateway Timeout Upstream server didn’t respond in time

9. HTTP Caching
Store copies of responses so they can be reused instead of refetched — reduces latency, bandwidth, and server
load.

The three headers that drive HTTP caching


Header Direction Purpose

Cache-Control: max-age=10 Server → Client Cache this response for up to 10 seconds

ETag: "3141" Server → Client Unique fingerprint (often a hash) of this version
of the resource

Last-Modified: … Server → Client Timestamp of when the resource was last


changed

If-None-Match: "3141" Client → Server On revalidation — "do you still have this ETag?"

Page 11 of 16
HTTP Protocol · Notes

Header Direction Purpose

If-Modified-Since: … Client → Server On revalidation — "has it changed since this


timestamp?"

Typical revalidation flow


First request — server sends resource + cache hints
HTTP

GET /api/resource HTTP/1.1


Host: [Link]

---

HTTP/1.1 200 OK
Cache-Control: max-age=10
ETag: "3141"
Last-Modified: Wed, 04 Jun 2026 12:30:00 GMT

{ "data": "..." }

Subsequent request — client revalidates with its cached version


HTTP

GET /api/resource HTTP/1.1


Host: [Link]
If-None-Match: "3141"
If-Modified-Since: Wed, 04 Jun 2026 12:30:00 GMT

---

HTTP/1.1 304 Not Modified


(no body — use your cached copy)

When the resource has changed — server sends fresh data + new ETag
HTTP

HTTP/1.1 200 OK
ETag: "2943"
Last-Modified: Wed, 04 Jun 2026 13:00:00 GMT

{ "data": "updated..." }

WARNING Production reality: Maintaining correct ETags server-side is error-prone — forget


to update one and clients keep serving stale data. Modern apps usually rely on
client-side caches (React Query, SWR) or CDN caches with explicit invalidation.

Page 12 of 16
HTTP Protocol · Notes

HTTP-native caching is a useful tool, but not always the right tool.

10. Content Negotiation


The mechanism by which client and server agree on the best representation of a resource — format, language,
encoding.
Negotiation type Client header Example

Media type (format) Accept Accept: application/json

Language Accept-Language Accept-Language: en, es;q=0.9

Encoding (compression) Accept-Encoding Accept-Encoding: gzip, br, deflate, zstd

The server picks the best match it can serve, applies it, and signals back via Content-Type, Content-Language,
Content-Encoding.

11. HTTP Compression


A subset of content negotiation. Client says what it understands (Accept-Encoding); server compresses and
signals via Content-Encoding.

STORY Numbers from the video: A JSON file with 11,000 entries → 3.8 MB compressed
(gzip) vs 26 MB uncompressed. ~85% bandwidth saving on a single response.
Multiply by millions of clients.

Common encodings
Encoding Notes

gzip Universal support, good ratio, very fast

deflate Older, less commonly preferred today

br Brotli — better ratio than gzip; Google-backed

zstd Zstandard — very fast, growing adoption

12. Persistent Connections & Keep-Alive


HTTP/1.0 opened a fresh TCP connection per request → handshake overhead on every call. HTTP/1.1 made
persistent connections the default — one TCP connection is reused for many requests.

Page 13 of 16
HTTP Protocol · Notes

Header value Effect

Connection: keep-alive Reuse the TCP connection for subsequent requests (default in
HTTP/1.1)

Connection: close Close the connection after this response (default in HTTP/1.0)

NOTE You usually don’t touch this header. Defaults are fine. Just know what it means
when you see it in DevTools or Nginx logs.

13. Large Requests and Responses

13.1 Uploading large files — multipart/form-data


When sending a file (image, video, PDF), the request body is split into parts separated by a unique boundary
string.
HTTP

POST /upload HTTP/1.1


Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryABC123
Content-Length: 358291

------WebKitFormBoundaryABC123
Content-Disposition: form-data; name="title"

My photo
------WebKitFormBoundaryABC123
Content-Disposition: form-data; name="file"; filename="[Link]"
Content-Type: image/jpeg

<binary file bytes here>


------WebKitFormBoundaryABC123--

NOTE Why the boundary? Binary file bytes can contain anything — including newlines
and JSON-looking sequences. The boundary is a unique string the parser uses as
a delimiter to know where each part begins and ends. The boundary value is
generated per-request and declared in the Content-Type header.

13.2 Streaming large responses — text/event-stream / chunked transfer


Instead of holding a huge response in memory and sending it in one go, the server streams chunks as soon as
they’re ready. Client builds up the full payload over time.
HTTP

HTTP/1.1 200 OK
Content-Type: text/event-stream

Page 14 of 16
HTTP Protocol · Notes

Cache-Control: no-cache
Connection: keep-alive
Transfer-Encoding: chunked

data: chunk 1\n\n


data: chunk 2\n\n
data: chunk 3\n\n
... (keeps streaming until done)

TIP Use cases: Server-Sent Events (SSE), LLM token streaming (ChatGPT-style
typewriter effect), live logs, large file downloads, real-time dashboards.

14. SSL · TLS · HTTPS


Term What it is

SSL Original encryption protocol for HTTP. Now deprecated due to known vulnerabilities.

TLS Modern, secure successor to SSL. Current recommended version: TLS 1.3.

HTTPS HTTP wrapped in TLS encryption — same protocol, encrypted transport.

How HTTPS protects you


• Encryption — data in transit cannot be read by anyone watching the network.
• Authentication — server presents a certificate signed by a trusted CA (Let’s Encrypt, DigiCert, etc.)
proving it really is who it claims to be.
• Integrity — tampering with packets in transit is detected.

EXAM Practical takeaway: Use HTTPS everywhere. Let Certbot handle Let’s Encrypt
certificates for free. Set HSTS to force browsers to use HTTPS even if a user types
[Link]

15. Cheat-Sheet
Topic Key takeaway

Statelessness Server has no memory. Every request must be self-contained.

Transport HTTP/1 & 2 → TCP. HTTP/3 → QUIC over UDP.

Method intent GET=read · POST=create · PATCH=partial update · PUT=full replace ·


DELETE=remove

Idempotency GET, PUT, DELETE = idempotent. POST is not. PATCH depends.

Page 15 of 16
HTTP Protocol · Notes

Topic Key takeaway

CORS preflight triggers Non-GET/POST/HEAD method, non-simple headers, or non-simple


Content-Type (e.g. application/json).

Status codes 2xx success · 3xx redirect · 4xx client wrong · 5xx server wrong

401 vs 403 401 = "who are you?". 403 = "you can't do that".

Caching Cache-Control + ETag + Last-Modified. 304 = "use your cached copy".

Content negotiation Accept, Accept-Language, Accept-Encoding tell server what you want.

Compression gzip / br typically saves ~70–85% on JSON/text payloads.

Keep-Alive Default in HTTP/1.1. Reuse the TCP connection.

Multipart Use for file uploads. Boundary string separates parts in the body.

Streaming text/event-stream + chunked transfer for live data, SSE, LLM tokens.

HTTPS HTTP + TLS. Always on in production. Free certs via Let’s Encrypt +
Certbot.

Headers as remote control Headers let client and server steer behavior without changing URL or
body.

End of notes — next stop: request & response in code, then auth.

Page 16 of 16

You might also like