Authentication and Authorization
In most system design interviews, authentication gets one box on the diagram ("the API gateway checks the token") and one sentence. That's usually the right amount. But the sentence has to be correct, and interviewers often poke at it: what's in the token, how do you revoke it, how does "Sign in with Google" actually work, how does service A prove to service B who it is? And some interviews are entirely about this: design an auth service, a permission system for Google Drive, or SSO for an enterprise product.
Two words get mixed up constantly, so let's separate them first:
- Authentication (authn) answers who are you? The user proves their identity with a password, a passkey, a one-time code or a login at another provider.
- Authorization (authz) answers what are you allowed to do? Given a known identity, can it read this document, refund this order, or call this admin API?
HTTP's status codes mirror the split, with an unfortunate name: 401 Unauthorized actually means unauthenticated (no valid credentials), while 403 Forbidden means authenticated, but not allowed.
We'll build up from the bottom:
- Proving identity: storing passwords, and remembering a logged-in user with sessions or tokens.
- Delegation and federation: OAuth 2.0, OpenID Connect, SAML and single sign-on.
- Authorization models (RBAC, ABAC, relationship-based) and authenticating services to each other.
Proving Identity
Storing Passwords
If your system has passwords, the first rule is that you never store them, not even encrypted. You store a password hash made with a function designed to be slow:
- Use Argon2id, scrypt or bcrypt, not a fast hash like SHA-256. A GPU can compute billions of SHA-256 hashes per second, so a leaked table of fast hashes falls quickly to brute force. Password hashing functions are deliberately expensive (tuned to take on the order of tens to hundreds of milliseconds and, for Argon2 and scrypt, a lot of memory), which makes guessing millions of candidates impractical.
- Each hash gets a random salt, stored alongside it, so two users with the same password have different hashes and precomputed tables are useless. Modern libraries generate and embed the salt for you.
- Encryption is the wrong tool because it's reversible. Whoever gets the key gets every password.
from argon2 import PasswordHasher
ph = PasswordHasher() # sensible defaults; salt is generated and embedded
stored = ph.hash("correct horse battery staple")
# '$argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash>'
ph.verify(stored, attempt) # raises if it doesn't match
The slowness is also a capacity concern. If each login costs 50 ms of CPU, a login spike of 2,000 logins per second needs on the order of 100 CPU cores just for hashing. That's a reason to keep login on its own service, rate-limit it per account and per IP, and avoid re-checking passwords on every request (which is what sessions and tokens are for).
Passwords alone are weak, so production systems add a second factor: a TOTP code from an authenticator app, a push approval or a hardware key. Increasingly, passkeys (WebAuthn) replace passwords entirely with a key pair stored on the user's device; the server stores only the public key, so there's nothing useful to leak. The flows for one-time codes are covered in /system-design/otp-mfa.
Remembering the User: Sessions
Once a user has proved who they are, you don't want them to send their password with every request. The system issues something that stands in for the login. The classic approach is a server-side session:
- The user logs in. The server creates a random session ID (at least 128 bits from a secure random generator) and stores
session_id -> {user_id, created_at, expires_at, ...}in a session store. - The server returns the ID in a cookie.
- On every request, the browser sends the cookie back, and the server looks up the session to find the user.
Set-Cookie: sid=Yp3kR8...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=1209600
The cookie attributes matter, and naming them is a good signal:
HttpOnly: JavaScript can't read the cookie, so a cross-site scripting (XSS) bug can't steal it.Secure: only sent over HTTPS.SameSite=Lax(orStrict): the browser doesn't send the cookie on most cross-site requests, which blocks most cross-site request forgery (CSRF), where another site tricks the user's browser into making a request to yours. For sensitive actions, add a CSRF token too.
The session store is usually Redis (or Memcached, or a database table). A lookup is well under a millisecond, and with key expiry, sessions clean themselves up. At 100,000 requests per second, that's 100,000 Redis reads per second, which a small Redis cluster handles easily.
Sessions have one huge advantage: revocation is trivial. Logging out, "sign out of all devices," banning an account or reacting to a stolen cookie all come down to deleting rows in the session store. The next request fails immediately.
Tokens and JWTs
The alternative is a self-contained token: instead of a random ID that points to state on the server, the token carries the user's identity, signed by the server so it can't be forged. Any service with the verification key can check it without calling anyone. The standard format is the JSON Web Token (JWT).
A JWT is three base64url-encoded parts separated by dots: header.payload.signature.
// header
{ "alg": "RS256", "kid": "2024-key-3", "typ": "JWT" }
// payload (the "claims")
{
"iss": "https://auth.example.com",
"sub": "user_8f3a2c",
"aud": "api.example.com",
"exp": 1767225600,
"iat": 1767224700,
"scope": "orders:read orders:write",
"roles": ["customer"]
}
The signature is computed over the header and payload. With HS256 it's an HMAC with a shared secret, so every service that verifies tokens can also mint them. With RS256 or ES256, the auth service signs with a private key, and everyone else verifies with the public key. Asymmetric signing is the better default for distributed systems: services can't forge tokens, and the auth service publishes its public keys at a JWKS endpoint (/.well-known/jwks.json) so services can fetch and cache them. The kid header says which key signed a token, which is what makes key rotation possible: publish the new key, start signing with it, and retire the old one once tokens signed with it have expired.
A service verifying a JWT must check the signature with an expected algorithm (never trust the token's own alg blindly; accepting "alg": "none" or switching algorithms has caused real vulnerabilities), then check exp, iss and aud. The aud check matters: a token issued for one API shouldn't be accepted by another.
Two things to say clearly about JWTs:
- The payload is encoded, not encrypted. Anyone holding the token can read it. Don't put emails, addresses or anything sensitive in it.
- They can't be revoked without giving up statelessness. A JWT is valid until
exp, no matter what. If a user logs out or is banned, the token keeps working. You can keep a denylist of revoked token IDs (jti) in Redis, but then every request checks shared state again, which is the thing JWTs were meant to avoid.
Access Tokens and Refresh Tokens
The standard way out of the revocation problem is to use two tokens:
- A short-lived access token (a JWT, valid for 5-15 minutes) sent with every API request and verified locally by services.
- A long-lived refresh token (an opaque random string, valid for days or weeks), stored server-side by the auth service and used only to get new access tokens.
When the access token expires, the client calls POST /oauth/token with the refresh token and gets a fresh pair. Revocation now happens at refresh time: delete the refresh token and the user is fully logged out within one access-token lifetime. Most requests never touch shared state, and revocation is bounded to a few minutes.
Refresh token rotation makes this safer: every refresh returns a new refresh token and invalidates the old one. If an old refresh token is ever used again, someone stole it, so the auth service revokes the whole token family and forces a fresh login.
Sessions or JWTs?
| Server-side sessions | JWT access tokens | |
|---|---|---|
| What the client holds | Random ID | Signed claims |
| Per-request check | Session store lookup | Signature check, no network call |
| Revocation | Instant (delete the session) | At expiry, or with a denylist |
| Size | ~32 bytes | Often 500 bytes to over 1 KB, on every request |
| Best fit | Browser apps talking to one backend | Many services, mobile apps, third-party APIs |
A common and sensible combination: the browser holds a session cookie with the edge (or a backend for frontend), and the edge exchanges it for a short-lived JWT that travels between internal services. External clients never see the internal token, and internal services never need the session store.
Don't pitch JWTs as "more scalable" without qualification. A Redis session lookup costs well under a millisecond, and it's rarely the bottleneck. The real reason to use JWTs is that many independent services can verify identity without a shared dependency. The real cost is revocation. Say both.
Where should a browser app keep tokens? localStorage is readable by any JavaScript on the page, so one XSS bug leaks the token. An HttpOnly cookie can't be read by scripts, which is why many teams keep browser apps on cookies (with SameSite and CSRF protection) and use bearer tokens for mobile and server clients.