Video in progress

What is TTL, and how do you give a Redis key a lifetime?

TTL is the time left until the key is removed automatically. You set it at write time with SET key value EX 300, or later with EXPIRE key 300, and TTL key shows the remaining time.

📖 Answer

SET otp:998901234567 4821 EX 120   # 2 minutes
TTL otp:998901234567               # 117
PERSIST otp:998901234567           # removes the expiry

Don't mix up the TTL replies: a positive number is the seconds left, -1 means the key exists but has no expiry, and -2 means the key doesn't exist at all.

In Spring Data Redis:

redis.opsForValue().set("otp:" + phone, code, Duration.ofMinutes(2));

One trap: a plain SET (without EX) that overwrites an existing key wipes out its TTL. If you forget to set the expiry again when refreshing a cached value, the key stays forever.