HTTP is stateless — so how do sessions work?
Short answer
HTTP is stateless — each request is independent and carries no memory of prior ones. Sessions add state on top: after login, the server issues an identifier the browser stores in a cookie and replays on every request. Server-side sessions keep the state on the server keyed by an opaque session ID; stateless tokens like JWTs put signed state in the token itself so the server can verify without storage.
HTTP is stateless by design: every request stands alone, and the server retains no built-in memory of who sent the previous one. That simplicity scales beautifully, but it conflicts with the need to stay "logged in." Sessions are the layer that adds identity continuity on top of a stateless protocol.
The core mechanism
After you authenticate once, the server issues an identifier and the browser stores it — almost always in a cookie. Because browsers automatically attach cookies to every subsequent request to that site, the server can recognize you on each request without you re-authenticating. The cookie is a bearer credential, which is why its flags (HttpOnly, Secure, SameSite) matter so much.
Two ways to hold the state
Server-side sessions (stateful). The cookie holds an opaque, random session ID. The server keeps the real session data (user ID, roles, expiry) in its own store — memory, Redis, a database — keyed by that ID. Advantages: the server can revoke a session instantly by deleting it, and no sensitive data lives in the cookie. Cost: the server (or a shared store) must hold state, which adds infrastructure when scaling horizontally.
Stateless tokens (e.g. JWT). The token itself carries the claims (user, roles, expiry) and is cryptographically signed. The server verifies the signature on each request and trusts the contents — no lookup needed. Advantages: scales easily across many servers with no shared session store. Costs: the token is valid until it expires, so revocation is hard (you need a denylist or short lifetimes plus refresh tokens), and oversized or sensitive claims can leak.
Why the ID must be unpredictable
Whether opaque ID or signed token, if an attacker can guess, brute-force, or forge it, they hijack the session. So session IDs must be long and from a CSPRNG, and tokens must use a strong signature with the algorithm pinned server-side.
Interviewers look for "HTTP is stateless, cookies carry an identifier," the stateful-vs-stateless trade-off (revocation vs scalability), and the security requirement that the identifier be unguessable.
Likely follow-ups
- What are the trade-offs of server-side sessions vs stateless JWTs?
- How do you revoke a stateless JWT before it expires?
- Why must a session ID be long and unpredictable?