OTP & Expiration
Redis OTP & Expiration Codes
Build secure one-time password (OTP) and verification code systems with Redis auto-expiration. Perfect for SMS verification, email confirmation, and 2FA.
Real-World Business Scenario
A fintech app requires SMS verification for login and transactions. Each OTP must be valid for exactly 5 minutes, limited to 3 verification attempts, and a user can only request 1 OTP per 60 seconds. Storing this in a SQL database requires complex cleanup jobs. Redis TTL handles expiration automatically, and atomic operations ensure security constraints are enforced without race conditions.
Architecture Diagram
User requests OTP → App Server
↓
Generate 6-digit code
↓
┌─────────────────────────────────────┐
│ Redis │
│ ┌─────────────────────────────────┐ │
│ │ otp:{phone}:code = 583921 │ │
│ │ TTL = 300s (5 min) │ │
│ ├─────────────────────────────────┤ │
│ │ otp:{phone}:attempts = 0 │ │
│ │ TTL = 300s │ │
│ ├─────────────────────────────────┤ │
│ │ otp:{phone}:cooldown = 1 │ │
│ │ TTL = 60s (resend cooldown) │ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────┘
↓ Send via SMS Gateway
User receives code → Submits for verification
Key Commands Explained
Performance Analysis
SET with EX and NX: O(1), ~0.1ms. No background cleanup jobs needed — Redis TTL handles expiration automatically.
Memory: Each OTP uses ~3 keys × ~100 bytes = ~300 bytes. 1M concurrent OTPs = ~300MB. Very manageable.
INCR for attempt counting: O(1), atomic. No race conditions even under concurrent verification requests.
TTL precision: Redis expires keys with millisecond accuracy. No risk of serving an OTP at 5:01.
Common Pitfalls
Not using NX on SET: Without NX, a second OTP request overwrites the first, confusing users who already received the original code.
Forgetting attempt limits: Without INCR-based attempt tracking, attackers can brute-force a 6-digit OTP (1M combinations) in minutes.
Storing OTP in plain text: For high-security scenarios, store a hash (SHA-256) of the OTP instead. Compare hashes during verification.
No cooldown between requests: Without the cooldown key, automated scripts can trigger thousands of SMS messages, costing money and annoying users.
Best Practices
Always use SET NX EX together — atomic creation with TTL in one command.
Limit attempts to 3-5 and delete the OTP on exceeding the limit.
Implement resend cooldown (60s) to prevent SMS bombing.
Use cryptographically secure random number generation for OTP codes.
Log all OTP generation and verification events for audit trails.
Consider HMAC-based OTP (HOTP/TOTP) for 2FA instead of SMS for higher security.
Runnable Demo
Redis Demo
Click "Step" or "Run All" to execute commands...
▌