← Back to Index

5. Web Concepts

Sessions

HTTP is stateless — each request is independent. Sessions allow servers to maintain state across multiple requests from the same client.

Approaches:

# Session-based authentication
POST /login { "username": "alice", "password": "***" }
Server validates credentials, creates session, returns:
Set-Cookie: session_id=abc123; HttpOnly; Secure

GET /profile
Cookie: session_id=abc123
Server looks up session, finds user_id=42, returns profile

Serialization

Serialization converts an in-memory object into a format that can be stored or transmitted. Deserialization reverses this.

FormatHuman-ReadableBinarySchema RequiredPerformance
JSONYesNoNoModerate
XMLYesNoOptionalSlower
Protocol BuffersNoYesYes (.proto)Fast
AvroNoYesYes (inline/separate)Fast
MessagePackNoYesNoFast
# JSON Serialization (Python dict → JSON string)
{"user": {"id": 42, "name": "Alice", "roles": ["admin"]}}

# Protocol Buffers (compact binary, ~40% smaller than JSON)
message User { int32 id = 1; string name = 2; repeated string roles = 3; }

CORS (Cross-Origin Resource Sharing)

CORS is a browser security mechanism that restricts web pages from making requests to a different domain than the one that served the page. The server specifies allowed origins via HTTP headers.

# Server response header to allow cross-origin requests
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization

# Preflight request (OPTIONS) for non-simple requests
OPTIONS /api/data
Origin: https://myapp.com
Access-Control-Request-Method: DELETE

Idempotency

An operation is idempotent if performing it multiple times has the same effect as performing it once. Crucial for distributed systems where retries are common.

Exercise: Your API receives duplicate payment requests due to network retries. Design an idempotency mechanism using an idempotency key. How do you store it? When do you expire it? What happens if the server crashes mid-processing?