Redis is usually the better place to store one-time passwords (OTPs) than a traditional database. OTPs are short-lived, read once and thrown away, and Redis is built for exactly that kind of data, with in-memory speed and built-in expiration. This guide compares Redis and a database for OTP storage, covers security best practices, and shows a Node.js example you can adapt.

What Is an OTP?

An OTP (One-Time Password) is a temporary code generated for user verification. It is commonly used for:

  • Phone verification
  • Email verification
  • Password reset
  • Two-Factor Authentication (2FA)
  • Login verification

Since OTPs are only valid for a short period (usually 30 seconds to 10 minutes), they have different storage requirements than permanent user data.

Why Redis Is Perfect for OTP Storage

Redis is an in-memory data store designed for speed and temporary data.

1. Extremely Fast

Redis stores data in RAM instead of reading from disk. This means:

  • Read operations happen in microseconds.
  • Write operations are almost instantaneous.
  • It suits authentication systems handling thousands of requests per second.

A typical flow looks like this:

User requests OTP
        ↓
Store OTP in Redis
        ↓
User submits OTP
        ↓
Verify in Redis
        ↓
Delete OTP

The entire process is incredibly fast.

2. Built-in Expiration (TTL)

One of Redis's greatest features is automatic expiration. Instead of manually deleting expired OTPs, simply set a TTL (Time To Live). See the Redis EXPIRE documentation for details.

await redis.set(
    `otp:${userId}`,
    otpHash,
    {
        EX: 300 // expires after 5 minutes
    }
);

After 5 minutes, Redis automatically removes the OTP. No cron jobs, no cleanup scripts, no database maintenance.

3. Automatic Cleanup

Imagine sending one million OTPs daily. If stored in a database, you'll accumulate one million new rows every day. Soon you'll need:

  • Cleanup scripts
  • Scheduled jobs
  • Additional indexing
  • Storage optimization

Redis handles this automatically through expiration.

4. Better Performance Under Heavy Load

High-traffic applications constantly generate OTPs. Examples include:

  • Banking apps
  • Ride-sharing platforms
  • Food delivery services
  • Social media
  • E-commerce websites

Redis easily handles hundreds of thousands of operations per second, while a large, poorly indexed OTP table in a traditional database gets slower as it grows.

5. Reduced Database Load

Databases should focus on long-term information such as users, orders, transactions, products and payments. OTPs are temporary, so keeping them in Redis prevents unnecessary writes to your primary database.

Why Storing OTPs in a Database Isn't Ideal

Storing OTPs in MySQL, PostgreSQL, or MongoDB works, but it's usually not the best design. Some drawbacks include:

Permanent Storage

Databases are designed for persistent data. OTPs should disappear after a few minutes.

Extra Cleanup Required

You'll need scheduled jobs like:

DELETE FROM otp_codes
WHERE expires_at < NOW();

This creates additional maintenance.

Increased Storage

Millions of expired OTPs consume storage unnecessarily.

Slower Queries

As the OTP table grows, searches become slower unless proper indexing is maintained.

Security Best Practices for OTP Storage

Regardless of where OTPs are stored, follow these practices. The OWASP Authentication Cheat Sheet is a good reference.

Hash OTPs

Instead of storing 123456, store a hash of it. This prevents attackers from reading OTPs if Redis or the database is compromised. Because a 6-digit code has only a million possibilities, a plain SHA-256 can be brute-forced quickly, so use an HMAC with a secret key (for example HMAC-SHA256) rather than a bare hash.

Limit Verification Attempts

Allow only 3–5 attempts, then temporarily block the account or request. Redis can easily track attempts with counters, and the same approach powers rate limiting a Node.js API with Redis.

Use Short Expiration Times

Recommended TTL:

  • Email OTP: 5–10 minutes
  • SMS OTP: 2–5 minutes
  • Login OTP: 30–120 seconds

Delete OTP After Success

Even if the TTL hasn't expired, remove the OTP immediately after successful verification so it can't be reused.

When Should You Use a Database?

A database is appropriate when you need:

  • OTP audit logs
  • Compliance records
  • Analytics
  • Historical verification reports

A common production architecture looks like this:

Redis
│
├── Active OTP
├── Retry Count
├── Rate Limit
└── Auto Expire

Database
│
├── Verification History
├── Audit Logs
├── Login Records
└── Security Events

Redis handles active OTPs, while the database stores historical information. The same split works well for sessions and tokens, as in JWT refresh token rotation in Node.js.

Redis OTP Example (Node.js)

This example generates a random OTP, stores an HMAC of it with a TTL, and verifies it with an atomic read-and-delete so the code can only be used once.

import crypto from 'node:crypto';

const hashOtp = (otp) =>
    crypto.createHmac('sha256', process.env.OTP_SECRET).update(otp).digest('hex');

async function createOtp(userId) {
    const otp = String(crypto.randomInt(0, 1000000)).padStart(6, '0');
    await redis.set(`otp:${userId}`, hashOtp(otp), { EX: 300 });
    return otp; // send via SMS or email
}

async function verifyOtp(userId, input) {
    const stored = await redis.getDel(`otp:${userId}`); // read and delete atomically
    if (!stored) return false;

    const a = Buffer.from(stored);
    const b = Buffer.from(hashOtp(input));
    return a.length === b.length && crypto.timingSafeEqual(a, b);
}

Note that GETDEL consumes the code even on a wrong guess. If you want to allow several attempts, read with GET, track a retry counter, and delete only on success or when attempts run out.

Final Recommendation

For almost every modern application, Redis is the best solution for storing OTPs. Its fast performance, built-in expiration, and automatic cleanup make it ideal for temporary authentication data. Traditional databases are better suited for permanent records, while Redis excels at short-lived, high-speed data like OTPs.

If you're building a secure authentication system, the recommended architecture is simple:

  • Store active OTPs in Redis
  • Store verification history and audit logs in your database
  • Hash OTPs before storing
  • Use TTL for automatic expiration
  • Delete OTPs immediately after successful verification
  • Implement rate limiting and retry limits

By combining Redis with your primary database, you get the best balance of performance, scalability, security, and maintainability.

FAQ

Is Redis better than MongoDB for OTP storage?

Yes. Redis is designed for temporary, high-speed data with automatic expiration, making it a better choice for OTP storage than MongoDB.

Should I hash OTPs before storing them?

Yes. Hashing OTPs adds an extra layer of security in case your storage system is compromised. Use a keyed hash (HMAC) because OTPs have a small value space.

How long should an OTP remain valid?

Most applications use 2–5 minutes for SMS OTPs and 5–10 minutes for email OTPs.

Can I use both Redis and a database?

Absolutely. Store active OTPs in Redis and keep verification logs or audit history in your database. This is the architecture used by many production systems.