On this page

Session-Based Authentication

Session-based authentication means the server remembers who you are. You log in once, the server stores your login info, and gives your browser a small session ID to show on every request.

How It Works

  1. User sends username and password.
  2. Server verifies them and creates a session (stored on the server).
  3. Server sends the session ID back in a cookie.
  4. Browser sends this cookie automatically with every request.
  5. Server looks up the session ID to identify the user.

Think of a cloakroom token: you hand over your bag once and get token #42. After that, you just show #42. The bag (your data) stays with the cloakroom (server).

This is called stateful authentication, because the server keeps state for every logged-in user.

Where Sessions Are Stored

StorageProsCons
Server memoryFastest, simplestLost on restart, doesn't work across servers
Redis (shared store)Fast, shared by all serversExtra component to run
DatabaseDurableSlower, adds load per request

The scaling problem: If a user logs in on Server A but the load balancer sends the next request to Server B, Server B doesn't know the session.

Two common fixes:

  • Sticky sessions: The load balancer always sends the same user to the same server, so that server always has their session. But if that server crashes, its sessions are lost and users get logged out. Also, users can't be moved, so one server may get overloaded while others stay idle.

  • Shared session store (Redis): All servers read sessions from one place. This is the usual choice.

Security Basics

  • HttpOnly cookie: JavaScript can't read it (protects against XSS stealing it).
  • Secure cookie: sent only over HTTPS.
  • SameSite cookie: limits cross-site requests (protects against CSRF).
  • Regenerate session ID after login to prevent session fixation.
  • Expiry: idle timeout (e.g., 30 min) plus an absolute timeout.

Pros and Cons

ProsCons
Instant logout/revocation: just delete the sessionServer must store state for every user
Session ID is small and reveals nothingNeeds a shared store when scaling horizontally
Simple, battle-tested for web appsEvery request needs a session lookup
Easy to update user data server-sideCookies are awkward for mobile apps and third-party APIs

When to Use It

  • Traditional web apps with a browser front end
  • Monolith or a small number of servers
  • Apps needing force logout (banking, admin panels)

For many microservices or mobile clients, token-based authentication usually fits better.

Summary

Next, we'll see Token-based authentication , where the server stops storing sessions and the client carries its own proof.

Next TopicScalability Fundamentals