惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
博客园 - 【当耐特】
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
D
Docker
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
云风的 BLOG
云风的 BLOG
F
Fortinet All Blogs
罗磊的独立博客
小众软件
小众软件
A
About on SuperTechFans
MyScale Blog
MyScale Blog
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
C
Check Point Blog
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
I Built an OTP System with Redis… Then Realized TTL Wasn’...
Deval Ujeniy · 2026-05-20 · via DEV Community

I thought this would be a simple backend task.

Generate OTP → Store in Redis → Add expiration → Verify user.

Done.

My first implementation looked like this:

await redis.set(
  otpKey(phone),
  otp,
  "EX",
  60
);

Enter fullscreen mode Exit fullscreen mode

OTP expires after 60 seconds.

Looks perfect.

Until I asked myself:

What actually stops someone from guessing forever?

Nothing 😭

Someone could still keep trying:

123456
111111
999999
000000
654321
222222

Enter fullscreen mode Exit fullscreen mode

The OTP expires.

Brute force attempts do not.

That was the moment I realized:

TTL solves expiration.
TTL does NOT solve security.


Version 1: Store Only OTP

Initially Redis stored only:

"123456"

Enter fullscreen mode Exit fullscreen mode

Simple.

But there was no information about:

  • Failed attempts
  • Blocking state
  • Verification behavior
  • Security tracking

So I changed the design.

Instead of storing only the OTP:

{
  "otp": "123456",
  "attempts": 0,
  "maxAttempts": 3,
  "blockedUntil": null
}

Enter fullscreen mode Exit fullscreen mode

Redis stopped feeling like cache.

It started acting like a lightweight state engine.


Adding Brute Force Protection

Wrong OTP?

Increase attempts:

otpData.attempts++;

Enter fullscreen mode Exit fullscreen mode

After 3 failures:

otpData.blockedUntil =
Date.now() + 60000;

Enter fullscreen mode Exit fullscreen mode

Users are blocked for 60 seconds.

Problem solved.

Or at least…

That’s what I thought 😭


The Redis Bug I Didn’t Expect

When verification failed I updated Redis:

await redis.set(
   otpKey(phone),
   JSON.stringify(
      otpData
   ),
   "EX",
   60
);

Enter fullscreen mode Exit fullscreen mode

Looks harmless.

But there was a hidden problem.

Imagine this:

  • OTP created
  • TTL = 60 sec
  • User fails at second 55
  • Redis updates state
  • TTL becomes 60 again

The OTP suddenly lives longer.

I accidentally extended authentication lifetime after every failed attempt.

Not ideal.


The Fix

Before updating Redis:

const ttl =
await redis.ttl(
   otpKey(phone)
);

Enter fullscreen mode Exit fullscreen mode

Reuse remaining TTL:

await redis.set(
   otpKey(phone),
   JSON.stringify(
      otpData
   ),
   "EX",
   ttl
);

Enter fullscreen mode Exit fullscreen mode

Now:

  • OTP created → 60 sec
  • User fails at second 55
  • Remaining TTL = 5
  • Redis update keeps TTL = 5

Expiration stays correct ✅


Biggest Lesson From This Project

I started with:

Redis = Cache

Enter fullscreen mode Exit fullscreen mode

I finished with:

Redis = State Engine

Enter fullscreen mode Exit fullscreen mode

TTL → Expiration

Attempts → Security

Blocking → Authentication logic

Redis became part of application behavior.

That was the biggest lesson.


Things I Want To Improve Next

1. Rate limiting per IP

Prevent OTP spam.

2. Redis Hashes

Avoid rewriting entire JSON objects.

3. Atomic updates

Current flow:

GET
↓
Modify
↓
SET

Enter fullscreen mode Exit fullscreen mode

Possible improvements:

  • Transactions
  • WATCH / MULTI
  • Lua scripts

4. Handle race conditions

Two verification requests arriving together could create inconsistent state.

5. Add resend cooldown

Send OTP
↓
Wait 30 sec
↓
Allow resend

Enter fullscreen mode Exit fullscreen mode


Final Thought

I started building:

OTP + Redis + TTL

I ended up learning:

  • Authentication design
  • State management
  • Expiration handling
  • Brute-force protection
  • Backend security

Small project.

Big Redis lesson.

Day 2 of learning Redis 🚀

If you’ve built OTP systems before:

Would you keep state in Redis?

Or move some logic elsewhere?