CHAPTER 08
Intermediate
Redis TTL Tutorial | EXPIRE and Cache Management
Updated: May 16, 2026
15 min read
# CHAPTER 8
Expiration, TTL, and Cache Management
1. Introduction
RAM is incredibly expensive. If you use Redis to cache the results of thousands of database queries, your server's memory will eventually reach 100%, and the system will crash. To prevent this, data in Redis should almost never live forever. It must be ephemeral. In this chapter, we will learn the most powerful feature of caching architectures: Expiration. We will learn how to attach a ticking time bomb to our data, ensuring it automatically self-destructs to free up memory.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the concept of Cache Invalidation.
-
Set expiration timers using the
EXPIREcommand.
-
Check remaining time using the
TTLcommand.
-
Use
SETEXfor single-step insertion and expiration.
- Architect automated One-Time Password (OTP) systems.
3. The EXPIRE Command
Let's store a user's session token. We want it to be valid for exactly 60 seconds. If they don't use it, it should vanish.- 1. First, set the data:
bash
bash TTL session:token_xyz
bash SETEX authcode99 300 "847291"
bash
PERSIST session:tokenxyz
``
*(Returns 1. The key is now permanently saved in RAM. If you run TTL, it will return -1).*
7. Real-World Use Case: The Cache Pattern
This is the core loop of every major website on Earth:- 1. User requests the Homepage.
-
2.
The application checks Redis: GET homepagecache
.
- 3. If it exists, serve it instantly!
- 4. If it does NOT exist (it expired), the application runs a heavy 3-second MySQL query to build the homepage.
-
5.
The application saves the new result in Redis for 10 minutes: SETEX homepagecache 600 "<html>..."
- 6. For the next 10 minutes, the MySQL database is completely shielded from traffic.
8. Mini Project: The OTP System
Scenario: Building an SMS Two-Factor Authentication (2FA) system.- 1. User requests a login code.
-
2.
The backend generates a random 6-digit number (123456
).
- 3. The backend stores it in Redis, valid for exactly 5 minutes:
-
4.
6 minutes later, the user types
123456 into the website.
-
5.
The backend checks Redis:
GET otp:user55.
-
6.
Redis returns
(nil). The backend rejects the login attempt. Security enforced!
9. Common Mistakes
-
Overwriting without Re-Expiring: If you set a key with an expiration (
SETEX mykey 60 "A"), and then 30 seconds later you update the value using the basic SET command (SET mykey "B"), the expiration timer is instantly destroyed! The key will now live forever. If you update a key, you must explicitly pass the EX parameter again: SET mykey "B" EX 60.
10. Best Practices
-
Eviction Policies (maxmemory): Even with expiration, your server might run out of RAM if traffic spikes. You must configure the
maxmemory-policy in your redis.conf file. Set it to allkeys-lru (Least Recently Used). If RAM hits 100%, Redis will automatically survive by deleting the oldest, least-accessed keys to make room for new data.
11. Exercises
-
1.
What command instantly creates a String key, assigns a value, and attaches a lifespan in seconds simultaneously?
-
2.
If you run the
TTL command on a key and it returns -2, what does this mathematically signify?
12. Redis Challenges
You are building an API Rate Limiter. Users are only allowed to make 10 requests per minute. You use the command INCR ratelimit:user1 every time they make a request. How do you utilize Expiration to ensure the counter automatically resets to zero at the end of the minute?
*(Answer: The very first time the user makes a request, you run INCR ratelimit:user1 followed immediately by EXPIRE ratelimit:user_1 60. Redis will automatically delete the counter after 60 seconds, perfectly resetting their rate limit for the next minute).*
13. MCQ Quiz with Answers
Question 1
When architecting an automated SMS One-Time Password (OTP) system, what is the primary security advantage of utilizing the Redis SETEX command over a standard relational database?
Question 2
A developer executes the TTL command on a specific key in the redis-cli and receives a return value of -1. What does this specific return code explicitly indicate about the state of the data?
14. Interview Questions
-
Q: Explain the concept of "Cache Invalidation". How does attaching a TTL to cached MySQL query results prevent an application from serving stale, outdated information to users?
-
Q: Discuss the architectural danger of updating an existing key using the standard
SET command when that key previously possessed an expiration timer.
15. FAQs
Q: Can I set an expiration timer in milliseconds instead of seconds?
A: Yes! For extreme high-frequency trading or gaming architectures, you can use the PEXPIRE command, which accepts the timer in milliseconds.
16. Summary
You are now a master of memory management. By leveraging EXPIRE, TTL`, and automated eviction policies, you ensure your Redis server acts as a self-cleaning, highly efficient cache that never crashes from memory bloat.