OTP (One-Time Password) Service¶
Quick Reference Guide for System Design Interviews
Problem Statement¶
Design a One-Time Password (OTP) service that generates, delivers, and verifies time-limited codes for user authentication. The system should be secure, highly available, and support multiple delivery channels.
Requirements¶
Functional Requirements¶
- Generate OTP for user (phone/email)
- Deliver OTP via SMS, email, or push
- Verify OTP entered by user
- Rate limiting to prevent abuse
- Support for multiple use cases (login, transactions)
Non-Functional Requirements¶
- Availability: 99.99% (critical for auth)
- Latency: Generate < 50ms, Deliver < 5s
- Security: Cryptographically secure OTPs
- Scale: 100M OTPs/day
High-Level Architecture¶
OTP Generation¶
Random OTP Generation:
import secrets
def generate_otp(length=6):
# Cryptographically secure random
return ''.join(
str(secrets.randbelow(10)) for _ in range(length)
)
# DO NOT use random.randint() - not secure!
TOTP Generation:
import hmac, hashlib, struct, time
def generate_totp(secret, interval=30):
counter = int(time.time() // interval)
counter_bytes = struct.pack('>Q', counter)
hmac_hash = hmac.new(secret, counter_bytes, hashlib.sha1).digest()
offset = hmac_hash[-1] & 0x0F
code = struct.unpack('>I', hmac_hash[offset:offset+4])[0]
code = (code & 0x7FFFFFFF) % 1000000
return f'{code:06d}'
OTP Storage¶
OTP Verification Flow¶
Delivery Service¶
Rate Limiting & Security¶
API Design¶
Interview Discussion Points¶
- How do you generate secure OTPs?
- Cryptographically secure random (not Math.random)
- 6 digits = 1M combinations
-
Short expiry + limited attempts
-
Why hash the OTP?
- Security: Don't expose in logs/breach
-
Compare hashes on verification
-
How do you prevent brute force?
- 3 attempts max per OTP
- Rate limit per user/IP/phone
-
Exponential backoff
-
How do you handle SMS delivery failures?
- Multiple SMS providers (fallback)
- Retry with backoff
-
Alternative channel (voice, push)
-
How do you ensure high availability?
- Redis cluster (replicated)
- Multiple delivery providers
-
Async delivery via queue
-
What about TOTP vs random OTP?
- TOTP: No network needed, works offline
- Random OTP: Simpler, no app required