CMD Guide
HomeSystem DesignAuthentication

Session vs Token Auth — Traced (Cookies & JWTs)

After you log in, how does the server remember you?

HTTP is stateless, so after one password check, how does request #2 know it’s you? Two mechanisms: a server-side session (the server remembers you in a store) or a signed token / JWT (the server verifies a cryptographic signature and trusts the claims inside).

Session-based auth stores state server-side and uses a cookie; token/JWT auth is stateless and verifies a signature
Session-based auth stores state server-side and uses a cookie; token/JWT auth is stateless and verifies a signature

Session vs JWT, traced

Both start the same way: the client POSTs credentials and the server checks the password hash once. After that the paths diverge.

Session (cookie) flow

  1. Server creates a high-entropy session ID and stores {userId, role, expiresAt} in Redis.
  2. Server replies Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax.
  3. Every request sends the cookie automatically; the server looks up session:abc123 in Redis.
  4. Logout = delete the Redis key. The next request is anonymous.

JWT flow

  1. Server signs a token containing claims such as {"sub":42,"role":"user","exp":1719003600}.
  2. Client stores it (preferably in an HttpOnly cookie, or a short-lived header) and sends it back.
  3. Server verifies the signature with SECRET_KEY and checks exp.
  4. Logout is harder: the token is valid until exp. You must keep lifetimes short or maintain a denylist.
 header.payload.signature
 header : {"alg":"HS256","typ":"JWT"}
 payload: {"sub":42,"role":"user","exp":1719003600}        ← readable claims
 signature: HMAC_SHA256(base64url(header)+"."+base64url(payload), SECRET_KEY)

Anyone can read the payload; only the server (with SECRET_KEY) can forge a valid signature, so tampering is rejected.

Comparison

Session (cookie)Token (JWT)
Server stores state?Yes (session store)No — verifies signature
Scale across serversNeeds shared store or sticky sessionsAny server verifies
Revoke before expiryEasy (delete session)Hard (needs denylist)
Theft vectorCSRF (mitigate with SameSite + anti-CSRF token)XSS if in localStorage (prefer HttpOnly cookie)

When to use which

Takeaways


Re-authored from-scratch; diagram hand-authored (SVG) for this guide.

Side-by-side trace: login → logout

StepSession (cookie)JWT
1. LoginPOST /login with credentialsPOST /login with credentials
2. Server createsRandom session id, stores state in RedisSigned token with claims + expiry
3. Server returnsSet-Cookie: session=abc123; HttpOnly; Secure; SameSite=LaxToken in HttpOnly cookie or Authorization header
4. Request #NCookie sent automatically; server looks up RedisToken sent manually; server verifies signature + exp
5. LogoutDelete Redis key instantly anonymousToken still valid until exp; add to denylist or wait
6. Scale noteNeeds shared Redis or sticky sessionsAny server can verify with public/secret key

The session path keeps authority in a store you control; the JWT path pushes authority into a signed, time-bounded credential you cannot easily retract.

When to use which: decision table

ScenarioPickWhyLatency / ops impact
Same-origin web app; instant ban/logout requiredSessionDelete Redis row = immediate revocation~1–2 ms Redis lookup per request; shared store to operate
Microservices / mobile / cross-origin SPAJWT access tokenEach service verifies signature locally; no cross-service session store~0.5 ms HMAC verify per service; revocation delayed until expiry
High-security flows where revocation must be instant and cross-domainReference / opaque tokenToken is just an id; introspection endpoint checks storeIntrospection adds 1–3 ms hop and a dependency; scales with cache
Long-lived SSO session across many appsShort JWT + refresh tokenAccess token stays short; refresh token can be revoked centrallyRefresh rotation adds writes but limits theft window

🪜 Drill ladder: session vs token follow-ups

L1 · Revocation trap: “A user clicks logout. How fast are they actually logged out in each model?”
Trap: “Both are instant.”
Bar: Sessions are instant because the server deletes the lookup key. JWTs remain valid until exp unless you keep a denylist (reintroduces state) or use very short lifetimes plus refresh rotation. The “logout” UX is immediate, but the cryptographic authority is not.

L2 · CSRF trap: “Why does a session cookie need SameSite/anti-CSRF tokens while a JWT in localStorage does not?”
Trap: “JWTs are immune to CSRF.”
Bar: Cookies are sent automatically by the browser, so a malicious site can forge a state-changing request; SameSite and anti-CSRF tokens close that hole. JWTs in localStorage must be attached by JavaScript, so CSRF does not apply — but XSS does, and XSS is harder to mitigate. Prefer HttpOnly cookies for tokens whenever you can.

L3 · Scaling trap: “Sessions don’t scale; use JWTs for scale. True or false?”
Trap: “True — stateful sessions are the bottleneck.”
Bar: A Redis-backed session cluster handles millions of QPS and adds ~1 ms. The real trade-off is operational: sessions couple you to a shared store; JWTs couple you to revocation semantics and key rotation. Neither is “more scalable” in the abstract.

L4 · Token theft trap: “A JWT access token with a 15-minute expiry is stolen. How much damage?”
Trap: “Rotate the signing key to kill it.”
Bar: Rotating the signing key invalidates every issued token, not just the stolen one, which logs out all users. Use short access-token lifetimes and revoke the refresh token; the thief’s window is bounded to the remaining access-token lifetime.

L5 · Refresh rotation trap: “Why rotate refresh tokens on every use?”
Trap: “It prevents replay.”
Bar: Rotation primarily detects parallel use of the same refresh token (a sign of theft or cloning). When the server sees a used refresh token again, it revokes the whole family. This is detection + containment, not prevention.

🤖 Don't fully get this? Learn it with Claude

Stuck on Session vs Token Auth — Traced (Cookies & JWTs)? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Session vs Token Auth — Traced (Cookies & JWTs)** (System Design) and want to truly understand it. Explain Session vs Token Auth — Traced (Cookies & JWTs) from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Session vs Token Auth — Traced (Cookies & JWTs)** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Session vs Token Auth — Traced (Cookies & JWTs)** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Session vs Token Auth — Traced (Cookies & JWTs)** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes