What it is
In session-based authentication the server remembers who is logged in. At login it creates a session record (user id, creation time, expiry, maybe roles and a CSRF secret) in a store, and gives the browser only a random session id in a cookie. Every later request carries the cookie; the server looks the id up and knows the user.
Why it exists
HTTP is stateless: each request stands alone. Asking for the password on every request is impossible, and putting the user id in a cookie the client can edit is insecure. A random, unguessable id that points at state only the server can change solves both: the browser can present it, but cannot forge or alter it.
How it works
Login. The server verifies the password against a slow, salted hash (Argon2id, scrypt or bcrypt) or verifies a passkey assertion. It then generates a new session id from a cryptographically secure random generator (128 bits is common practice; OWASP’s minimum is 64 bits of entropy), stores the session, and answers with Set-Cookie. Issuing a fresh id at login, and again when privileges change, prevents session fixation, where an attacker plants a known id before the victim logs in.
The cookie. A typical header:
Set-Cookie: __Host-sid=k3Jq…; Path=/; Secure; HttpOnly; SameSite=Lax
HttpOnly: invisible to JavaScript, so an XSS bug cannot read and exfiltrate it (it can still make requests from the page while the user is there).Secure: only sent over HTTPS.SameSite=Lax: not sent on cross-site subrequests or cross-site POSTs, still sent on top-level GET navigations.Strictalso withholds it on cross-site navigations (users arriving from a link appear logged out on the first page).NoneneedsSecureand turns the protection off.__Host-prefix: the browser accepts the cookie only if it isSecure, hasPath=/and noDomain, so other subdomains cannot set or overwrite it.- Without
Expires/Max-Ageit is a session cookie (dropped when the browser decides the session ends); with one it persists. Server-side expiry is what actually counts.
Every request. The app reads the cookie, fetches the session from the store and proceeds, or answers 401 if there is none. With several app servers the store must be shared (or the load balancer must pin each user to one server: sticky sessions).
Expiry and logout. An idle timeout (for example 15–30 minutes for sensitive apps) and an absolute lifetime (for example 8–24 hours) bound forgotten sessions. Logout deletes the record server-side and clears the cookie. “Log out everywhere” deletes all of a user’s sessions, which needs an index from user to sessions.
CSRF. Because the browser attaches cookies automatically, another site can make the browser send a request to yours with the user’s cookie. Defences, in layers: SameSite cookies; a CSRF token (a per-session secret that the page includes in a hidden field or header, which another origin cannot read); checking Origin or Sec-Fetch-Site on state-changing requests; and never changing state on GET.
When to use it
Browser applications served from one site (or a site and its own API), especially when you need instant logout, account suspension or “sign out other devices”. It is also the standard back-end-for-frontend pattern: the browser holds a session cookie and the server holds any OAuth tokens.
When not to
- Third-party API clients and machine-to-machine calls, which do not have cookie jars: use OAuth access tokens.
- Many independent services that would each need access to the session store; there, a gateway or BFF typically converts the session into short-lived tokens for internal calls.
- Native mobile apps can use sessions, but token-based flows with platform secure storage are the usual fit.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Server-side sessions vs self-contained tokens | Instant revocation, nothing sensitive in the client, small cookie | A store lookup per request; a store to run highly available |
| Sessions in the main relational database | No new infrastructure, durable | Session reads compete with business queries; easy to saturate |
| In-memory store (Redis, Valkey, Memcached) | Sub-millisecond lookups, built-in TTLs | Another stateful system; data loss on restart unless persisted or replicated |
| Sessions in app server memory + sticky sessions | No store at all | Uneven load; restarts and deploys log users out |
| SameSite=Strict vs Lax | Stronger CSRF protection | Users following a link from elsewhere arrive logged out |
Alternatives
- Self-contained tokens (JWT): the server verifies a signature instead of looking anything up. No store on the hot path; revocation becomes the hard part.
- Signed or encrypted cookies holding the session data (as some web frameworks offer): no store, but the same revocation problem as tokens and a 4 KB cookie limit.
- OAuth 2.0 / OpenID Connect with an external identity provider: hands login to a dedicated service; your app usually still keeps its own session afterwards.
Failure modes
- Store saturation: every request reads the store, so a store sized for logins collapses at peak traffic and takes every authenticated page with it.
- Store outage: nobody can be identified. An empty restart logs out every user.
- Session fixation: reusing a pre-login id after login.
- Predictable ids: ids from counters or weak random generators can be guessed.
- Missing CSRF defences on state-changing endpoints, or state changes on GET.
- Cookie scope too broad: a
Domain=example.comcookie is sent to, and can be overwritten by, every subdomain. - Sessions that never expire: stolen cookies stay useful indefinitely.
In production
Use your framework’s session middleware rather than rolling your own. Keep sessions in a replicated in-memory store with TTLs and a failover plan, or in a database table with an index on the id if traffic is modest. Monitor store latency and hit rate alongside request latency. Rotate the id on login and privilege changes. Offer “sign out other devices”. Store as little as possible in the session (ids and flags, not whole user profiles), so the record stays small and changes to user data do not leave stale copies.
Common misconceptions
- “HttpOnly cookies make XSS harmless.” They stop the cookie being stolen; injected script can still act as the user while the page is open.
- “SameSite solves CSRF completely.” It stops most cross-site sends, but same-site subdomains are not cross-site, and Lax still sends cookies on top-level GETs. Keep tokens or Origin checks for state-changing requests.
- “Sessions don’t scale.” A key lookup in an in-memory store is cheap; large sites run sessions. The real requirement is that the store is sized and replicated like any other critical dependency.
- “Logging out in the browser ends the session.” Only deleting it on the server does. Clearing the cookie alone leaves any copy valid.
Interview angle
Expect to compare sessions with JWTs: lookup per request versus local verification, instant revocation versus waiting for expiry. Mention the cookie flags by name, a shared store for horizontally scaled app servers (and why sticky sessions are a weaker option), sizing the store by request rate, replication of the store, and CSRF. A strong answer lands on a hybrid: sessions at the browser edge (often via a BFF), short-lived tokens between internal services.
Model assumptions
Login, cookies, logout and CSRF are a scripted illustration: packets are placed by hand with illustrative durations (10 ms between browser and load balancer, 3 ms inside the data centre). The engine has no model of cookies, passwords or browser same-site rules. The per-request lookup is simulated: Poisson arrivals, a load balancer with 1 ms of work, two app servers with 32 workers and 3 ms mean service time (lognormal, cv 0.3) and room for 60 waiting requests each, then the session store, then an app database with 32 connections and 4 ms reads. The session store is modelled as a lookup service with a connection pool: first a sessions table with 4 connections reserved and 6 ms per lookup (cv 0.4) to stand for a relational database under contention, then an in-memory store with 16 connections and 0.5 ms per lookup. A failed store refuses connections and the request fails. Numbers are illustrative orders of magnitude, not benchmarks of any database.