A Backend Engineer’s Deep-Dive
When people say:
“Authentication is confusing”
What they usually mean is:
👉 Cookies, headers, sessions, tokens, browser behavior — all mixed together.
This article clears that confusion from the ground up.
🌐 First: Why Cookies Exist at All
HTTP is stateless.
That means:
- Server does NOT remember users
- Every request is independent
But real apps need memory:
- Logged-in users
- Shopping carts
- Preferences
- Sessions
So browsers introduced cookies.
🍪 What Is a Cookie?
A cookie is a small piece of data stored by the browser and automatically sent to the server with every request to the same domain.
👉 Cookies are not authentication by themselves
👉 Cookies are just a transport mechanism
Cookie Example
Server response:
Set-Cookie: session_id=abc123; HttpOnly; Secure
Browser stores it.
Later request:
Cookie: session_id=abc123
That’s it.
No magic.
Important Cookie Properties (Backend MUST Know)
| Flag | Meaning |
|---|---|
| HttpOnly | JS cannot access cookie |
| Secure | Sent only over HTTPS |
| SameSite | Controls cross-site sending |
| Path | URL scope |
| Domain | Which domain can read |
Cookie ≠ Session ≠ Token
This confusion causes 90% of auth bugs.
- Cookie → storage + transport
- Session → server-side state
- Token → self-contained credential
Cookies can carry:
- Session IDs
- JWT tokens
- Preferences
🔁 How Cookies Work (Full Flow)
Step 1: User Logs In
Server verifies credentials.
Step 2: Server Sends Cookie
Set-Cookie: session_id=abc123
Step 3: Browser Stores Cookie
Invisible to user.
Step 4: Browser Automatically Sends Cookie
Every request to the domain.
👉 Backend doesn’t need to ask for it.
🧠 Why Cookies Are Powerful
Because:
- Automatically attached by browser
- Work with redirects
- Secure flags exist
- No manual JS handling required
That’s why sessions traditionally use cookies.
🔐 Cookie-Based Authentication
How It Works
- Login success
- Server creates session
- Session ID stored in cookie
- Browser sends cookie automatically
- Server checks session store
Browser → Cookie → Server → Session Store
Advantages
✅ Automatic sending
✅ Protected by HttpOnly
✅ Strong CSRF defenses possible
✅ Mature browser support
Disadvantages
⚠️ CSRF risk (if misconfigured)
⚠️ Less natural for mobile apps
⚠️ Cross-domain complexity
🔥 Header-Based Authentication
This is common in APIs.
Instead of cookies:
Authorization: Bearer <token>
How Header-Based Auth Works
- User logs in
- Server returns token (JWT)
- Client stores token
- Client manually attaches header
- Server verifies token
Client → Authorization Header → Server
Advantages
✅ Stateless
✅ Perfect for APIs
✅ Easy for mobile apps
✅ No CSRF (by default)
Disadvantages
⚠️ Token theft risk
⚠️ Must manage expiration
⚠️ Manual handling in frontend
⚔️ Cookie vs Header — Direct Comparison
| Feature | Cookies | Headers |
|---|---|---|
| Auto-sent by browser | ✅ Yes | ❌ No |
| CSRF risk | ⚠️ Yes | ❌ No |
| Works well with SSR | ✅ Yes | ❌ Harder |
| Mobile friendly | ⚠️ Limited | ✅ Excellent |
| Security flags | ✅ Yes | ❌ No |
🧠 Cookie + Token (Modern Best Practice)
Very common today:
- JWT stored in HttpOnly cookie
- Sent automatically
- No JS access
- No localStorage risks
This gives:
✔ Token scalability
✔ Cookie security
⚠️ Why CSRF Happens (Simple Explanation)
Because cookies are auto-sent.
Malicious site:
<img src="bank.com/transfer?amount=1000" />
Browser sends cookies → server thinks it’s legit.
Mitigation:
- SameSite=strict
- CSRF tokens
- Double submit cookie
🧠 Why Sessions Are NOT Stored in Database (Usually)
This is a very important backend design question.
Short answer:
👉 You can store sessions in DB — but you usually shouldn’t.
Let’s explain why.
Problem 1: Database Is Too Slow
Sessions are accessed:
- On every request
- By every authenticated user
DBs are optimized for:
- Business data
- Transactions
- Queries
Not millions of tiny reads per second.
This creates:
❌ Latency
❌ Lock contention
❌ Performance bottlenecks
Problem 2: Database Connections Are Limited
DBs have limited connections.
Session lookups steal connections from:
- Orders
- Payments
- Writes
Bad tradeoff.
Problem 3: Cleanup Is Expensive
Sessions expire.
In DB you need:
DELETE FROM sessions WHERE expires_at < now();
This causes:
- Table scans
- Locks
- IO pressure
At scale → dangerous.
Problem 4: Horizontal Scaling Pain
If DB goes down:
👉 Auth goes down
Single point of failure.
🧠 Why Redis Is Used Instead
Redis is:
- In-memory
- Extremely fast
- TTL built-in
- Designed for ephemeral data
Example:
SET session:abc123 userId=42 EX 3600
Redis auto-expires sessions.
No cleanup job needed.
❗ When DB Sessions MAY Be Acceptable
Small apps:
- Low traffic
- Monolith
- MVP
- Internal tools
Even then — Redis is better if available.
🧭 Final Mental Models (Memorize These)
👉 Cookies are carriers, not auth
👉 Headers are manual carriers
👉 Sessions = server remembers you
👉 Tokens = you prove yourself
👉 Databases store truth, not temporary state
⭐ Backend Interview Gold Tip
If interviewer asks:
“Why not store sessions in DB?”
Answer:
“Sessions are high-frequency, short-lived, non-critical data.
Databases are optimized for durability, not ephemeral state.
Redis matches session access patterns much better.”
That’s a senior-level answer.
Follow me on : Github Linkedin Threads Youtube Channel
Top comments (0)