Table of Contents
How Sessions Work
- User logs in → server creates a session record in the database
- Server sends a
session_id cookie to the client
- On every request, the server looks up
session_id in the DB
- If found and valid, the user is authenticated
Pros: Instant revocation, simple to implement, small cookie
Cons: Every request hits the DB, hard to scale horizontally
How JWTs Work
- User logs in → server creates a signed JWT with user claims
- JWT is sent to the client
- On every request, the server verifies the signature — no DB lookup
- Claims in the payload are trusted
Pros: Stateless, scalable, works across microservices
Cons: Can't revoke until expiry, payload is visible (just Base64)
Key Tradeoffs
| Feature | Session | JWT |
|---|
| Revocation | Instant | Wait for expiry |
| DB calls per request | Yes | No |
| Horizontal scaling | Harder | Easy |
| Microservices | Hard | Natural |
When to Use Sessions
- Traditional web app with server-side rendering
- Need to revoke sessions instantly
- Single-server deployment
When to Use JWTs
- Distributed microservices architecture
- Mobile apps where cookies are cumbersome
- Cross-domain authentication (SSO)
The Hybrid Approach
Most modern apps use both:
- Refresh token = long-lived, stored as httpOnly cookie, stored in DB (revocable)
- Access token = short-lived JWT (15 min), verified in-memory, no DB call