Skip to content

Interview PrepAuth designs · Advanced

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:

  1. Decide the scope. Often the browser keeps its session, and only mobile and service clients move to tokens.

  2. Build the token side: signing keys in a KMS, a JWKS endpoint, a token endpoint, refresh-token storage (JWT design).

  3. One middleware, two inputs: it accepts a session cookie or a bearer token and produces the same user object, so handlers do not change.

    ts
    export 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()
    }
  4. Move clients one by one, watching error rates per client.

  5. Silent upgrade: a client with a valid session calls an exchange endpoint to receive tokens.

  6. 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.

ConcernDesign
StorageRedis Cluster, sess:{id} → hash, about 1 KB each
ExpiryTTL of 30 minutes idle; refresh it at most once a minute to reduce writes
Absolute lifetimeauth_time checked against a maximum, such as 12 hours
Log out everywhereSet user_sessions:{userId} of session IDs; delete all on demand
Read load50,000 requests per second → 50,000 Redis reads; a cluster handles it; optional 5-second local cache
Multi-regionSessions written in the home region; replicated for reads; or tokens for global clients
FailureReplica 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.

ControlDesign
IdentityOne client per partner; credentials per environment
AuthenticationClient credentials with private_key_jwt or mTLS; or hashed API keys (API keys versus OAuth)
Acting for usersAuthorization code with consent screen (OAuth flows)
AuthorizationScopes per endpoint; data restricted to the partner's tenants
AbuseRate limits and quotas per client; anomaly alerts
IntegritySigned requests or webhooks with HMAC and timestamps for high-value calls
LifecycleSandbox, rotation, instant revocation, deprecation notices
EvidenceAudit 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.

servicechange + audit rowone transactionaudit streamaudit servicevalidate, hash chainredactwrite-once storage7-year retention locksearch for auditorsaccess to logs is audited
Recorded with the change, stored where nobody can edit it. The audit event commits with the business change, so neither exists without the other. The store cannot be altered or deleted before its retention ends, and the hash chain proves no record was removed.

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.

FailureDesign so that
One instanceOthers serve; health checks remove it
One zoneInstances and data replicas in other zones
Whole regionSecond region serves; DNS or anycast failover
User databaseSynchronous replica promoted in seconds
Session storeReplicated Redis; worst case, users sign in again
Auth service fully downAPIs still verify existing tokens locally until they expire
Optional dependencies, such as risk scoring or emailTimeouts and fallbacks; login still works
Credential-stuffing attackRate 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.

LayerTenant-aware rule
Tokentenant_id and sub signed by the IdP; never from a header
GatewayReject tokens without a tenant; route by tenant if tenants are sharded
ServiceSELECT … WHERE tenant_id = $tenant, plus row-level security (tenant isolation)
PolicyRoles assigned per tenant; checks local through a sidecar engine (centralised authorization)
EventsTenant ID in every message; consumers set tenant context before work
Caches, storageTenant-prefixed keys and paths
Support accessTime-limited, approved, audited elevation into a tenant

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
System Design
The method
Case studies
Auth designs
Scenarios
Other topics
Nothing picked yet