Authentication and SMS OTP routes are high-value targets for credential stuffing and billing abuse. Keeping rate-limit counters in Node.js process memory breaks as soon as traffic scales across multiple instances or a container restarts.
Key Takeaway: Execute fixed-window or sliding-window increments inside an atomic Redis Lua script so key expiration never leaks on worker crash, enforce separate IP and phone/email identity keys on OTP endpoints, and return standard HTTP 429 responses with
Retry-Afterheaders.
Separate IP limits from recipient identity limits
Relying solely on client IP either blocks legitimate users behind corporate or mobile carrier NATs or fails completely when an attacker rotates residential proxies against one victim's phone number.
On high-cost routes like Twilio SMS OTP verification, enforce two independent Redis keys before triggering an SMS send: a coarser IP window (for example, 20 requests per 15 minutes) and a tight per-recipient cooldown (for example, 3 OTP dispatches per 10 minutes normalized by E.164 phone number).
- Normalize email addresses and E.164 phone numbers before hashing or building the Redis key.
- Trust
X-Forwarded-Foronly after configuring Expressapp.set('trust proxy', 1)behind your load balancer. - Fail fast before database writes or external SMS/AI API calls execute.
Use atomic Redis Lua scripts so TTLs never leak
Sending INCR followed by EXPIRE as two separate network round-trips introduces a subtle race condition: if the Node.js process restarts between commands, the key persists indefinitely without a TTL and permanently locks out that user.
Running the increment and conditional PEXPIRE inside a single Redis Lua script guarantees atomicity in one round-trip and returns both the current request count and remaining TTL in milliseconds.
Atomic fixed-window counter with Redis Lua
// Atomic fixed-window counter with Redis Lua const luaScript = ` local current = redis.call("INCR", KEYS[1]) if current == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end local ttl = redis.call("PTTL", KEYS[1]) return { current, ttl } `; export async function consumeRateLimit(redis: Redis, key: string, windowMs: number, limit: number) { const [count, ttlMs] = (await redis.eval(luaScript, 1, key, String(windowMs))) as [number, number]; const retryAfterSec = Math.max(1, Math.ceil((ttlMs > 0 ? ttlMs : windowMs) / 1000)); return { allowed: count <= limit, remaining: Math.max(0, limit - count), retryAfterSec }; } Return explicit Retry-After headers and protect availability
When either limit trips, respond with HTTP 429 Too Many Requests alongside Retry-After (whole seconds rounded up from PTTL) and RateLimit-* headers. Frontend login and OTP screens can render an accurate resend countdown instead of hammering the endpoint.
Decide deliberately how middleware behaves if Redis is briefly unreachable: high-cost SMS/AI routes should fail closed or fall back to an emergency in-memory safety cap so a cache blip never turns into an unbounded Twilio bill.
Express middleware applying layered checks and HTTP 429 response headers
app.post("/api/auth/request-otp", async (req, res, next) => { const ipKey = `rl:otp:ip:${req.ip}`; const phoneKey = `rl:otp:phone:${normalizePhone(req.body.phone)}`; const [ipCheck, phoneCheck] = await Promise.all([ consumeRateLimit(redis, ipKey, 15 * 60_000, 20), consumeRateLimit(redis, phoneKey, 10 * 60_000, 3), ]); if (!ipCheck.allowed || !phoneCheck.allowed) { const retryAfter = Math.max(ipCheck.retryAfterSec, phoneCheck.retryAfterSec); res.setHeader("Retry-After", String(retryAfter)); return res.status(429).json({ error: "Too many OTP requests", retryAfter }); } return next(); }); Originally published on Deepak Chauhan's Engineering Notes.
Related reading: