Skip to content
send.io
All posts

Email OTP verification: how it works and how to implement it

Email OTP verification follows a six step lifecycle with security checkpoints at each stage. Learn how to implement it securely. This guide includes hashed token storage, rate limiting at three levels, tested HTML and React templates, and a production readiness checklist you can use before deploy.

On this page
TL;DR: Email OTP is a six-step lifecycle, and each step has a security checkpoint. Most tutorials miss two things: delivery latency is a security property (a late code is a failed authentication), and rate limiting at three levels (per user, per IP, per endpoint) is the primary control between a 6-digit code and account takeover. Test the full flow in the send.io sandbox.

Your email OTP endpoint is an attack surface. A 6-digit code with a 10-minute expiry window gives an attacker 1 million possible combinations and 600 seconds to try them. Your rate limiter is the primary control standing between that math and an account takeover.

Most email OTP tutorials stop at "generate a random number and send it." This article treats OTP as a full lifecycle with security properties at each step, and it names the delivery latency problem that most tutorials ignore. An OTP that arrives after the user has moved on is a failed authentication, which makes delivery speed a security property, not just a UX nicety.

Understanding the email OTP authentication flow

Email OTP verification proves you own an email address or strengthens an authentication claim by sending a time-limited code to an address you control. You retrieve the code from your inbox and submit it back to the application, which validates the code against a stored hash and grants access if the match succeeds within the expiry window.

The flow has six discrete steps: request, generation, delivery, input, validation, and access. Each step has a security checkpoint. OWASP recommends you generate OTPs with a cryptographically secure pseudo-random number generator (CSPRNG) and enforce a short time-to-live (TTL). This article uses the following TTL guidance as its reference: for second-factor codes, 2–5 minutes is typical and 10 minutes is the practical upper limit, depending on your delivery latency measurements. Passwordless login typically runs 15–30 minutes. Later sections refer back to this paragraph instead of restating the numbers.

Email OTP vs. SMS: delivery mechanics

Email OTP and SMS OTP have different delivery latency patterns, abuse exposure, and regional reliability. SMS delivery in India typically ranges from 3–10 seconds under normal conditions, extending to 30 seconds during peak hours. Email delivery latency varies more widely by receiving ISP and can range from seconds to several minutes for transactional mail.

Email OTPs resist large-scale pumping attacks better than SMS OTPs because email lacks the termination fee structure that makes SMS pumping profitable. Attackers profit from termination fees on premium-rate numbers, making high-volume SMS attacks economically viable. Email lacks this fee structure, so email-based OTPs face lower exposure to the large-scale network abuse that SMS pumping inflicts.

NIST SP 800-63B-4 treats an out-of-band authentication as invalid unless it completes within 10 minutes, and it accepts each secret only once. For issued recovery codes, it sets different maximums by channel: 10 minutes when sent by text message or voice, and 24 hours when sent to an email address. The guidance doesn't define email address verification (confirming ownership at signup) as a separate case, so treat the longer verification TTLs below as common practitioner practice, not a NIST rule. For email verification flows, you have flexibility on expiry windows. For second-factor and passwordless flows, use the TTL guidance in "Understanding the email OTP authentication flow" above.

The trade-off: Email accounts can be compromised independently of your application, making email OTP less secure than TOTP or hardware keys for high-value authentication. Use email OTP for verification-only flows (confirming address ownership) or as a second factor alongside a password, not as the sole authentication mechanism for sensitive accounts.

Optimal workflows for email OTP

Email OTP works best in three specific workflows:

Email address verification: Confirming that a user can receive messages at an address during signup or when adding a secondary contact method. TTL can extend to 15–30 minutes because you're confirming address ownership, not granting account access.

Passwordless authentication: Replace passwords with email codes or magic links for low-friction login flows. Most implementations expire these tokens after 15–30 minutes, and 15 minutes is a widely used default, because users need time to switch to their inbox. Some implementations set 5 minutes as a floor to limit brute-force exposure, but that is a minimum, not the typical recommendation.

Second-factor authentication: Add email OTP as a "something you have" factor alongside a password. Sources differ on expiry for this flow: 2–5 minutes is more typical for login codes, and NIST SP 800-63B-4 requires out-of-band authentication to complete within 10 minutes. A 5–10 minute TTL works as a practical upper range rather than a fixed standard for email, and setting attempt limits toward the stricter end (around 3–5 tries, with a 15-minute cooldown) is a sensible precaution because this is an active authentication flow.

Flow Type

Use Case

Session Management

Integration Surface

TTL window

Verification-only

Email confirmation during signup

No session created

Single endpoint (verify)

15–30 minutes

Passwordless auth

Primary login mechanism

Full session on success

Send + verify endpoints

15–30 minutes

Second-factor

Additional layer after password

Elevate existing session

Send + verify + session upgrade

2–5 minutes typical, 10 minutes maximum

The end-to-end email OTP lifecycle

The email OTP lifecycle starts when a user requests a code and ends when your application either grants access or the code expires unused. Each step has a failure mode that turns a simple auth flow into a security vulnerability if you skip the checkpoint.

No rate limiting on the request endpoint allows email pumping attacks that send unlimited messages and inflate your sending costs. Using Math.random() or a non-cryptographic RNG for generation produces predictable codes that attackers can enumerate faster than brute force. Storing plaintext codes exposes them in database dumps, logs, or debug output. Slow delivery means the code arrives after the user abandons the flow. No attempt limits on verification allow brute-force attacks, and no single-use enforcement allows replay attacks. No expiry enforcement means old codes remain valid indefinitely.

Generating secure email OTP values

Use a cryptographically secure random number generator to create OTPs, not Math.random() or rand(). Non-cryptographic RNGs use predictable seeds and internal state that attackers can reverse-engineer, reducing the effective keyspace below the theoretical 1 million combinations of a 6-digit code.

Here's a Node.js implementation using the crypto module:

const crypto = require('crypto');

function generateOTP(length = 6) {
const max = Math.pow(10, length);
const randomNumber = crypto.randomInt(0, max);
return randomNumber.toString().padStart(length, '0');
}

const code = generateOTP(6);

crypto.randomInt() uses the operating system's entropy pool, which makes the output unpredictable even with knowledge of previous outputs.

OWASP recommends considering 8-digit or longer codes where usability allows. A 6-digit code gives you about 1 million combinations, and an 8-digit code gives you 100 million. The trade-off is typing friction: 6 digits fits on one screen and users can transcribe it without friction, while 8 digits can increase typos and abandonment.

For high-security environments, alphanumeric codes expand the keyspace further (36^6 = 2.2 billion combinations for a 6-character code), but they introduce usability issues with case sensitivity and character ambiguity (0 vs O, 1 vs l).

Database schema for email OTP storage

Hash OTPs before storage, never store them in plaintext. Hashing prevents accidental disclosure via logs, metrics, or debugging tools and reduces blast radius if the database is briefly exposed during the OTP's validity window.

A 6-digit OTP gives attackers a small keyspace (~1 million possibilities), which means an attacker with database access can brute-force any OTP hash quickly. Hashing OTPs does not provide strong offline attack resistance the way password hashing does. The OWASP Password Storage Cheat Sheet says fast algorithms such as SHA-256 are unsuitable for passwords because they let attackers test large numbers of guesses quickly, and it recommends slow, salted algorithms such as Argon2id. Hashing OTPs remains useful for a different reason: it prevents accidental disclosure.

Hashing algorithm choice matters less for OTPs than it does for passwords. SHA-256 is the common choice because it keeps verification fast and prevents casual inspection without adding latency, and some reference implementations use bcrypt instead: the StartMessaging OTP example hashes codes with const hash = await bcrypt.hash(code, 10). Either approach satisfies the core requirement, which is to store only the hash and never the plaintext code.

Here's the schema:

Column

Data type

Purpose

id

UUID

Primary key

user_id

UUID

Foreign key to users table

token_hash

VARCHAR(64)

SHA-256 hash of the OTP code

expires_at

TIMESTAMP

Absolute expiration time

created_at

TIMESTAMP

Creation timestamp

used

BOOLEAN

Single-use enforcement flag (default false)

purpose

VARCHAR(20)

Flow type, with application-defined example values such as login, verification, password_reset

PostgreSQL DDL:

CREATE TABLE otp_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(64) NOT NULL,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
used BOOLEAN NOT NULL DEFAULT FALSE,
purpose VARCHAR(20) NOT NULL,
-- application-specific example values, not an industry standard: replace them with your own flow types
CONSTRAINT valid_purpose CHECK (purpose IN ('login', 'verification', 'password_reset'))
);

CREATE INDEX idx_otp_user_created ON otp_tokens(user_id, created_at DESC);
CREATE INDEX idx_otp_expires ON otp_tokens(expires_at) WHERE used = FALSE;

The idx_otp_expires partial index speeds up cleanup queries that delete expired tokens. The composite index on user_id, created_at supports rate limiting queries that count recent OTP requests per user.

Preventing OTP reuse vulnerabilities

Single-use enforcement requires you to mark an OTP as used = true immediately after successful verification, before granting access. This prevents replay attacks where an attacker intercepts a valid code and submits it multiple times.

Here's the verification flow with single-use enforcement:

async function verifyOTP(userId, submittedCode) {
const tokenHash = crypto
.createHash('sha256')
.update(submittedCode)
.digest('hex');

const result = await db.query(`
UPDATE otp_tokens
SET used = TRUE
WHERE user_id = $1
AND token_hash = $2
AND used = FALSE
AND expires_at > NOW()
RETURNING id
`, [userId, tokenHash]);

if (result.rowCount === 0) {
return { success: false, reason: 'invalid_or_expired' };
}

return { success: true };
}

The UPDATE ... WHERE used = FALSE pattern makes the check-and-mark operation atomic. Without this, two concurrent requests with the same code could both pass the used = FALSE check before either marks it used, allowing the same code to grant access twice.

End-to-end email OTP verification logic

The complete verification function combines hash comparison, expiry checking, single-use enforcement, and attempt limiting:

async function verifyOTPComplete(userId, submittedCode) {
const recentAttempts = await db.query(`
SELECT COUNT(*) as count
FROM otp_verification_attempts
WHERE user_id = $1
AND attempted_at > NOW() - INTERVAL '15 minutes'
AND success = FALSE
`, [userId]);

if (parseInt(recentAttempts.rows[0].count) >= 5) {
return {
success: false,
reason: 'rate_limited',
retryAfter: 900
};
}

const tokenHash = crypto
.createHash('sha256')
.update(submittedCode)
.digest('hex');

const result = await db.query(`
UPDATE otp_tokens
SET used = TRUE
WHERE user_id = $1
AND token_hash = $2
AND used = FALSE
AND expires_at > NOW()
RETURNING id
`, [userId, tokenHash]);

await db.query(`
INSERT INTO otp_verification_attempts (user_id, attempted_at, success)
VALUES ($1, NOW(), $2)
`, [userId, result.rowCount > 0]);

if (result.rowCount === 0) {
return { success: false, reason: 'invalid_or_expired' };
}

return { success: true };
}

OWASP recommends a typical lockout threshold of 5–10 unsuccessful attempts. The implementation above uses 5 attempts per 15 minutes per user, which gives legitimate users room for typos while blocking brute-force attacks.

Implementing email OTP: step by step

This section walks through a complete email OTP implementation from token generation to verification. Each step includes working code you can adapt to your stack.

1. Generate and store OTP tokens

Generate the OTP using a cryptographically secure RNG, hash it immediately, and insert it with expiry and tracking metadata:

const crypto = require('crypto');

async function createAndStoreOTP(userId, purpose) {
const code = crypto.randomInt(0, 1000000).toString().padStart(6, '0');

const hash = crypto
.createHash('sha256')
.update(code)
.digest('hex');

const expiresAt = new Date(Date.now() + 10 * 60 * 1000);

await db.query(`
INSERT INTO otp_tokens (user_id, token_hash, expires_at, purpose)
VALUES ($1, $2, $3, $4)
`, [userId, hash, expiresAt, purpose]);

return { code, expiresAt };
}

The function returns the plaintext code (which you send via email) and stores the hash. The plaintext code exists only in memory during generation and in the user's inbox. It never touches your database or application logs. The purpose field lets you enforce different TTLs and rate limits for different flows.

2. Triggering the email OTP delivery

Send the plaintext code via your transactional email provider. Here's a generic implementation using plain HTTP POST:

// Set EMAIL_API_URL to your provider's transactional send endpoint.
async function sendOTPEmail(email, code) {
const response = await fetch(process.env.EMAIL_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.EMAIL_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'auth@yourapp.com',
to: [email],
subject: 'Your verification code',
html: `
<p>Your verification code is:</p>
<h2 style="font-size: 36px; letter-spacing: 4px;">${code}</h2>
<p>This code expires in 10 minutes.</p>
`,
text: `Your verification code is: ${code}. It expires in 10 minutes.`
})
});

if (!response.ok) {
throw new Error(`Email send failed: ${response.status}`);
}

return await response.json();
}

Time-sensitive sends like OTP codes need priority queuing so they don't wait behind bulk campaign sends. Resend and Postmark are established transactional senders, and send.io lets you tag time-sensitive sends for priority, so they queue ahead of bulk campaign sends. send.io also handles inbound email under the same API (receiving messages at custom addresses, parsing attachments, and routing them to your application logic), so you don't run transactional and inbound email across two providers. When you're sending an auth code that expires in 5 minutes, it can't sit in a queue behind a 50,000-recipient newsletter send.

Many transactional email APIs support idempotency keys: a repeated OTP send request with the same key returns the original result instead of sending a duplicate email, which prevents accidental double-delivery when your application retries after a timeout. Check your provider's documentation, including send.io's, to confirm support and the key retention window before you rely on it.

3. Implement secure code verification

The verification endpoint checks the submitted code against the stored hash, enforces rate limits, and marks the token as used. Use the verifyOTPComplete function from the "End-to-end email OTP verification logic" section above.

The endpoint handler:

app.post('/api/verify-otp', async (req, res) => {
const { userId, code } = req.body;

if (!userId || !code || code.length !== 6) {
return res.status(400).json({ error: 'Invalid request' });
}

const result = await verifyOTPComplete(userId, code);

if (!result.success) {
if (result.reason === 'rate_limited') {
return res.status(429).json({
error: 'Too many attempts',
retryAfter: result.retryAfter
});
}
return res.status(401).json({ error: 'Invalid or expired code' });
}

const session = await createSession(userId);
res.json({ success: true, sessionToken: session.token });
});

Return the same error message for "code doesn't exist" and "code expired" to prevent timing attacks that enumerate valid vs. invalid user IDs or code states.

4. Prevent common security pitfalls

The most common email OTP vulnerabilities:

No rate limiting on the request endpoint: Attackers abuse the /api/request-otp endpoint to send unlimited messages, inflating your email costs and spamming users. Limit OTP requests to three per email address per hour.

Timing side-channels: If your verification endpoint responds faster for "user not found" than "invalid code," attackers can enumerate valid user IDs. Hash the submitted code and compare it against the stored hash in the database query. Return identical responses for "not found" and "expired" so response timing doesn't reveal which user IDs exist.

Codes in logs: Application logs that capture request bodies will log the plaintext OTP when users submit it. Sanitize logs to exclude the code field.

No cleanup job: Expired OTPs accumulate in the database. Run a periodic job to delete tokens where expires_at < NOW() - INTERVAL '24 hours'.

Predictable code generation: Using Math.random() or timestamp-based seeds makes codes predictable. Always use a cryptographic RNG.

Ready-to-use email OTP template samples

OTP emails need to work in low-bandwidth environments, render correctly across email clients, and make the code easy to transcribe. The templates below are tested and ready to adapt.

Lightweight OTP email code sample

Plain HTML template with inline CSS for maximum client compatibility:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 20px; font-family: Arial, sans-serif; background-color: #f4f4f4;">
<table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 8px;">
<tr>
<td style="padding: 40px 30px;">
<h1 style="margin: 0 0 20px 0; font-size: 24px; color: #333333;">Your verification code</h1>
<p style="margin: 0 0 30px 0; font-size: 16px; color: #666666; line-height: 24px;">
Enter this code to complete your sign in:
</p>
<div style="background-color: #f8f8f8; border: 2px solid #e0e0e0; border-radius: 6px; padding: 20px; text-align: center; margin: 0 0 30px 0;">
<span style="font-size: 36px; font-weight: bold; letter-spacing: 8px; color: #1a1a1a; font-family: 'Courier New', monospace;">
{{CODE}}
</span>
</div>
<p style="margin: 0 0 10px 0; font-size: 14px; color: #999999; line-height: 20px;">
This code expires in 10 minutes.
</p>
<p style="margin: 0; font-size: 14px; color: #999999; line-height: 20px;">
If you didn't request this code, you can safely ignore this email.
</p>
</td>
</tr>
</table>
</body>
</html>

Replace {{CODE}} with the actual OTP when sending. The monospace font and letter-spacing make the code easy to read and transcribe. The high-contrast border ensures the code block is visible even with images disabled.

Building OTP flows with React

React Email template for the same OTP flow:

import { Html, Body, Container, Text, Heading, Section } from '@react-email/components';

export default function OTPEmail({ code }) {
return (
<Html>
<Body style={{ backgroundColor: '#f4f4f4', padding: '20px' }}>
<Container style={{
backgroundColor: '#ffffff',
borderRadius: '8px',
padding: '40px 30px',
maxWidth: '600px'
}}>
<Heading style={{ fontSize: '24px', color: '#333', marginBottom: '20px' }}>
Your verification code
</Heading>
<Text style={{ fontSize: '16px', color: '#666', marginBottom: '30px' }}>
Enter this code to complete your sign in:
</Text>
<Section style={{
backgroundColor: '#f8f8f8',
border: '2px solid #e0e0e0',
borderRadius: '6px',
padding: '20px',
textAlign: 'center',
marginBottom: '30px'
}}>
<Text style={{
fontSize: '36px',
fontWeight: 'bold',
letterSpacing: '8px',
color: '#1a1a1a',
fontFamily: 'Courier New, monospace',
margin: 0
}}>
{code}
</Text>
</Section>
<Text style={{ fontSize: '14px', color: '#999', marginBottom: '10px' }}>
This code expires in 10 minutes.
</Text>
<Text style={{ fontSize: '14px', color: '#999' }}>
If you didn't request this code, you can safely ignore this email.
</Text>
</Container>
</Body>
</Html>
);
}

The React Email template uses the same visual design as the HTML version above. React Email renders components to plain HTML, so you can version templates alongside your application code and send the rendered output through the html field of any provider's API.

Design principles for OTP emails

Single-column layout: Multi-column layouts break on mobile clients. OTP emails should render correctly at 320px width.

Inline CSS: Many email clients strip <style> tags. Use inline styles for all formatting.

Large, monospace code display: Display the code at a large font size with letter-spacing for readability (the templates above render it at 36px). Monospace fonts prevent character ambiguity (0 vs O, 1 vs l).

No images in the critical path: The code itself should be text, not an image. Images can be blocked or slow to load, and screen readers can't parse them.

Plain-text fallback: Always include a text version of the email with just the code and expiry information for clients that don't render HTML.

HTTP API implementation for OTP flows

Most transactional email providers expose an HTTP API for sending. This section shows a generic HTTP POST structure that works across providers.

Constructing the POST request body

Standard transactional email APIs accept a JSON payload via POST. Here's the generic structure:

{
"from": "auth@yourapp.com",
"to": ["user@example.com"],
"subject": "Your verification code",
"html": "<p>Your code is: <strong>047392</strong></p>",
"text": "Your verification code is: 047392",
"headers": {
"X-Priority": "1",
"X-OTP-Purpose": "login"
}
}

Common optional fields:

  • reply_to: Where replies should go
  • tags: Array of strings for categorization
  • metadata: Key-value pairs for tracking
  • idempotency_key: Prevents duplicate sends on retry

The idempotency key pattern is common across providers. A retry with the same key returns the original message ID without sending a duplicate, but the retention window varies by provider, so confirm it in your provider's docs.

Preventing abuse in email verification workflows

Rate limiting must apply at three levels: per user, per IP, and per endpoint. Per-user limits stop brute-force attempts on one account, per-IP limits stop one source from hitting many accounts, and per-endpoint limits cap aggregate volume from distributed attacks.

User-level rate limiting and backoff

Limit failed verification attempts per user to prevent brute-force attacks on a specific account. OWASP recommends 5–10 unsuccessful attempts before lockout.

Use a fixed lockout, not a short exponential backoff. After 5 failed attempts, lock verification for that user for 15 minutes. A backoff that starts at 1 second and doubles only costs an attacker 16 seconds after five failures, so it doesn't slow brute force in any meaningful way. The checkUserRateLimit function below enforces the fixed lockout:

async function checkUserRateLimit(userId) {
const attempts = await db.query(`
SELECT COUNT(*) as count
FROM otp_verification_attempts
WHERE user_id = $1
AND attempted_at > NOW() - INTERVAL '15 minutes'
AND success = FALSE
`, [userId]);

const count = parseInt(attempts.rows[0].count);

if (count >= 5) {
const oldestAttempt = await db.query(`
SELECT attempted_at
FROM otp_verification_attempts
WHERE user_id = $1
AND success = FALSE
ORDER BY attempted_at ASC
LIMIT 1
`, [userId]);

const retryAfter = new Date(oldestAttempt.rows[0].attempted_at);
retryAfter.setMinutes(retryAfter.getMinutes() + 15);

return {
allowed: false,
retryAfter: Math.ceil((retryAfter - Date.now()) / 1000)
};
}

return { allowed: true };
}

A temporary lockout slows attackers without permanently locking out legitimate users. If you prefer escalating lockouts, start at a real floor such as 15 minutes and double it after each lockout. See OWASP's Authentication Cheat Sheet for account lockout guidance.

Limiting requests by IP address

IP-level rate limiting prevents attackers from hammering your OTP endpoint across multiple user accounts. Limit requests to 10 per IP per hour for the /api/request-otp endpoint:

const ipAttempts = new Map();

function checkIPRateLimit(ip) {
const now = Date.now();
const attempts = ipAttempts.get(ip) || [];

const recentAttempts = attempts.filter(time => now - time < 3600000);

if (recentAttempts.length >= 10) {
return { allowed: false, retryAfter: 3600 };
}

recentAttempts.push(now);
ipAttempts.set(ip, recentAttempts);

return { allowed: true };
}

In production, use Redis or Memcached instead of an in-memory Map so rate limits work across multiple application instances.

Capping total traffic per endpoint

Per-user and per-IP limits miss distributed attacks. A botnet that rotates through thousands of IP addresses and targets thousands of accounts stays under both thresholds while still flooding your email provider and inflating sending costs. A per-endpoint limit caps aggregate volume on /api/request-otp and /api/verify-otp regardless of who sends the traffic.

Set each cap from your measured baseline, for example a multiple of your peak legitimate request rate per minute, not a fixed industry number. The checkEndpointRateLimit function below uses a shared Redis counter with a fixed window:

// Requires a shared store such as Redis so the counter spans all application instances.
async function checkEndpointRateLimit(endpoint, limit, windowSeconds) {
const windowId = Math.floor(Date.now() / (windowSeconds * 1000));
const key = `ratelimit:endpoint:${endpoint}:${windowId}`;

const count = await redis.incr(key);
if (count === 1) {
await redis.expire(key, windowSeconds);
}

if (count > limit) {
return { allowed: false, retryAfter: windowSeconds };
}

return { allowed: true };
}

The trade-off: An endpoint-wide cap can block legitimate users during an attack, so treat it as a circuit breaker, not a primary control. A fixed window also permits a short burst at each window boundary. Pair the cap with an alert on rate-limit hits so you can investigate before legitimate sign-ins start failing.

Production readiness checklist for email OTP

Before deploying email OTP to production, verify each item below:

Token security:

  • OTP generation uses crypto.randomInt() or equivalent CSPRNG
  • Codes are 6–8 digits, generated fresh for each request
  • Plaintext codes exist only in memory during generation and in the user's inbox
  • OTPs are hashed with SHA-256 or bcrypt before storage
  • Each OTP has a unique id and includes user_id, expires_at, used, and purpose fields

Database protection:

  • No plaintext OTPs in database, logs, or error messages
  • The otp_tokens table has a composite index on user_id, created_at for rate limiting queries and a partial index on expires_at for cleanup. Don't put a unique index on token_hash, because two users can legitimately receive the same 6-digit code
  • Expired tokens are deleted by a cleanup job running at least daily
  • Database access to the otp_tokens table is restricted to the application service account
  • OTP verification attempts are logged to a separate otp_verification_attempts table for rate limiting

Replay and expiry:

  • Single-use enforcement via atomic UPDATE ... WHERE used = FALSE query
  • Expiry enforced at the database level with expires_at > NOW() in verification query
  • TTL for each flow type follows the guidance in "Understanding the email OTP authentication flow"
  • Old OTPs for the same user are invalidated when a new OTP is requested

Brute-force prevention:

  • Per-user rate limit: 5 failed attempts per 15 minutes
  • Per-IP rate limit: 10 OTP requests per hour
  • Fixed 15-minute lockout after 5 failed attempts for a user
  • CAPTCHA or proof-of-work challenge after 3 failed attempts from the same IP
  • Verification endpoint returns identical response times for "user not found" and "invalid code" to prevent user enumeration

Monitoring and debugging:

  • Log all verification attempts with user_id, attempted_at, success, and ip_address (but never log the submitted code)
  • Alert on rate limit violations (a sudden spike in rate-limited requests can indicate an attack)
  • Monitor OTP send success rate (a common target is above 99%, but tune it against your own delivery data)
  • Track time from OTP request to successful verification (a common starting point is a p95 under 60 seconds, which you should tune against your own delivery data)
  • Set up dead-letter queue for failed email sends so you can retry or investigate delivery failures

Test the OTP delivery flow in the send.io sandbox, where you can tag time-sensitive sends for priority so they queue ahead of bulk campaigns. The sandbox includes a test inbox, API access, and 100 emails per day until your first purchase, so you can validate the complete flow before committing to an integration.

FAQs

How long should an email OTP be valid?

Email OTPs should be valid for 2–5 minutes for second-factor flows, with 10 minutes as the upper limit, and 15–30 minutes for passwordless and verification-only flows. Shorter windows reduce brute-force exposure but risk expiring before slow email delivery, while longer windows improve usability but expand the attack surface.

What happens if a user requests multiple OTPs?

When a user requests a new OTP, invalidate all previous unused OTPs for that user and purpose. This prevents confusion (users might enter an old code) and reduces the number of valid codes an attacker can target.

Should you hash OTP codes before storing them?

Yes, hash OTPs with SHA-256 or bcrypt before storage. Hashing prevents accidental disclosure via logs or database inspection, though it doesn't provide strong offline attack resistance due to the small keyspace of 1 million combinations for a 6-digit code.

How can you prevent brute-force attacks on OTP verification?

Implement three layers: per-user rate limiting (5 failed attempts per 15 minutes, followed by a fixed 15-minute lockout), per-IP rate limiting (10 requests per hour), and per-endpoint rate limiting on the request and verify routes. Add CAPTCHA after 3 failed attempts from the same IP.

Can you resend the same OTP code?

No, generate a fresh code for each send request. Resending the same code means it remains valid longer than intended, and it complicates single-use enforcement. If the user didn't receive the first email, generate and send a new code with a new expiry window.

Key terms glossary

CSPRNG (Cryptographically Secure Pseudo-Random Number Generator): A random number generator that uses operating system entropy sources to produce unpredictable output. Required for OTP generation because predictable RNGs let attackers guess future codes based on observed outputs.

Email pumping: An attack where bots trigger massive volumes of automated email sends to inflate sending costs or spam recipients. Prevented with rate limiting, CAPTCHA, and anomaly detection on the OTP request endpoint.

Idempotency key: A unique identifier included in an API request that allows the server to recognize and safely handle retries without duplicating the operation. Prevents duplicate OTP sends when clients retry after network timeouts.

Rate limiting: Restricting the number of requests a user or IP address can make within a time window. Applied to OTP endpoints at three levels: per user, per IP, and per endpoint.

Single-use enforcement: Marking an OTP as used immediately after successful verification so the same code cannot grant access twice. Implemented via an atomic database update that checks used = FALSE and sets used = TRUE in one operation.

TTL (Time To Live): The duration an OTP remains valid after generation, typically 2–5 minutes for second-factor flows (10 minutes at most) and 15–30 minutes for passwordless and verification-only flows. Enforced by comparing the current time to the expires_at timestamp during verification.