Building a Secure Login and Session Service for a Cloud App
System DesignModel answerLast updated
Design a login and session service for web and API clients using email and password, extensible to federated identity, with strong credential handling, abuse defenses, and a plan for 10x growth.
You are asked to design the identity and login layer for a multi-tenant cloud product. Today people sign in with an email address and a password. Later, the business wants to let customers sign in through external identity providers without a rewrite.
Walk through a design that covers:
- The login flow and the public APIs (sign-up, login, token refresh, logout, password reset, and a future external-provider flow)
- The storage schema and your choice of database
- How credentials are protected at rest and in transit
- The session lifecycle: issuance, validation, rotation, expiry, and revocation
- Backup, restore, and disaster recovery for identity data
- A staged plan for handling ten times today's traffic
Assumptions
- Both browsers and programmatic API clients must be supported.
- Authentication answers "who is this?". Product-specific authorization is a separate concern, but it must receive the identity in a safe, verifiable form.
- Passwords must never be recoverable from what you store.
- Clients may retry requests, sessions may need to be revoked, and attackers will attempt credential stuffing.
- Availability matters, but you must not weaken credential checks to stay up during an outage.
Questions worth raising with the interviewer
- Which login methods, compliance requirements, and session lengths are needed?
- Does revocation need to take effect instantly everywhere, or is a short delay acceptable?
- Is multi-factor authentication mandatory for everyone or only for sensitive actions?
- What recovery point and recovery time objectives apply to identity data?
Hints
Hint 1
Start by drawing trust boundaries: untrusted clients, an edge layer (TLS, WAF, rate limiting), the auth service, its datastore, and downstream product services that only ever see signed identity assertions.
Hint 2
Decide what a session is: short-lived signed access tokens plus a longer-lived, rotating, server-tracked refresh token gives you cheap validation and a real revocation point.
Hint 3
Treat abuse as a first-class requirement: per-account and per-IP throttling, uniform error messages, breached-password checks, and audit logs. Then describe how each tier (stateless auth nodes, cache, primary and replicas, partitioning) scales independently.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and clarifying assumptions
I would assume: email and password at launch, browser and API clients, an access-token lifetime of about 10-15 minutes, a refresh lifetime of 30 days, revocation within roughly a minute for normal cases and immediately for account compromise, optional MFA, and an RPO of a few minutes with an RTO under an hour. Authentication is its own service; authorization lives in product services.
2. Architecture and trust boundaries
- Clients (browser, mobile, API) are untrusted.
- Edge terminates TLS, applies WAF rules and coarse rate limits, and forwards to the auth service.
- Auth service is stateless and horizontally scaled. It handles login, refresh, logout, reset, and federation callbacks.
- Identity database (the source of truth) and a cache/counter store (for throttling and revocation lists).
- Downstream services never see passwords. They validate a signed access token locally using public keys published through a key-set endpoint.
- Async pipeline for emails, audit events, and risk signals, so the login path stays short.
3. Data model (relational)
users(id, tenant_id, email_normalized UNIQUE, status, created_at)credentials(user_id, algo, hash, params, updated_at)for the password hashidentities(user_id, provider, provider_subject, UNIQUE(provider, provider_subject))for future external providerssessions(id, user_id, device_info, created_at, last_seen, revoked_at)refresh_tokens(id, session_id, token_hash, family_id, expires_at, used_at)mfa_factors(user_id, type, secret_encrypted, ...)reset_tokens(user_id, token_hash, expires_at, used_at)audit_log(...)append-only
Separating identities from credentials is what makes later federation additive: a user can have one password credential and several linked providers.
Normalize emails (case-fold, Unicode normalization) before the unique constraint, so [email protected] and [email protected] cannot become two accounts.
4. Database choice
Identity data is relational, needs uniqueness constraints and transactions (sign-up must be atomic, refresh rotation must be atomic), and is read-heavy but small per row. A relational database such as PostgreSQL with synchronous replication inside a region and asynchronous replication to a second region fits well. A cache (Redis) holds rate-limit counters, short-lived revocation entries, and one-time codes. I would avoid a purely eventually consistent store for the credential and refresh-token tables, because double-spend of a refresh token is a security bug.
5. Credential protection
- Hash with a memory-hard algorithm (Argon2id, or bcrypt/scrypt if constrained), with a per-user random salt and parameters stored alongside the hash so they can be upgraded; rehash on next successful login.
- Optionally add a server-side pepper held in a KMS/HSM.
- TLS everywhere; HSTS; passwords never logged.
- Check new passwords against breached-password lists and enforce length over complexity rules.
- Compare in constant time. Run a dummy hash for unknown emails so timing does not reveal account existence.
6. APIs
POST /signup: verifies email ownership before activation.POST /login: returns an access token and a refresh token. For browsers, deliver the refresh token in anHttpOnly; Secure; SameSitecookie.POST /token/refresh: rotates the refresh token.POST /logout: revokes the session.POST /password/reset-requestand/password/reset-confirm: always return the same response regardless of whether the email exists.GET /oauth/{provider}/startand/callback: authorization code flow with PKCE,state, andnonce; link on verified provider subject, not on email alone.GET /.well-known/jwks.json: public keys.
Mutating endpoints accept an idempotency key so client retries do not create duplicate sessions or accounts.
7. Session lifecycle
- Access token: short-lived signed JWT (asymmetric keys) with
sub,tenant,sid,exp,kid. Validated locally by services with no network call. - Refresh token: opaque random value, stored only as a hash, rotated on every use. Reuse of an already-used token indicates theft, so revoke the entire token family.
- Revocation: marking the session revoked blocks refresh immediately. For instant effect on access tokens, push the
sidinto a small cache-backed deny list that services check, bounded by the access-token TTL. - Key rotation: publish new keys with a new
kidahead of use, keep old public keys until all tokens signed with them expire. - CSRF: SameSite cookies plus a CSRF token for cookie-authenticated state changes; API clients using bearer headers are not exposed to CSRF.
- Replay: short TTL, TLS, optional token binding to device.
8. Abuse resistance
- Rate limit by IP, by account, and by IP-account pair, with exponential backoff and temporary lockouts that do not allow an attacker to lock out victims indefinitely (prefer step-up challenges over hard locks).
- Credential stuffing signals: many accounts from one IP or ASN, high failure ratios, known-bad IP feeds. Respond with CAPTCHA or MFA step-up.
- Uniform error messages ("invalid email or password").
- Audit log of logins, failures, resets, and MFA changes, streamed to a SIEM.
9. Backup and recovery
- Continuous WAL archiving with point-in-time recovery plus daily snapshots, encrypted, stored in another region.
- Standby replica in a second region with automated or semi-automated failover.
- Regular restore drills with measured RTO/RPO.
- Signing keys backed up separately in a KMS with strict access control.
- During an outage, fail closed: if the database is unreachable, do not fall back to cached password checks. Existing valid access tokens keep working until expiry, which gives graceful degradation without weakening verification.
10. Scaling to 10x
- Measure first: login is CPU-bound by password hashing, so scale auth nodes horizontally and size them for hash cost.
- Most traffic is token validation, which is local and scales for free.
- Add read replicas for session and profile lookups; keep writes on the primary.
- Partition by tenant or user-id hash when a single primary saturates; the unique email constraint means routing by normalized email hash (or a small global lookup index) is needed.
- Move expensive work (emails, risk scoring) to queues.
- Run multi-region active-passive first; consider regional cells for isolation and data residency.
- Protect the hash tier with admission control so a stuffing attack cannot starve legitimate logins.
11. Common mistakes
- Storing passwords with fast hashes or reversible encryption.
- Different responses for unknown email versus wrong password, or on reset.
- Long-lived, non-rotating refresh tokens, or no reuse detection.
- Auto-linking federated accounts by unverified email, which enables account takeover.
- Putting authorization rules inside the identity service.
- A single global primary with no plan for hashing CPU cost.
- Falling back to weaker checks during an outage.
12. Trade-offs summary
Short-lived stateless tokens give scalability but need a deny list for instant revocation. Opaque server-side sessions give instant revocation but add a lookup on every request. My hybrid keeps the hot path local and the sensitive path (refresh) centralized and transactional.