Cloud Identity and Session Authentication Service
Medium · System Design · Software Engineer · Onsite
Prompt
Architect the core identity and sign-in service for a cloud SaaS product accessed by both web browsers and programmatic API clients. At launch, accounts authenticate via email and password, while the underlying schema and token model must cleanly accommodate external and enterprise identity providers in future phases. Walk through your sign-in workflow, client and internal APIs, storage engine and data model, secret protection, session/token lifecycle, backup and disaster-recovery posture, and concrete evolution path to handle a 10x jump in traffic.
Design around these non-negotiable constraints (and state explicit assumptions on MFA enforcement rules, compliance/audit retention, session lifetimes, revocation latency bounds, and RPO/RTO targets):
- Identity verification is distinct from product-level permission checks, yet downstream microservices must consume the verified caller identity across well-defined trust boundaries.
- User passwords must only be stored using irreversible cryptographic hashing—never in cleartext or decryptable form.
- Callers may re-send timed-out requests, active sessions may be terminated at any moment, and botnets may launch large-scale credential-stuffing campaigns.
- High uptime is critical, but degrading or bypassing credential checks during an outage is strictly forbidden (the platform must fail closed).
Scope & Expectations
- APIs, extensible identity schema, and database selection: Specify endpoints for browsers and API/CLI callers, justify your primary datastore, and model accounts, hashed credentials, federated identity mappings, MFA factors, and sessions.
- Credential security, session lifecycle, and abuse defense: Cover memory-hard password hashing, short-lived vs. refreshable session tokens, retry-safe rotation, rapid revocation, clear service trust boundaries, and pre-hash defenses against credential stuffing.
- Fail-closed resilience, safe recovery, and 10x scale: Detail behavior during dependency outages, tamper-resistant backups and point-in-time recovery without reviving revoked credentials, and architectural partitioning to absorb tenfold load growth.
Step-by-step walkthrough
Clarify requirements, assumptions, and security invariants
Authentication answers "Who is this caller?", whereas authorization answers "What is this caller allowed to do?". Keeping those two concerns separate lets one authentication platform establish a cryptographic identity once and pass it safely to dozens of downstream product services.
Functional requirements
- Email + password registration, email verification, login, logout, and active-session management ("view and revoke my logged-in devices").
- Support both browser clients (web apps) and API clients (CLI tools, automation scripts, and service-to-service accounts).
- Self-service password reset, authenticated password change, and optional MFA (multi-factor authentication) — requiring a second proof beyond a password, such as a 6-digit TOTP (time-based one-time password) app or a WebAuthn hardware key / passkey.
- Clean extensibility for external Identity Providers (IdPs) later — social login via OIDC (OpenID Connect) and enterprise SSO (Single Sign-On) via OIDC or SAML — without changing how downstream services read sessions or tokens.
Non-functional requirements and hard security rules
- Irreversible password storage: passwords are never stored in plaintext or reversible encryption; they use a slow, salted, memory-hard one-way hash.
- Latency & availability: login p99 latency (the time within which 99% of requests complete) < 500 ms including intentional password-hashing work; per-request identity verification inside product services < 0.5 ms; 99.95% login availability, while already-authenticated users keep working during brief auth-database blips.
- Fail-closed verification: if a database, MFA verifier, or password hasher is overloaded or unreachable, the login fails with
503 Service Unavailable. An outage never skips or weakens password hashing, MFA, or signature checks. - Retry safety & abuse resistance: network retries must not accidentally lock users out or invalidate active sessions, and the platform must withstand credential stuffing (automated botnets replaying millions of email/password pairs leaked from other websites).
Explicit product and operational assumptions
Policy Area Assumed Design Decision Sign-in factors, compliance, and session lifetimes Email + password + TOTP/WebAuthn today; OIDC/SAML later. GDPR-style account deletion + 1-year security audit retention. Browser sessions: 7 days idle, 30 days absolute max, backed by 5-minute access tokens. Session revocation latency target Immediate at the auth service (revoked sessions can never refresh); propagated to product services within ~1–2 seconds via pub/sub push, with a hard worst-case ceiling of 5 minutes (+ 60 s clock-skew leeway) if the event bus is down. High-risk endpoints verify online. MFA enforcement policy Optional for standard users, mandatory for admins and enterprise org policies, plus step-up authentication (requiring a fresh login/MFA check within the last 15 minutes) before changing email/password or minting API keys. Disaster-recovery RPO (max data lost) and RTO (time to recover) Single Availability Zone (AZ) failure: RPO = 0,RTO < 2 minvia synchronous standby. Full region failure:RPO < 5 s,RTO < 30 minvia async cross-region replica.Back-of-the-envelope numbers (launch and 10x)
1. Traffic profile (Launch -> 10x target) Registered users 10M -> 100M Daily active users (DAU) 2M -> 20M Password logins (~1/DAU/day) 2M/day (~23/s avg, ~120/s at 5x morning peak) 10x peak: ~1,200 logins/s Authenticated API calls ~1,000/DAU/day = 2B/day (~23k/s avg, ~70k/s at 3x peak) 10x peak: ~700,000 token checks/s! Peak concurrent active clients 10% of DAU = 200,000 -> 2,000,000 at 10x 2. Deliberate password-hashing CPU & RAM (Argon2id tuned to ~50 ms = 0.05 core-s, >= 19 MiB RAM) Launch peak (120 logins/s) 120 x 0.05 s = 6 CPU cores busy (~120 MB RAM) 10x peak (1,200 logins/s) 1,200 x 0.05 s = 60 CPU cores busy (~1.1-3.8 GB RAM) Botnet stuffing at 10,000 req/s 10,000 x 0.05 s = 500 CPU cores! -> Rate limiting MUST block abusive traffic BEFORE password hashing runs. 3. Access-token refreshes (every 5 minutes = 300 s while active) Launch peak 200,000 active clients / 300 s = ~670 refreshes/s Daily volume: ~2M DAU x ~10 refreshes/day = ~20M/day (~230/s avg) 10x peak 2,000,000 / 300 s = ~6,700 refreshes/s (busiest DB write path!) 4. Storage footprint (Launch) Users + credentials + identities 10M x ~1 KB = ~10 GB Active sessions ~10M x ~400 B = ~4 GB Refresh tokens (7-day history) 20M/day x 7 x 150 B = ~21 GB Total core transactional DB ~35 GB at launch (~350 GB at 10x) Append-only security audit log ~5M events/day x 300 B = 1.5 GB/day (~550 GB/year, separate log store)Three design lessons come directly out of these numbers: 1. Token checks outnumber logins ~600 to 1 (
700k/svs.1.2k/sat 10x): product services cannot query a central session database on every API call. They must verify short-lived signed tokens locally in memory. 2. Attackers control how often your most expensive CPU function runs: Argon2id intentionally burns ~50 ms of CPU per attempt, so pre-hash throttling and an isolated hasher worker pool are mandatory. 3. Core identity data is small (~35 GB), while token refreshes dominate writes (6,700/sat 10x): a single primary relational database easily serves launch, and shardingsessions+refresh_tokensaway fromusersunlocks 10x cleanly.API design for browser and API clients
Public HTTPS endpoints (
https://auth.example.com)POST /v1/signup { email, password } -> 202 { status: "check_your_email" } // identical response whether email already exists or not POST /v1/email/verify { token } -> 204 POST /v1/login { email, password, device_token? } -> 200 { access_token: "<JWT>", expires_in: 300 } + Set-Cookie: __Host-refresh=<opaque>; HttpOnly; Secure; SameSite=Strict; Path=/ (Non-browser API/CLI clients pass client_type="token" and receive refresh_token in JSON) -> 200 { mfa_required: true, challenge_id: "ch_...", methods: ["totp", "webauthn"] } -> 401 { error: "invalid_credentials" } // identical body & timing for unknown email vs bad password -> 429 { error: "too_many_attempts" } + Retry-After -> 503 { error: "temporarily_unavailable" } // fail closed if DB or hasher pool is unavailable POST /v1/login/mfa { challenge_id, totp_code | webauthn_assertion } -> 200 tokens POST /v1/token/refresh (__Host-refresh cookie + Origin check, or JSON refresh_token) -> 200 { access_token, expires_in: 300 } + rotated refresh token POST /v1/logout -> 204 (revokes current session and clears cookie) GET /v1/sessions -> list active devices, approximate location, last_seen_at DELETE /v1/sessions/{sid} -> revoke one session (or DELETE /v1/sessions?keep_current=true) POST /v1/password/forgot { email } -> 202 always POST /v1/password/reset { reset_token, new_password, mfa_code? } -> 204 (revokes all sessions) POST /v1/password/change { current_password, new_password } (requires recent auth_time) POST /v1/api-keys { name, scopes, expires_in_days } -> 201 { key_id, secret } (shown once) POST /oauth/token grant_type=client_credentials, client_id=<key_id>, client_secret=<secret> -> 200 { access_token, expires_in: 300 } // scripts & service accounts get the exact same JWT format GET /.well-known/jwks.json -> public signing keys (next, current, previous)Internal service-to-service interfaces
POST /internal/v1/introspect { access_token } -> { active, sub, sid, auth_time } (high-risk actions) Pub/Sub topic: auth.revocations { type: "session_revoked", sid, exp } { type: "user_tokens_revoked", sub, revoked_auth_before, exp } { type: "signing_key_revoked", kid }Why this API contract avoids classic security traps - Zero account enumeration:
/signup,/login, and/password/forgotreturn the exact same status code and response shape whether an email is registered or not, preventing attackers from scraping customer email lists. - Browser XSS and CSRF protection: the browser holds the 5-minuteaccess_tokenonly in JavaScript memory (neverlocalStorage, where injected scripts can steal it) and stores the long-lived refresh token in anHttpOnly; Secure; SameSite=Strict__Host-cookie (which blocks JavaScript access and forbids subdomain cookie injection). BecauseSameSite=Strictstill treats sibling subdomains (*.example.com) as same-site, cookie-authenticatedPOSTendpoints also verify theOriginheader (or require a customX-Auth-CSRF: 1header) to block subdomain CSRF. - One unified downstream token: browsers, CLI scripts, and API keys all exchange their credentials for the same 5-minute JWT format, so every product microservice runs one tiny verification library.Data model and database choice
users user_id (UUID) PK, email_normalized UNIQUE, email_display, email_verified_at, status (active | suspended | deleted), tokens_valid_after TIMESTAMP, created_at password_credentials user_id PK REFERENCES users, password_hash TEXT, -- e.g. '$argon2id$v=19$m=47104,t=2,p=1$<salt>$<digest>' params_version INT, changed_at TIMESTAMP identities -- decouples login method from user account! identity_id UUID PK, user_id REFERENCES users, provider TEXT, -- 'password' | 'oidc:<conn_id>' | 'saml:<conn_id>' subject TEXT, -- user_id for password; immutable IdP 'sub' / NameID for SSO UNIQUE (provider, subject), created_at, last_used_at mfa_factors factor_id UUID PK, user_id REFERENCES users, type (totp | webauthn), totp_secret_ciphertext BYTEA, -- envelope-encrypted via KMS (server must compute codes) webauthn_cred_id BYTEA, webauthn_public_key BYTEA, sign_count BIGINT, created_at recovery_codes (user_id, code_id) PK, code_hash TEXT, used_at TIMESTAMP -- slow Argon2id hash! sessions session_id UUID PK, user_id REFERENCES users, auth_time TIMESTAMP, amr TEXT[], idp TEXT, -- when & how user proved identity idle_expires_at TIMESTAMP, absolute_expires_at TIMESTAMP, revoked_at TIMESTAMP, revoke_reason TEXT, device_label TEXT, created_ip INET, last_seen_at TIMESTAMP, INDEX (user_id) refresh_tokens token_sha256 BYTEA PK, session_id REFERENCES sessions, issued_at TIMESTAMP, used_at TIMESTAMP, INDEX (session_id) -- kept 7 days after use for theft detection api_keys key_id TEXT PK, owner_user_id UUID, secret_sha256 BYTEA, scopes TEXT[], expires_at TIMESTAMP, revoked_at TIMESTAMP, last_used_at TIMESTAMP reset_tokens token_sha256 BYTEA PK, user_id REFERENCES users, expires_at TIMESTAMP, used_at TIMESTAMP signing_keys kid TEXT PK, public_jwk JSONB, private_key_ciphertext BYTEA, state (next | current | previous | retired), created_at TIMESTAMP outbox event_id BIGSERIAL PK, topic TEXT, payload JSONB, created_at TIMESTAMPMatching secret types to the right cryptographic storage - Low-entropy human secrets (passwords, 8–10 character MFA recovery codes): humans pick predictable strings, so a stolen table can be guessed offline. Store with Argon2id + unique 16-byte random salt. - High-entropy machine secrets (256-bit random refresh tokens, API key secrets, password reset tokens):
2^256possibilities cannot be brute-forced even with fast hashes, so storingSHA-256(token)protects against database leaks while keeping lookups at ~1 microsecond. - TOTP shared secrets: the server must read the secret to compute the current 6-digit HMAC code, so hashing is impossible; use envelope encryption (encrypt each secret with a data key wrapped by a cloud KMS — Key Management Service). WebAuthn needs only the user's public key. - Separateidentitiestable: adding Google OIDC or Okta SAML later simply inserts(provider = 'oidc:okta_acme', subject = '00u123...')pointing touser_id. Never auto-link an external IdP login solely because its email string matches an existing account — an untrusted or misconfigured IdP assertingceo@company.comwould take over that account!Database choice: PostgreSQL (or MySQL) A relational ACID database (guaranteeing atomic, consistent, isolated, durable transactions) fits ~35 GB and ~800 writes/s at launch effortlessly:
UNIQUE (email_normalized)andUNIQUE (provider, subject)prevent duplicate accounts at the storage layer, primary reads eliminate stale-password bugs, and a single transaction atomically updates a reset password, revokes sessions, and writes anoutboxrevocation event. Redis is used strictly for expendable rate-limit counters and 30-second retry caches — losing Redis never lets an attacker bypass authentication.High-level architecture and trust boundaries
Browser / CLI / API Clients (Untrusted Internet) │ HTTPS (TLS 1.3) ════════════╪══════════════════════════════════════ Trust Boundary 1: Edge ▼ ┌──────────────────────────────────────────────────────────────────────┐ │ Edge Proxy + WAF: TLS termination, IP/ASN rate limits, bot scoring; │ │ STRIPS any client-supplied internal headers (e.g. X-User-Id) │ └───────────┬───────────────────────────────────────┬──────────────────┘ /v1/auth │ │ /api/* + Bearer JWT ════════════╪══════════════════════ Boundary 2 ▼ ▼ │ ┌──────────────────────────┐ ┌───────────────┼──────────────────┐ │ Stateless Auth API │───────►│ Redis Cluster │ │ │ (login, refresh, reset) │ │ (rate limits, │ │ └──┬──────────┬──────────┬─┘ │ 30s retry) │ │ │ │ │ └───────────────┘ │ │ RPC │ sign │ primary SQL │ ▼ ▼ ▼ │ ┌────────┐ ┌────────┐ ┌──────────────────────┐ │ │ Hasher │ │ Token │ │ Identity DB Primary │──sync──► Standby (AZ B) │ │ Pool │ │ Signer │ │ (PostgreSQL, AZ A) │──async─► DR Replica │ │(bounded│ │ (KMS │ └──┬─────────────┬─────┘ + Immutable S3 │ │ queue) │ │ keys) │ │ outbox │ audit events │ └────────┘ └────────┘ ▼ ▼ │ ┌────────────────┐ ┌──────────────┐ │ │ Event Bus │ │ Security Log │ │ │auth.revocations│ │ Pipeline/SIEM│ │ └──────┬─────────┘ └──────────────┘ │ ═════════════════════════╪═════════════════════════ Boundary 3 │ ▼ (push < 2 s) ▼ ┌────────────────────────────────────────────────────┐ │ Product API Gateway / Microservices │ │ 1. Verify JWT signature + exp locally (cached JWKS)│ │ 2. Check local in-memory revocation map │ │ 3. Pass verified {sub, org, sid, auth_time, amr} │ │ to product Authorization Engine │ └────────────────────────────────────────────────────┘Strict isolation across trust boundaries 1. Header stripping at the edge: external callers cannot spoof
X-Authenticated-User; only verified JWT claims inside Boundary 3 establish identity. 2. Credential isolation: onlyAuth APIholds credentials toIdentity DB, and structured logs automatically redactpassword,secret, andtokenfields. 3. Asymmetric signing (ES256/EdDSA): onlyToken Signercan ask KMS to decrypt private signing keys; product microservices fetch public keys from/.well-known/jwks.json. Even if a product service is compromised, it cannot forge tokens for other users.Example 5-minute JWT Access Token payload: { "iss": "https://auth.example.com", "aud": "cloud-product-api", "sub": "u_8f3c2a...", // immutable user_id "sid": "s_41c990...", // session_id "org": null, // populated for enterprise SSO tenants "iat": 1764230400, // token minted timestamp "exp": 1764230700, // iat + 300 s (5 minutes) "auth_time": 1764229800, // when user actually proved password/MFA! "amr": ["pwd", "hwk"] // authentication methods used }Deep dive 1: credential protection and the login flow
Password hashing parameters and optional KMS pepper
- Argon2id is a memory-hard hash (an algorithm that fills a large block of RAM during computation so attackers with thousands of tiny GPU cores cannot guess passwords cheaply in parallel). Start from OWASP minimums (
19 MiBRAM,2passes,1lane) and tune memory/passes on production CPUs to hit ~50 ms per hash. Normalize Unicode (NFKC), allow passwords of 12–128+ characters, and block passwords found in public breach lists (such as Have I Been Pwned hashes) without forcing annoying"must include 1 symbol"rules. - Defense-in-depth KMS pepper: after Argon2id produces its hash string, encrypt that hash column using an AES-GCM key managed in KMS (
AES_GCM(kms_key, argon2_string)). If an attacker steals a SQL dump or backup without KMS access, offline cracking cannot even start; and unlike an HMAC pepper baked inside the password input, an outer encryption wrapper can be rotated across all rows in a background job without waiting for users to log in!
Step-by-step login execution (constant-time and fail-closed)
Client POST /v1/login {email, password} │ ├─ 1. Normalize email; check per-IP and per-account Redis rate limits │ └─ Over limit? -> 429 Too Many Requests immediately (0 ms of hasher CPU spent!) │ ├─ 2. Read user + password_credentials from Identity DB PRIMARY (never a lagging replica, │ which could accept an old compromised password seconds after a password reset!) │ └─ Email not found? -> substitute a fixed dummy Argon2id hash so step 3 still takes ~50 ms, │ preventing timing side-channel discovery of registered emails. │ ├─ 3. Dispatch to isolated Hasher Pool (separate worker processes, bounded queue = 2x cores) │ └─ Queue full? -> return 503 immediately (fail closed; NEVER lower Argon2id cost under load!) │ ├─ 4. Wrong password (or dummy path)? -> increment failure counters, log event, return 401 │ ├─ 5. Correct password: │ ├─ Reset account failure counter; if params_version < current, rehash in background │ ├─ MFA enrolled / required by policy / high-risk IP? │ │ └─ Insert 5-min single-use MFA challenge -> return 200 {mfa_required: true, challenge_id} │ └─ Otherwise, in 1 DB transaction: insert session + SHA-256(refresh_token), │ mint 5-min JWT, emit audit log (+ "New device sign-in" email if unknown device).Isolating Argon2id inside its own bounded worker pool guarantees that even if a spike gets past edge filters, token refreshes, JWKS endpoints, and health checks in
Auth APIstay responsive instead of starving for CPU threads.- Argon2id is a memory-hard hash (an algorithm that fills a large block of RAM during computation so attackers with thousands of tiny GPU cores cannot guess passwords cheaply in parallel). Start from OWASP minimums (
Deep dive 2: session lifecycle, token rotation, and fast revocation
Why we pair a 5-minute JWT with a single-use rotating refresh token
Property Access Token (JWT) Refresh Token (Opaque) Format Signed JSON ( ES256/EdDSA)256-bit cryptographically random string Lifetime 5 minutes Single-use; rolls session forward (7d idle / 30d max) Verified by Every product service locally in RAM ( < 0.2 ms)Only Auth API, via primary DB transactionTheft defense Short 5-min lifespan + pushed revocation map Stored in HttpOnly__Host-cookie + reuse detectionAtomic refresh rotation with safe network-retry handling
If every refresh token works strictly once, what happens when a user's Wi-Fi drops the response to
POST /v1/token/refreshand the browser automatically retries 1 second later with the old cookie? Without a tiny retry window, the server would falsely accuse the user of token theft and log them out! Conversely, what if the user refreshed att = 0 s, clicked Logout att = 5 s, and an attacker replayed the old token att = 10 s? We must check session validity first, and only then check the retry window:BEGIN; -- 1. Lock the refresh-token row so concurrent retries/attacks serialize cleanly SELECT session_id, used_at FROM refresh_tokens WHERE token_sha256 = :hash FOR UPDATE; -- If no row -> 401 -- 2. ALWAYS verify the parent session is still active BEFORE honoring any retry cache! SELECT auth_time, idle_expires_at, absolute_expires_at, revoked_at FROM sessions WHERE session_id = :sid FOR UPDATE; -- If revoked_at IS NOT NULL or expired -> 401 -- 3. Handle already-used token: network retry (< 30 s) vs. stolen-token replay (>= 30 s) -- If used_at IS NOT NULL AND now() - used_at < interval '30 seconds': -- COMMIT and return the encrypted response cached in Redis under :hash (mint nothing new) -- If used_at IS NOT NULL AND now() - used_at >= interval '30 seconds': -- Compromise detected! Both thief and real user tried to use the chain: -- UPDATE sessions SET revoked_at = now(), revoke_reason = 'refresh_token_reused' WHERE session_id = :sid; -- INSERT INTO outbox ... ('session_revoked', :sid); -- COMMIT, alert user, return 401! -- 4. Normal first-time refresh: mark old token used, insert new token hash, extend idle expiry UPDATE refresh_tokens SET used_at = now() WHERE token_sha256 = :hash; INSERT INTO refresh_tokens (token_sha256, session_id, issued_at) VALUES (:new_hash, :sid, now()); UPDATE sessions SET last_seen_at = now(), idle_expires_at = LEAST(now() + interval '7 days', absolute_expires_at) WHERE session_id = :sid; COMMIT;Near-instant revocation without per-request database queries
- Block refresh immediately: logout updates
sessions.revoked_at = now(); password reset updates all user sessions and setsusers.tokens_valid_after = now(), writing anoutboxrow in the same commit. - Kill existing 5-minute JWTs in ~1–2 seconds: the outbox relay publishes
session_revoked {sid, exp}oruser_tokens_revoked {sub, revoked_auth_before, exp}toauth.revocations. Every product microservice subscribes and keeps two tiny in-memory hash maps:revoked_sids[sid] = exprevoked_users[sub] = revoked_auth_before(rejecting any token wheretoken.auth_time < revoked_auth_before)
- Tiny memory footprint: entries auto-evict once
now > exp + 60 s(6 minutes total). Even at 1 million revocations/day (~12/s), 6 minutes holds12 x 360 = ~4,300map entries (< 500 KB of RAM per service!). On startup, a service replays the last 6 minutes of the Kafka topic before accepting traffic; sensitive actions (email change, API key creation, billing) also call/internal/v1/introspect.
Zero-downtime signing-key rotation
Every JWT header includes
kid(key ID)./.well-known/jwks.jsonpublishes three keys (next,current,previous) so services caching JWKS for up to 24 hours already knownexta full day before we promote it every 30 days. If a private key is ever suspected leaked, we promotenextimmediately and pushsigning_key_revoked {kid}onauth.revocationsso services drop the compromised key in seconds rather than waiting out their 24-hour JWKS cache.- Block refresh immediately: logout updates
Deep dive 3: credential stuffing defense and account recovery
Stopping credential stuffing without locking out real customers
Credential-stuffing botnets try 1–2 leaked passwords against millions of accounts from thousands of residential proxy IPs. Hard-locking an account after 5 failed attempts backfires: an attacker can intentionally lock your CEO or every customer out in seconds! Instead, stack pre-hash defenses:
- Edge IP, subnet, and ASN budgets: cap login attempts per IP (e.g., 20/min) and flag cloud-hosting ASNs or known proxy pools with proof-of-work / bot challenges before reaching
Auth API. - Progressive per-account throttling + signed known-device bypass: after 5 failed attempts on an email in 15 minutes, require a bot challenge or exponential cooldown (
30 s, 2 m, 5 m). Crucially, browsers that previously logged into that account hold a signeddevice_tokencookie: presenting a validdevice_tokenfor thatuser_idbypasses the per-account throttle, so the real owner on their laptop logs right in even while a botnet hammers their email! - Global failure-rate circuit breaker: if platform-wide login failures jump from a baseline of 8% to 65%, automatically tighten bot challenges on unrecognized devices and page security engineering.
- Breached-password detection & phishing-resistant MFA: check passwords against k-anonymized SHA-1 breach prefixes at signup/change (and prompt for reset on login), and encourage WebAuthn passkeys (which cryptographically bind to
auth.example.com, defeating phishing pages too).
Secure password reset and MFA recovery
- URL fragment reset links:
POST /v1/password/forgotgenerates a 256-bit random token, storesSHA-256(token)with a 30-minute expiry (invalidating older reset tokens for that user), and emailshttps://auth.example.com/reset#token=<raw_token>. Browsers never transmit#fragmentvalues in HTTP requests, keeping the secret token out of load-balancer access logs, corporate proxies, andRefererheaders; JavaScript readslocation.hashand submits it in the JSON body ofPOST /v1/password/reset. - MFA is still enforced on password reset: if the account has MFA enabled, completing
/password/resetrequires a valid MFA factor (otherwise an attacker who hijacked only the victim's email inbox would silently bypass MFA!). - Lost MFA device: at MFA enrollment, generate 10 single-use recovery codes stored with Argon2id (never SHA-256, since 8–10 character codes have modest entropy). Users who lose both their MFA device and recovery codes go through a delayed manual verification flow (e.g., 72-hour hold with repeated email/SMS alerts to all registered contacts so an impersonation attempt is caught in time).
- Edge IP, subnet, and ASN budgets: cap login attempts per IP (e.g., 20/min) and flag cloud-hosting ASNs or known proxy pools with proof-of-work / bot challenges before reaching
Backup, disaster recovery, and restoring identity safely
Immutable cross-account backups
Stream PostgreSQL WAL (Write-Ahead Log) segments continuously plus daily encrypted snapshots into an S3/GCS bucket inside a separate, locked-down cloud account with 35-day WORM retention locks (Write-Once-Read-Many), so ransomware or compromised admin credentials in the production account cannot delete backups. Because backups contain password hashes and encrypted TOTP secrets, restrict decryption keys strictly to disaster-recovery roles and test full restores monthly in an isolated VPC.
Why restoring an authentication database to the past is a security incident
Suppose an attacker steals Alice's password at
10:00, Alice resets her password and revokes all sessions at10:05, and a bad schema migration at10:15forces a point-in-time restore back to10:02. Without extra care, restoring10:02brings Alice's compromised password and revoked sessions back to life! - Mandatory post-restore replay: becauseauth_eventsstreams to an independent append-only security log outside PostgreSQL, our recovery runbook replays every security-critical state transition between10:02and10:15(password resets/changes, session revocations, MFA enrollments, account suspensions) before reopening traffic. - Fallback if the gap log is incomplete: settokens_valid_after = now()globally (forcing clean re-login) and force password resets for any account that modified credentials during the restored window.Failure-mode behavior (always fail closed)
Component Outage System Behavior Identity DB primary fails Sync standby in AZ B promotes in < 2 min ( RPO = 0). During those ~90 s, logins/refreshes return503; already-issued 5-min JWTs keep working across all product services!Hasher pool saturated Immediate 503+Retry-After+ autoscale trigger; Argon2id parameters are never weakened.Redis cluster down Auth APIfalls back to stricter local in-memory per-instance rate limits; logins continue safely.Event bus ( auth.revocations) downRevoked sessions still cannot refresh; existing JWTs expire naturally within <= 5 min; high-risk endpoints call /internal/v1/introspect.KMS API outage Running Token Signer/Auth APInodes keep current keys cached in locked RAM; keep >= 3 warm replicas per AZ so restarts aren't needed mid-outage.Scaling to 10x traffic
At 10x scale (
100Musers,1,200peak logins/s,6,700refreshes/s,700,000API token checks/s), inspect each tier in order:- 700,000 token checks/s: 100% local CPU verification inside product services; scales horizontally with zero changes to the auth platform.
- 1,200 logins/s (~60 CPU cores of Argon2id): stateless
Auth APIandHasher Poolautoscale horizontally behind internal load balancers. - 6,700 refresh transactions/s (the real database bottleneck): writing 6,700 rows/s + cleaning up ~200M/day refresh rows eventually crowds a single PostgreSQL primary. Split session state from identity state:
- Keep
users,password_credentials,identities, andmfa_factorsin the core Identity DB (~100 GB, < 1,500 reads/s, < 50 writes/s — tiny!). - Move
sessionsandrefresh_tokensinto a dedicated sharded session store partitioned byuser_id. Format opaque refresh tokens as<user_id>.<256-bit-random-secret>: the non-secretuser_idprefix tellsAuth APIwhich shard owns the session, andSHA-256(secret)looks up the row inside that single shard (list my sessionsandrevoke all sessions for useralso stay single-shard!).
- Keep
- Solving the cross-database password-reset race at 10x: once
usersandsessionslive on different clusters, a password reset atreset_at = 12:00:00can no longer update both in one SQL transaction. Instead:- Transaction 1 (Identity DB): update
password_credentials, setusers.tokens_valid_after = 12:00:00, and write anoutboxeventpassword_reset {sub, reset_at: 12:00:00}. - Async worker (idempotent, retried until complete): marks all sessions of
subwithauth_time < 12:00:00as revoked in the user's session shard, and publishesuser_tokens_revoked {sub, revoked_auth_before: 12:00:00}to product services. - Notice why checking
token.auth_time < reset_at(when the user proved their password) rather thantoken.iat(when the JWT was refreshed) is rock-solid: even if an attacker's pre-reset session sneaks in a refresh at12:00:01before the async worker reaches the session shard, the refreshed JWT still carries yesterday'sauth_time < 12:00:00and is rejected immediately, while the real user logging in with their new password at12:00:01getsauth_time = 12:00:01 >= reset_atand works without interruption!
- Transaction 1 (Identity DB): update
Summary of key trade-offs
- Short-lived stateless JWTs (5 min) + pushed revocation vs. central session lookups: removes database calls from 700,000 API requests/s at 10x while keeping normal revocation at ~1–2 seconds and bounding event-bus outages to 5 minutes.
- Single-use rotating refresh tokens + 30 s session-checked retry cache: catches stolen refresh tokens in the wild without logging honest users out on flaky mobile Wi-Fi.
- Argon2id (~50 ms) in an isolated bounded pool + pre-hash layered throttling: makes leaked password tables expensive to crack while preventing credential-stuffing floods from starving the platform.
- Decoupled
identitiestable + relational core DB -> sharded session store at 10x: preserves strict ACID guarantees on accounts and credentials today, plugs in OIDC/SAML cleanly tomorrow, and scales high-frequency refresh writes horizontally when needed.
Intuition & how it works
Think of a scalable authentication platform like airport security paired with a 5-minute stamped boarding pass. Checking a traveler's passport and bags (verifying a password with a deliberately slow hash plus multi-factor authentication) is thorough and CPU-heavy, so it happens only once at the entrance (Auth Service). Once verified, the traveler receives two items: a 5-minute signed boarding pass — a JWT (JSON Web Token) digitally signed with a private key so any product microservice can verify it locally in microseconds using cached public keys — and a single-use renewal voucher — an opaque refresh token locked inside an HttpOnly browser cookie that quietly trades itself in at the Auth Service every 5 minutes for a fresh boarding pass.
Naive designs fail on either security or scale. Hashing passwords with a fast function like SHA-256 lets an attacker with GPUs test billions of guesses per second if the database leaks, while running a proper 50-millisecond slow hash without pre-hash rate limiting lets a credential-stuffing botnet (automated scripts replaying millions of leaked email/password pairs) burn 500+ CPU cores and take the site offline. On the session side, querying a central database on all 700,000 API calls/second at 10x scale creates a fragile bottleneck, whereas handing out 30-day stateless JWTs makes it impossible to kick an attacker out when a user resets a stolen password. Combining pre-hash throttling, an isolated Argon2id worker pool, 5-minute JWTs, rotating refresh tokens, and a lightweight pub/sub revocation stream solves all three problems together.
Walk through a concrete 4-step trace for Alice:
1. Login (POST /v1/login):
Edge checks IP + account rate limits in Redis (fast!). Auth API reads Alice's row from
the PostgreSQL primary, runs Argon2id (~50 ms) in the isolated Hasher Pool, creates session
s_1 (auth_time = 10:00), returns a 5-min JWT (in JS memory) + __Host-refresh=rt_1 cookie.
2. Normal API calls (70,000/s -> 700,000/s at 10x):
Product services verify the JWT's ES256 signature + expiry locally in RAM and check a tiny
in-memory revocation map (< 5,000 entries). Zero calls to Auth DB!
3. Refresh with Wi-Fi hiccup at 10:05 (POST /v1/token/refresh with rt_1):
Auth DB verifies s_1 is active, marks rt_1 used_at = 10:05, issues rt_2 + new JWT, and
caches the reply for 30 s. When Alice's browser retries rt_1 1 second later after a dropped
packet, the server re-checks s_1 is still unrevoked and returns the cached rt_2 cleanly.
4. Password reset at 10:12 (POST /v1/password/reset):
One DB transaction updates Alice's Argon2id hash, revokes s_1, sets tokens_valid_after = 10:12,
and emits user_tokens_revoked {sub: Alice, revoked_auth_before: 10:12}. Every microservice
rejects JWTs with auth_time < 10:12 within ~1-2 seconds.
Key trade-offs
- 5-minute stateless JWTs + pushed revocation vs. central opaque-token lookups. Local JWT verification eliminates network hops and central database load on 700,000 requests/s at 10x, at the cost that revoking an already-minted token requires pushing small revocation events to services (with a 5-minute worst-case window if the event bus is down, plus online introspection for high-risk actions).
- Access-token lifetime (5 minutes vs. 15–60 minutes). Shorter lifetimes shrink the worst-case exposure window if a revocation event is delayed, while multiplying refresh database writes (
2,000,000 active clients / 300 s = ~6,700 writes/sat 10x). Five minutes balances tight security bounds with manageable write throughput. - Deliberate hash cost (~50 ms Argon2id) vs. login CPU capacity. A memory-hard hash (an algorithm requiring megabytes of RAM per hash so GPUs cannot brute-force leaked hashes cheaply in parallel) protects passwords at rest, but costs ~60 CPU cores at 1,200 logins/s. Because fail-closed security forbids lowering hash parameters during traffic spikes, we trade away "cheap logins" and enforce strict rate limiting + a bounded hasher queue that returns fast
503s when full. - Progressive throttling + known-device tokens vs. hard account lockouts. Locking an account after 5 wrong passwords stops brute-force guessing on one account, but hands attackers an easy denial-of-service weapon against real users. Progressive delays/challenges bypassed by a signed
device_tokenon the owner's usual browser stop botnets while keeping legitimate users unblocked. - 30-second refresh-retry grace window vs. strict instant reuse revocation. Rotating refresh tokens on every use exposes stolen tokens when both attacker and victim try to spend the same token. Allowing a 30-second cached retry (only after confirming
sessions.revoked_at IS NULL) prevents flaky mobile networks from logging users out, trading a narrow 30-second window before replay theft triggers full session revocation. - Relational ACID database vs. sharded session store. Keeping
users,credentials, andsessionsin one PostgreSQL primary at launch (~35 GB) gives multi-table transactions and unique constraints out of the box. At 10x (6,700refreshes/s), splittingsessions+refresh_tokensinto auser_id-sharded cluster scales writes cleanly, trading single-database transactions for an outbox-drivenauth_time < reset_atrevocation flow. - KMS-encrypted hash wrapper (pepper) vs. operational key dependency. Encrypting Argon2id strings under a KMS (Key Management Service) key stops offline cracking if a SQL backup leaks alone and allows bulk key rotation, at the cost that losing the KMS key permanently invalidates stored password hashes.
Common mistakes
- Using fast hashes (SHA-256, MD5) or reversible encryption for passwords, or forgetting to use a slow hash on short 8–10 character MFA recovery codes.
- Leaking registered emails via account enumeration: returning
"Email not found"vs."Wrong password", or skipping Argon2id on unknown emails so missing accounts reply in 1 ms instead of 50 ms. - Running rate limits after password hashing, allowing attackers to exhaust 100% of CPU cores with wrong passwords before getting throttled.
- Returning a cached refresh-token retry response before checking whether the session was just revoked, which lets a logged-out session stay alive during the retry grace window.
- Storing JWTs or refresh tokens in
localStorage, where a single cross-site scripting (XSS) bug lets an attacker exfiltrate long-lived sessions. - Reading password hashes or
tokens_valid_afterfrom an asynchronous read replica, allowing an attacker's old password to keep working for seconds after a victim resets it. - Auto-linking external OIDC/SAML logins to existing accounts by email string alone without domain/ownership verification, enabling account takeover via untrusted identity providers.
- Bypassing MFA during email-based password reset, turning a compromised email inbox into a full MFA bypass.
- Restoring a database backup without replaying the security event log, accidentally reviving compromised passwords and un-revoking attacker sessions created after the snapshot timestamp.
Follow-up questions
- When a user resets a compromised password, how do you cut off active sessions rapidly without forcing every downstream API call to hit a central session store? Inside the password-reset transaction, mark the user's sessions revoked, set
users.tokens_valid_after = reset_at, and insert a transactional outbox eventuser_tokens_revoked {sub, revoked_auth_before: reset_at}. A relay publishes that event within ~1 second to a pub/sub topic subscribed to by every product service, which storesrevoked_users[sub] = reset_atin a tiny in-memory map and rejects any JWT whoseauth_time < reset_at(evicting the entry after the 5-minute max JWT lifetime + 60 s clock skew). Even if a service briefly loses the event stream, revoked sessions cannot refresh and any existing JWT expires within 5 minutes, while high-risk endpoints call/internal/v1/introspectsynchronously. - How would you extend the platform so enterprise tenants can mandate corporate single sign-on across their employees? Add
organizations,verified_domains(proven via a DNSTXTchallenge), andsso_connectionsstoring each tenant's OIDC issuer/client credentials or SAML IdP signing certificate. Switch the login UI to an email-first step: enteringalice@acme.comlooks upacme.com's policy and redirects the browser to Acme's IdP using OIDC Authorization Code + PKCE (state,nonce) or a signed SAMLAuthnRequest. On callback, validate the IdP's cryptographic signature, audience, and expiry, map(provider = 'oidc:conn_acme', subject = idp_sub)via theidentitiestable (provisioning new employees just-in-time), enforce org rules (disabling password login once SSO is mandatory and cappingabsolute_expires_atto e.g. 12 hours), includeorgandidpclaims in JWTs, and add a SCIM webhook endpoint so HR offboarding immediately suspends the user and emitsuser_tokens_revoked. - If cryptographic standards require stronger password-hashing settings, how can you upgrade stored credentials transparently without requiring mandatory password resets? Store hashes in a self-describing format (
$argon2id$v=19$m=19456,t=2,p=1$<salt>$<digest>) alongsideparams_versionso the verifier knows how to check both old and new hashes. When an active user logs in and passes verification against old parameters, immediately computenew_argon2id(password, fresh_salt, new_params)while the plaintext password is still in memory and overwrite the row. To protect dormant accounts right away without waiting months for them to log in, run an offline batch job that wraps every remaining old digest inside the new stronger hash — storingouter_digest = new_argon2id(old_digest, new_salt, new_params)while keeping(old_params, old_salt)alongside it — so an attacker who steals the database tomorrow must pay both hash costs, and unwrap it into a single directnew_argon2id(password)hash the next time that user logs in.
Follow-up questions
- When a user resets a compromised password, how do you cut off active sessions rapidly without forcing every downstream API call to hit a central session store?
- How would you extend the platform so enterprise tenants can mandate corporate single sign-on across their employees?
- If cryptographic standards require stronger password-hashing settings, how can you upgrade stored credentials transparently without requiring mandatory password resets?
Similar questions
- Multi-Tenant Educational Catalog, Checkout, and Streaming Platform
- SDET Internship Behavioral Interview Prompts
- Post-Coupon Order Totals with Sales Tax
- Piecewise Order Cost and Break-Even Volume
- Pointer Lifetimes, TLS over HTTP, and Transport Protocols
- Per-Interval Overlap Counts on a Line
More MathWorks interview questions
- Pointer Lifetimes, TLS over HTTP, and Transport Protocols Medium
- Fixed-Quota Task Reward Maximization Easy
- SDET Internship Behavioral Interview Prompts Medium Pro
- Post-Coupon Order Totals with Sales Tax Medium Pro
- Piecewise Order Cost and Break-Even Volume Medium Pro
- Per-Interval Overlap Counts on a Line Medium Pro
- Hypergeometric Red Draw Probability Easy Pro
- Sequential Draw Probabilities and Expected Count Easy Pro
- Global Character Substitution Sequence Medium Pro
- Unique Grid Cell Under Spatial Constraints Hard Pro