AlgoMaster Logo

Session-Based vs Token-Based Authentication

High Priority9 min readUpdated July 4, 2026
AI Mock Interview

Practice this topic in a realistic system design interview

Listen to this chapter
Unlock Audio

After a user signs in, the server has to answer the same question on every later request: how do I know this request is still from that signed-in user? HTTP does not remember earlier requests, so the client has to send some proof each time.

Two patterns dominate. Session-based authentication stores a random session ID on the client, usually in a cookie, and keeps the real session data on the server. Token-based authentication stores a token on the client and sends it with each request. The token may be just a random reference, or it may be self-contained, such as a JWT that carries facts about the user inside it.

The real question is not "which one scales?" Both can scale. The better question is: where does the authentication state live, and how quickly can you change or revoke it? Revoking means making a login, session, or token stop working. That difference drives most of the tradeoffs in this chapter, from logout behavior to stolen credentials.

1. The Core Problem

HTTP is stateless. A server does not automatically know that request 20 belongs to the same user who logged in on request 1.

The system needs proof the client can present after login. That proof should identify the signed-in user or client, expire, be protected from theft, support logout or revocation when needed, and work for the client type: browser, mobile app, CLI, backend service, or third-party API client.

Sessions and tokens solve this problem differently.

2. Session-Based Authentication

In session-based authentication, the server creates a session record and gives the client a random session ID.

The session ID is only a reference, like a claim ticket. The real session data lives on the server.

POST /loginValidate credentials and MFAGenerate random session_idSave session record under session_idOKSet-Cookie: __Host-session=...GET /dashboard with cookieLookup session_iduser_123, tenant_id, session metadataDashboard responseBrowserAppSession StoreBrowserAppSession Store
10 / 10
algomaster.io

What the Server Stores

A session record commonly includes:

FieldPurpose
Session ID hashLookup key for the session
User IDSigned-in user
Tenant or account scopeCurrent organization or workspace
Created atSession creation time
Last seen atActivity tracking and idle timeout
Expires atAbsolute timeout
MFA stateWhether strong authentication was completed
Device detailsUser agent, device ID, approximate location
Revoked atExplicit logout or admin revocation

Store a hash of the session ID rather than the raw session ID when practical. If the session store leaks, raw active session IDs can be used like passwords.

Browser sessions are usually carried in cookies.

Important attributes:

AttributeWhy it matters
SecureSends the cookie only over HTTPS
HttpOnlyPrevents JavaScript from reading the cookie
SameSiteReduces CSRF risk for cross-site requests
Path=/Required for the __Host- prefix
__Host- prefixPrevents Domain scoping and requires Secure + Path=/
Max-Age / ExpiresControls cookie lifetime

SameSite=Lax is often a practical default for web apps. Strict is stronger but can break legitimate navigation from other sites. Sensitive actions should still use CSRF protection, such as CSRF tokens or a well-designed double-submit pattern.

Scaling Sessions

Sessions keep state on the server, but that does not mean they cannot scale.

Common designs:

DesignHow it worksTradeoff
Single server memorySession lives in application memorySimple, but fragile
Sticky sessionsLoad balancer keeps user on the same serverFailover and rebalancing are harder
Shared storeAll servers use Redis, Memcached, or a databaseExtra dependency and network hop
Replicated storeSession data is copied across nodesMore operational complexity

For most production web apps, a shared store such as Redis is straightforward and fast enough. The session lookup is usually not the bottleneck. Slow database queries, external APIs, template rendering, and over-fetching are more often the real cost.

Strengths

  • Immediate logout and admin-driven revocation
  • Easy active-session management across devices
  • Small client-side value, since the browser only holds a session ID
  • The server can update session state without issuing a new client token
  • Strong browser story with HttpOnly, Secure, and SameSite cookies

Weaknesses

  • Require server-side session storage
  • Need CSRF protection when cookies are sent automatically
  • Depend on a shared session store, which adds another system to run
  • Cross-domain applications need careful cookie and CORS design

3. Token-Based Authentication

In token-based authentication, the client sends a token with each request.

Tokens come in two broad forms:

  • Opaque tokens: random strings that must be looked up by a server.
  • Self-contained tokens: signed tokens, usually JWTs, that carry facts about the user or client inside the token.

This distinction matters. Not every token is a JWT, and not every token system avoids server-side state.

Self-Contained Token Flow

The sequence below follows a self-contained token from login to an API call. The API verifies the token and returns data without looking up a server-side session.

Login or token grantValidate user or clientAccess tokenGET /orders with Authorization: Bearer tokenValidate signature, issuer, audience, expiryOrders responseClientAuth ServerAPIClientAuth ServerAPI
6 / 6
algomaster.io

The API can validate the token without a session lookup if it has the issuer's public key or shared secret. That is useful in distributed systems, but it moves complexity into token lifetime, key rotation, token contents, and revocation.

JWT Basics

A JWT has three Base64Url-encoded parts:

The payload is encoded, not encrypted. Anyone holding the token can read the claims, which are the facts stored inside the token.

Common claims:

ClaimMeaning
subUser or client ID
issIssuer
audIntended audience
expExpiration time
nbfNot valid before
iatIssued at
jtiToken identifier

APIs must validate more than the signature. They should check who issued the token, who it is meant for, whether it has expired, which algorithm and key signed it, and whether it includes the required scopes or permissions.

Access Tokens and Refresh Tokens

Production token systems often use two token types:

TokenLifetimePurpose
Access tokenShortSent to APIs
Refresh tokenLongerUsed to obtain new access tokens

Access tokens should be short-lived because whoever holds the token can use it. If stolen, the token usually works until it expires or is revoked.

Refresh tokens need stronger protection because they can be used to get new access tokens. For browser apps, many teams store refresh tokens in HttpOnly, Secure, SameSite cookies and keep access tokens in memory. For mobile apps, use platform secure storage. For backend services, use managed workload identity or a secret manager instead of hardcoded long-lived tokens.

Token Storage in Browsers

Browser storage is one of the easiest places to make a token-based design unsafe.

StorageMain riskNotes
JavaScript memoryLost on refreshSafer than persistent storage, but still vulnerable to active XSS
localStorageToken theft through XSSPersistent and readable by JavaScript
sessionStorageToken theft through XSSCleared when the tab closes, still readable by JavaScript
HttpOnly cookieCSRF if not protectedNot readable by JavaScript, but sent automatically
Backend-for-Frontend sessionServer stores tokens; browser stores only a session cookieOften the safest pattern for browser apps

Do not treat localStorage as a safe default for sensitive browser tokens. It is convenient, but an XSS bug can read and steal the token.

For many browser apps, the best design is still cookie-based: either a traditional server-side session or a Backend-for-Frontend that keeps OAuth tokens on the server and gives the browser only an HttpOnly session cookie.

Strengths

  • Work well for APIs, mobile apps, CLIs, and service-to-service calls
  • Self-contained tokens avoid a central lookup on every API call
  • Can carry audience, scope, and expiration in a standard format
  • Fit OAuth 2.0 and OpenID Connect cleanly when many services validate the same token

Weaknesses

  • Revocation is harder for self-contained tokens
  • Old claims remain valid until expiration unless extra checks exist
  • Large tokens increase request size
  • Key rotation and issuer/audience validation must be correct
  • Browser storage choices create XSS or CSRF tradeoffs

4. The Real Tradeoffs

The old framing is "sessions are stateful, tokens are stateless." That is partly true, but it hides the real design choices.

The real tradeoffs are practical.

ConcernSession-basedToken-based
Server-side stateRequiredOptional, depending on token type
Logout and revocationDirectEasy for lookup-based tokens, harder for self-contained tokens
Browser safetyStrong with HttpOnly cookiesDepends heavily on storage design
CSRFRelevant for cookiesRelevant if tokens are stored in cookies
XSS token theftReduced by HttpOnly cookiesHigh if tokens are readable by JavaScript
API/service usePossible, but less commonNatural fit
Claim freshnessServer can check current stateClaims may be old until token refresh
Request sizeSmall cookieJWTs can be large
Main dependencySession storeToken issuer, keys, revocation plan

Revocation

Sessions are easy to revoke: delete the session or mark it as revoked.

Self-contained access tokens are harder. If an access token is valid for 30 minutes, removing a user's role may not affect that token until it expires.

Common ways to reduce the risk:

  • Short access token lifetime.
  • Refresh token rotation.
  • Revocation list for high-risk tokens.
  • Permission version checked server-side.
  • Server-side token checks for sensitive APIs.
  • Step-up authentication for dangerous actions.

Freshness of Authorization

Putting roles and permissions in a JWT avoids a lookup, but it can make authorization old.

If a user loses billing_admin, an old token may still contain that role. For low-risk reads, a short delay may be acceptable. For production access, payments, security settings, or user management, check current authorization on the server or use short token lifetimes.

Performance

Session lookup versus token verification is rarely the deciding factor.

A Redis lookup may add a small network call. JWT verification uses CPU and may require key lookup or key caching. Large JWTs also increase bandwidth on every request.

Choose based on correctness, revocation, client type, and operational simplicity before optimizing for a few milliseconds.

5. When to Use Sessions

Use session-based authentication when:

  • You are building a browser-first web application.
  • You want simple logout and revocation.
  • You need active-session management across devices.
  • You want the browser to store only a random reference.
  • Your app can use first-party cookies.
  • You want to avoid exposing tokens to JavaScript.

Sessions are a strong default for traditional web apps and many modern SaaS apps. They are not old-fashioned. A well-designed Redis-backed session system is easy to reason about and scales well.

6. When to Use Tokens

Use token-based authentication when:

  • You are building public APIs for third-party clients.
  • You have mobile apps, CLIs, or desktop clients.
  • You need OAuth 2.0 delegated access.
  • Multiple services need to validate a token independently.
  • You are doing service-to-service authentication.
  • You want short-lived access tokens with scoped permissions.

Prefer short-lived access tokens. Keep refresh tokens protected and revocable. For service-to-service auth, prefer platform identity such as cloud IAM, workload identity, mTLS, or SPIFFE-style identities over manually shared long-lived bearer tokens.

7. Hybrid Patterns

Many production systems use both.

Browser App + Backend-for-Frontend

The browser stores an HttpOnly session cookie. The Backend-for-Frontend stores access and refresh tokens on the server and calls the APIs behind it.

This keeps sensitive tokens out of JavaScript while still using token-based authentication between backend components.

Short-Lived Access Token + Refresh Session

The client receives a short-lived access token and uses a protected refresh mechanism to get new tokens.

This limits the damage if an access token is stolen while keeping API calls efficient.

Opaque Tokens + Server Check

The API receives an opaque token and asks the authorization server whether it is still active.

This improves revocation and keeps authorization current, but it adds a network call unless results are cached.

8. Security Checklist

For sessions:

  • Generate hard-to-guess random session IDs.
  • Store only a hash of the session ID when practical.
  • Use Secure, HttpOnly, and SameSite cookies.
  • Rotate session IDs after login and privilege changes.
  • Enforce idle and absolute timeouts.
  • Protect state-changing requests from CSRF.
  • Revoke sessions on logout, password reset, MFA reset, and account disablement.

For tokens:

  • Use short-lived access tokens.
  • Validate issuer, audience, expiration, signature, algorithm, and key ID.
  • Rotate signing keys safely.
  • Keep sensitive data out of token payloads.
  • Avoid long-lived bearer tokens.
  • Protect refresh tokens more strongly than access tokens.
  • Plan revocation before launch.
  • Do not store sensitive browser tokens in localStorage by default.

For both:

  • Use HTTPS everywhere.
  • Log authentication and revocation events.
  • Rate limit login and token endpoints.
  • Require step-up authentication for sensitive actions.
  • Treat internal service calls as authenticated and authorized requests.

Summary

Session-based authentication stores state on the server and gives the client a random reference. It is a strong default for browser applications because revocation is simple and cookies can be protected from JavaScript.

Token-based authentication gives clients a token they send to APIs. It is a strong fit for APIs, mobile apps, CLIs, service-to-service calls, and OAuth/OIDC systems, but it requires careful handling of storage, expiration, key rotation, and revocation.

Do not choose tokens just because they sound more scalable. Choose based on the client, security risks, revocation needs, and how current authorization must be. In many production systems, the best answer is a hybrid: browser sessions at the edge, short-lived tokens behind the edge.

Quiz

Session vs Token Based Auth Quiz

10 quizzes