SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

Session vs Token Based Auth

Does the server remember you, or do you carry a pass?

⏱ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

After you log in, the server must know who you are on every next request. There are two common ways to do this.

  • Session based: the server remembers you. It keeps a record and gives you only an id (a cookie).
  • Token based: you carry a signed pass. The server keeps no record and just checks the signature.
  • Sessions are easy to cancel but need shared storage. Tokens scale easily but are hard to cancel before they expire.

02Concept: What is it?

HTTP forgets you after every request. It is stateless. So logging in once is not enough: each later request must prove who you are again. Sessions and tokens are two answers to this one problem.

Session based
The server remembers
  • Server creates a session record after login
  • Browser keeps only a random session id in a cookie
  • Every request: server looks the id up in its store
  • Logging out = delete the record
Token based
You carry the proof
  • Server creates a signed token after login
  • App keeps the token and sends it in a header
  • Every request: server checks the signature and expiry
  • The server stores nothing about you
🧠One line
Session = β€œI will remember you.” Token = β€œShow me your signed pass.”

03Real-Life Example

🍡Cloakroom ticket vs concert wristband
At a cloakroom, you get a small number ticket. The staff keep your coat and a list. To get your coat, they look up your number. At a concert, they put a special wristband on your arm. The guard only checks the band. There is no list to look at.
Real life
Software
Cloakroom ticket number
Session id in a cookie
The staff's list of tickets
Session store (memory, Redis, database)
Guard checks the wristband
Server checks the token signature
Staff cancel a ticket on the list
Delete the session = instant logout
Wristband stays valid until the event ends
Token stays valid until it expires
Two ways to prove who you are
🎟️Sessioncookie: sid=abc123
↓lookup
πŸ—„οΈSession storeabc123 β†’ Asha
🎫TokenBearer eyJ…
↓verify signature
πŸ”‘Secret keyno lookup needed
With a session the server looks something up. With a token it only checks the pass.

04Why Do We Need It?

Both methods exist because HTTP has no memory. Which one you pick changes how your system scales and how safe it is.

🧠HTTP forgets
Each request is separate. We must attach proof of identity to every one.
πŸ“ˆScaling
With many servers, where do we keep the login memory? This decides the design.
🚨Logging out
Can you cut someone off right now? Sessions can. Tokens usually cannot.
πŸ“±Many clients
Mobile apps and other services often prefer tokens in headers over browser cookies.

05Where Do We Use It?

🏦Banking website
Often sessions. Instant logout and revoke matter more than raw scale.
πŸ“±Mobile app + API
Tokens. The app stores a token and sends it with every call.
🧩Microservices
Tokens. A service can check a token without calling a central store.
πŸ”ŒPublic APIs
API keys and bearer tokens in the Authorization header.
πŸ›οΈClassic web apps
Server-rendered sites usually use session cookies.
πŸ”Login with Google
OAuth gives your app an access token, often next to its own session.

06Types / Parts / How It Works

Session based, step by step

  1. 1
    You log in
    Send email and password.
  2. 2
    Server creates a session
    A record like β€œabc123 belongs to Asha”, kept in memory, Redis or a database.
  3. 3
    Server sends the id
    As a cookie: Set-Cookie: sid=abc123.
  4. 4
    Browser sends the cookie each time
    Automatically, on every request to that site.
  5. 5
    Server looks the id up
    Found? You are Asha. Missing? 401 Unauthorized.

Token based, step by step

  1. 1
    You log in
    Send email and password.
  2. 2
    Server creates a signed token
    It holds your id, role and an expiry time. The server signs it with a secret key.
  3. 3
    App stores the token
    In memory, or a secure place. The server keeps nothing.
  4. 4
    App sends it each time
    Header: Authorization: Bearer <token>.
  5. 5
    Server verifies it
    Checks the signature and expiry. Valid? You are Asha.
Many servers: where does the memory live?
Session
βš–οΈLoad balancer
↓
πŸ–₯️
πŸ–₯️
πŸ–₯️
↓
πŸ—„οΈShared storeneeded
Token
βš–οΈLoad balancer
↓
πŸ–₯️
πŸ–₯️
πŸ–₯️
no shared store
Session servers Token servers / shared store Traffic split
Sessions need one shared place. Tokens need none.
PointSessionToken
Where is the state?On the server (store)In the token, held by the client
What does the client hold?A random session idA signed token with claims
Each requestLook the id upVerify the signature
Scaling serversNeeds a shared store or sticky sessionsEasy, any server can verify
Logout / revokeInstant, delete the recordHard, wait for expiry or keep a block-list
Where it travelsCookie (sent by the browser)Authorization header (sent by your code)
Size per requestTiny idLarger, grows with claims
Main attack to watchCSRF (cookie sent automatically)XSS stealing the token from storage
VisualizerFollow one request: session or signed pass?Switch between the two. Then use two servers with sessions kept in each server, and watch what breaks.
How does the server know you?
How many servers?
Where are sessions kept?
πŸ™‚Browserno pass yet
→↓email + password
πŸ–₯️Server Akeeps sessions in memory
Step 1 of 4
1. You log in
You send your email and password to Server A. It checks them.
VisualizerCut a thief off: who is faster?Press the red button. Compare an instant session logout with a token that must expire first.
Method
🦹Attackeruses the stolen login
→↓request
πŸ–₯️Server200: allowed
Clock
0 min
Pass expires in
n/a
Attacker
Still in
Everything looks normal. Press the red button to cut this user off.

07How to Use It / Steps / Implementation

Doing sessions well

  • Use a long, random session id that cannot be guessed.
  • Set the cookie flags: HttpOnly (scripts cannot read it), Secure (HTTPS only) and SameSite (helps stop CSRF).
  • With many servers, keep sessions in a shared store such as Redis, with an expiry time.
  • Make a new session id after login, to stop session fixation.

Doing tokens well

  • Keep the access token short (for example 5 to 15 minutes).
  • Use a longer-lived refresh token to get new access tokens. Store it safely, and rotate it.
  • Always send tokens over HTTPS. Do not put secrets inside a token. Anyone can read it.
  • Verify the signature, the expiry and who the token is for, on every request.

How to choose

  1. Browser-only site, one team, need instant logout? Start with sessions.
  2. Mobile apps, many services or third-party clients? Use tokens.
  3. Many servers with sessions? Add a shared store.
  4. Many tokens in a big system? Keep them short and add a refresh flow.
πŸ’‘You can mix them
Many real systems use a session cookie for the website and tokens for the mobile app and the API. They do not exclude each other.

08Key Terms to Know

TermMeaning in easy words
StatelessThe server keeps no memory of earlier requests. HTTP is stateless.
SessionA record on the server saying a certain user is logged in.
Session idA random string that points to the session. Kept in a cookie.
CookieA small piece of data the browser stores and sends back to the same site.
TokenA signed piece of data that proves who you are.
Bearer tokenA token you send in the Authorization header. Whoever β€œbears” it is trusted.
Access tokenA short-lived token used to call the API.
Refresh tokenA longer-lived token used only to get a new access token.
Sticky sessionThe load balancer always sends one user to the same server.
RevokeCancel a login before it would end by itself.
CSRFAn attack that tricks your browser into sending its cookie to a site you did not mean to use.
XSSAn attack that runs bad script in a page. It can steal tokens kept where scripts can read.

09Pros, Cons and Trade-offs

βœ… Pros
  • Session: instant logout and revoke.
  • Session: tiny id, the real data stays on the server.
  • Session: simple and well understood for websites.
  • Token: any server can verify, with no shared store.
  • Token: works well for mobile apps and other services.
⚠️ Cons
  • Session: needs a shared store with many servers.
  • Session: every request costs a lookup.
  • Session: cookies bring CSRF risk.
  • Token: hard to revoke before expiry.
  • Token: bigger on every request, and stolen tokens work until they expire.

Trade-offs

ChoiceWe gainWe lose
SessionsControl and instant revokeA store to run and a lookup each time
TokensEasy scaling, no lookupHard revoke, trust until expiry
Short token lifeLess damage if stolenMore refreshes
Block-list for tokensCan revokeYou are back to a lookup
⚠️Neither is β€œmore secure” by itself
Safety comes from doing the details right: HTTPS, cookie flags, short lives and safe storage. A badly stored token is as risky as a badly protected cookie.

10Common Problems and Mistakes

Common mistakes

  1. Sessions in server memory with many servers. Users get logged out at random when the load balancer picks another server.
  2. Long-lived tokens. A stolen token works for days.
  3. Keeping tokens where scripts can read them (like localStorage) on a site with XSS risk.
  4. Cookies without HttpOnly, Secure or SameSite.
  5. Putting secrets or private data inside a token. The payload is readable by anyone.
  6. Not checking expiry or audience when verifying a token.
  7. No logout plan for stolen accounts.
πŸ”€Session fixation
An attacker sets your session id first. Fix: make a new id after login.
🎭CSRF
A bad site makes your browser send its cookie. Fix: SameSite cookies and CSRF tokens.
πŸ•·οΈXSS token theft
Bad script reads a token from storage. Fix: HttpOnly cookies and a strict content policy.
⏳Revoke gap
A token lives on after you disable the account. Fix: short life and a block-list.

11Real-World Examples

πŸ›οΈTraditional web frameworks
Many server-rendered frameworks use cookie sessions by default.
πŸ“±Mobile apps
Commonly use access and refresh tokens to talk to their backend.
πŸ”Login with Google or GitHub
Use OAuth tokens. Your own site then often starts its own session.
☁️Cloud APIs
Often use signed tokens or keys in the Authorization header.
πŸ“Note
These are general ideas. Each company mixes the two in its own way.
A common mix
🌐Websitesession cookie
→↓cookie
πŸ–₯️Web backend
↔
πŸ”ŒAPIverifies tokens
←bearer token
πŸ“±Mobile app
Website uses a session cookie. Mobile app and other services use short tokens, refreshed when needed.

12Related Topics to Read Next

Authentication vs Authorization→

Login proves who you are. Then we check what you may do.

JWT→

The most common format for signed tokens.

OAuth / OAuth2β†’

How an app gets a token on your behalf.

Single Sign-On (SSO)β†’

One login for many apps, often built on tokens.

Rate Limiting→

Limits how often one user or token can call an API.

HTTP / HTTPS→

Cookies and headers travel over HTTP, so use HTTPS.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Problem: HTTP forgets you, so every request needs proof of identity.
  • βœ”Session: server remembers you. Client holds an id. Easy revoke, needs a shared store at scale.
  • βœ”Token: client holds a signed pass. No lookup, scales easily, hard to revoke.
  • βœ”Cookies: HttpOnly + Secure + SameSite, always.
  • βœ”Tokens: short access token + refresh token. Never put secrets inside.
  • βœ”Attacks: sessions fear CSRF. Tokens in storage fear XSS.
  • βœ”Pick: website with instant logout? sessions. Mobile, APIs, microservices? tokens. Often both.
← Previous
Authentication vs Authorization
Next β†’
JWT