Appearance
Identity at Scale
48. How would you migrate an application from server-side sessions to JWTs?
The short answer
First ask why: if the browser app talks only to its own back end, sessions are usually the better choice, and the real need may be tokens for new clients, such as mobile or other services. If you proceed, migrate in parallel, not in one cut: add a token endpoint that issues short JWTs and rotating refresh tokens; make APIs accept both session cookies and bearer tokens through one authentication middleware that produces the same req.user; move clients one at a time; exchange an existing session for tokens on next request so nobody is logged out; keep revocation through refresh tokens and a deny list; and remove session support only when traffic on it reaches zero.
The migration in steps:
Decide the scope. Often the browser keeps its session, and only mobile and service clients move to tokens.
Build the token side: signing keys in a KMS, a JWKS endpoint, a token endpoint, refresh-token storage (JWT design).
One middleware, two inputs: it accepts a session cookie or a bearer token and produces the same user object, so handlers do not change.
tsexport async function authenticate(req: Request, res: Response, next: NextFunction) { const bearer = req.get('authorization')?.match(/^Bearer (.+)$/)?.[1] if (bearer) req.user = toUser(await verifyAccessToken(bearer)) // new path else if (req.session.userId) req.user = await users.findById(req.session.userId) // old path if (!req.user) return next(new HttpError(401, 'Sign in required')) next() }Move clients one by one, watching error rates per client.
Silent upgrade: a client with a valid session calls an exchange endpoint to receive tokens.
Measure and remove: count requests by auth type; remove session handling when it reaches zero.
Things that change, to call out: logout and "ban user" need refresh-token revocation and a deny list; permission changes take effect only when the access token expires; and CSRF protection is no longer needed for bearer-token calls but XSS becomes more dangerous if tokens are in the browser.
49. How would you support millions of active sessions?
The short answer
Store sessions in a Redis cluster, sharded by session ID, with replicas and automatic failover; at about 1 KB per session, 10 million sessions are only about 10 GB. Keep each session small, the user ID, tenant, auth time and a few flags, not whole profiles. Use TTLs for idle expiry, refreshed on activity but not on every request, and an absolute limit. Keep a per-user index of session IDs for "log out everywhere". Cache the session briefly in each app instance if Redis latency matters, and plan for Redis failure: a replica takes over, or users must sign in again.
| Concern | Design |
|---|---|
| Storage | Redis Cluster, sess:{id} → hash, about 1 KB each |
| Expiry | TTL of 30 minutes idle; refresh it at most once a minute to reduce writes |
| Absolute lifetime | auth_time checked against a maximum, such as 12 hours |
| Log out everywhere | Set user_sessions:{userId} of session IDs; delete all on demand |
| Read load | 50,000 requests per second → 50,000 Redis reads; a cluster handles it; optional 5-second local cache |
| Multi-region | Sessions written in the home region; replicated for reads; or tokens for global clients |
| Failure | Replica promotion; alert; worst case users sign in again, not data loss |
Numbers to say: 10 million active sessions × 1 KB = 10 GB, which fits in a three-shard cluster with room to spare. The bottleneck is request rate, not memory.
50. How would you secure APIs used by third-party partners?
The short answer
Give each partner a registered client and strong credentials: OAuth client credentials with short-lived, scoped tokens, ideally authenticated with private_key_jwt or mTLS rather than a shared secret, or, if you must, hashed, scoped, rotatable API keys. If partners act for your users, use the authorization code flow with consent. Enforce scopes and tenant boundaries on every call, rate limits and quotas per partner, request signing or IP allow-lists for high-value APIs, versioned contracts, and complete audit logs of what each partner accessed. Provide a sandbox, key rotation and a way to revoke a partner instantly.
| Control | Design |
|---|---|
| Identity | One client per partner; credentials per environment |
| Authentication | Client credentials with private_key_jwt or mTLS; or hashed API keys (API keys versus OAuth) |
| Acting for users | Authorization code with consent screen (OAuth flows) |
| Authorization | Scopes per endpoint; data restricted to the partner's tenants |
| Abuse | Rate limits and quotas per client; anomaly alerts |
| Integrity | Signed requests or webhooks with HMAC and timestamps for high-value calls |
| Lifecycle | Sandbox, rotation, instant revocation, deprecation notices |
| Evidence | Audit every call: partner, user, resource, result |
More on partner APIs in general: exposing APIs to partners.
51. How would you design audit logging for a regulated enterprise application?
The short answer
Define a standard audit event: who, on whose behalf, what action, which resource and tenant, when, from where, result, and a trace ID. Write audit events reliably: in the same transaction as the change through an outbox, never best-effort. Ship them to a separate, append-only, access-controlled store, write-once storage such as S3 Object Lock, with hash chaining so tampering is detectable. Keep them for the regulated period, often 1 to 7 years, encrypted, with personal data minimised. Provide search and export for auditors, alert on sensitive actions, and audit access to the audit log itself.
Hash chaining in one sentence: each record stores the hash of the previous record, so deleting or editing any record breaks every hash after it. The event format and what to audit are in audit logging across services.
52. How would you design a high-availability authentication service?
The short answer
If login is down, everything is down, so design it as the most available service you run. Run stateless instances in several zones, and ideally several regions, behind global load balancing. Replicate the user store with automatic failover, and sessions in a replicated Redis cluster. Make token verification local in every API, with cached JWKS, so already signed-in users keep working even if the auth service is unavailable. Keep signing keys in a regional KMS or HSM with keys in each region. Protect it from attacks with rate limits and bot defences, degrade gracefully, such as skipping a risk-score call if it times out, and practise regional failover.
| Failure | Design so that |
|---|---|
| One instance | Others serve; health checks remove it |
| One zone | Instances and data replicas in other zones |
| Whole region | Second region serves; DNS or anycast failover |
| User database | Synchronous replica promoted in seconds |
| Session store | Replicated Redis; worst case, users sign in again |
| Auth service fully down | APIs still verify existing tokens locally until they expire |
| Optional dependencies, such as risk scoring or email | Timeouts and fallbacks; login still works |
| Credential-stuffing attack | Rate limits and bot defences keep real users served (load shedding) |
The insight to volunteer: issuing tokens needs the auth service; checking them should not. That separation is what keeps an auth outage from taking every API down with it.
53. How would you design tenant-aware authorization across multiple services?
The short answer
Every token carries the tenant ID and the user, and every service enforces "may this user do this action on this resource in this tenant" itself. Keep tenant-scoped roles and permissions in a central authorization service or a policy engine, with policies and role assignments distributed to a decision point next to each service so checks are local and fast. Services always load resources filtered by tenant and then ask the policy. Pass tenant and user through every hop in signed tokens, put tenant IDs on every event and cache key, and audit cross-tenant access, such as support staff, explicitly.
| Layer | Tenant-aware rule |
|---|---|
| Token | tenant_id and sub signed by the IdP; never from a header |
| Gateway | Reject tokens without a tenant; route by tenant if tenants are sharded |
| Service | SELECT … WHERE tenant_id = $tenant, plus row-level security (tenant isolation) |
| Policy | Roles assigned per tenant; checks local through a sidecar engine (centralised authorization) |
| Events | Tenant ID in every message; consumers set tenant context before work |
| Caches, storage | Tenant-prefixed keys and paths |
| Support access | Time-limited, approved, audited elevation into a tenant |