Skip to main content
SDMastery
easy7 min readUpdated 2026-06-03

Design an Authentication System

Design an authentication system with JWT vs sessions, OAuth2 flows, password hashing (bcrypt/argon2), MFA, and token refresh.

Design an Authentication System system design overview showing key components and metrics
High-level overview of Design an Authentication System

Problem Statement

Design a centralized authentication and authorization system that handles user registration, login, token management, OAuth2 social logins, and multi-factor authentication (MFA). The system must be secure against common attacks (brute force, credential stuffing, token theft) while maintaining low-latency auth checks for every API request.

Requirements

Design an Authentication System system architecture with service components and data flow
System architecture for Design an Authentication System

Functional

  • User registration with email/password and email verification
  • Login with password (bcrypt/argon2-hashed), returning JWT access + refresh tokens
  • OAuth2 social login (Google, GitHub, Apple) using Authorization Code flow
  • Multi-factor authentication (TOTP via authenticator app, SMS fallback)

Non-Functional

  • Security: Passwords hashed with Argon2id (memory-hard), tokens signed with RS256
  • Latency: Token validation <5ms (stateless JWT), login <500ms
  • Availability: 99.99% -- auth downtime blocks all services
  • Scale: 100M users, 50K logins/second at peak

Core Architecture

Step-by-step diagram showing how Design an Authentication System works in practice
How Design an Authentication System works step by step
  1. Auth API Service -- Handles registration, login, and token endpoints. Validates credentials against the user store, issues JWTs (short-lived access token: 15 min, long-lived refresh token: 7 days). Implements rate limiting per IP and per account to block brute force.

  2. Token Service -- Issues and validates JWTs signed with RS256 asymmetric keys. Public keys are published at /.well-known/jwks.json so all downstream services can validate tokens without calling the auth service. Supports token revocation via a short-lived blacklist in Redis.

  3. OAuth2 Gateway -- Implements Authorization Code flow with PKCE for social logins. Exchanges authorization codes for provider tokens, maps provider user IDs to internal accounts (creating accounts on first login). Stores provider refresh tokens encrypted at rest.

Comparison table for Design an Authentication System showing key metrics and tradeoffs
Comparing key aspects of Design an Authentication System
  1. MFA Service -- Generates TOTP secrets (stored encrypted), validates 6-digit codes with a 30-second window and one-step tolerance. For SMS fallback, integrates with Twilio with rate limiting (max 5 SMS/hour per account). Recovery codes are pre-generated and bcrypt-hashed.

Database Choice

PostgreSQL for the user table (email, password_hash, mfa_secret_encrypted, created_at, locked_until). Relational integrity for OAuth provider linkage (users-to-providers many-to-many). Redis for two critical uses: (1) refresh token whitelist with TTL matching token expiry, enabling instant revocation; (2) rate limiting counters using INCR with TTL (sliding window). Both are small, high-throughput workloads ideal for Redis.

Interview tips for Design an Authentication System system design questions
Interview tips for Design an Authentication System

Key API Endpoints

text
POST /api/v1/auth/register
  -> Body: \{ email: "[email protected]", password: "...", name: "Jane" \}

POST /api/v1/auth/login
  -> Body: \{ email: "[email protected]", password: "...", mfa_code?: "123456" \}
  -> Returns: \{ access_token: "eyJ...", refresh_token: "...", expires_in: 900 \}

POST /api/v1/auth/refresh
  -> Body: \{ refresh_token: "..." \}
  -> Returns: \{ access_token: "eyJ...", expires_in: 900 \}

Scaling Insight

JWT validation is stateless and decentralized -- the critical scaling property. Every microservice validates tokens locally by checking the RS256 signature against the cached public key. No network call to the auth service is needed for 99.9% of requests. The only centralized check is the Redis revocation blacklist, which holds only recently-revoked tokens (max 15-min TTL) and stays small.

Decision guide showing when to use Design an Authentication System and when to avoid
When to use Design an Authentication System

Key Tradeoffs

DecisionOption AOption BChosen
Token formatStateless JWTServer-side sessionsJWT -- eliminates session store bottleneck, scales horizontally
Hashingbcrypt (proven)Argon2id (memory-hard)Argon2id -- better resistance to GPU attacks, tunable memory cost
Token revocationBlacklist in RedisShort expiry + no revocationBlacklist -- small overhead, but enables instant logout for compromised accounts

Practical Implementation for .NET Developers

In a .NET application, you would typically implement this pattern using the following approach:

Pros and cons analysis of Design an Authentication System for system design decisions
Advantages and disadvantages of Design an Authentication System

ASP.NET Core setup: Create a service class that encapsulates the logic, register it with dependency injection, and inject it into your controllers or minimal API endpoints. The built-in DI container handles lifecycle management.

Entity Framework Core: For database interactions, EF Core provides the ORM layer. Use migrations for schema management and raw SQL for performance-critical queries. Consider Dapper for read-heavy paths where EF Core's overhead matters.

Azure integration: If deploying to Azure, leverage managed services — Azure Cache for Redis, Azure SQL, Azure Service Bus, Azure Cosmos DB. These eliminate operational overhead and provide built-in monitoring through Application Insights.

Real-world companies using Design an Authentication System in production systems
Real-world examples of Design an Authentication System

Testing: Use xUnit with Testcontainers for integration tests that spin up real databases in Docker. Mock external dependencies with NSubstitute. The WebApplicationFactory class lets you test your entire HTTP pipeline in-process.

Monitoring: Add Application Insights telemetry to track request latency, dependency calls, and custom metrics. Use structured logging with Serilog to make production debugging possible:

text
Log.Information("Processing order {OrderId} for {CustomerId}", orderId, customerId);

This gives you searchable, structured logs in Azure Monitor or Seq.

Data flow diagram for Design an Authentication System showing request and response paths
Data flow through Design an Authentication System

System-Specific Clarifying Questions

Before designing Authentication System, ask questions specific to THIS system:

Key components of Design an Authentication System with roles and responsibilities
Key components of Design an Authentication System
  1. Who are the primary users? Understanding the user base shapes every technical decision — consumer apps have different requirements than enterprise B2B systems.
  2. What is the read-to-write ratio? This determines whether you optimize for fast reads (caching, denormalization) or fast writes (write-ahead logs, async processing).
  3. What is the geographic distribution? Users in one country vs. global users fundamentally changes your data replication and CDN strategy.
  4. What is the acceptable latency? Some features need sub-100ms responses, others can tolerate seconds. This determines your caching and architecture strategy.
  5. What is the consistency requirement? Some data (payments, inventory) needs strong consistency. Other data (social feeds, recommendations) can be eventually consistent.

Architecture Deep Dive

The architecture for Authentication System should be designed around the specific access patterns of the system. Do not apply generic templates — every system has unique hotspots, bottlenecks, and scaling challenges.

Write Path: How does data enter the system? Is it bursty (event-driven, flash sales) or steady (sensor data, logs)? Bursty writes need queuing and backpressure. Steady writes can go directly to the database.

Read Path: How is data consumed? Is it fan-out (one write, many reads like social feeds) or point lookups (one read for specific data like user profiles)? Fan-out reads benefit from pre-computation and caching. Point lookups benefit from efficient indexing.

Hot Spots: Where are the bottlenecks? For Authentication System, identify the component that will fail first under load and design mitigation strategies: caching, sharding, rate limiting, or async processing.

Sources