Skip to main content
Redis Basics
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 EXPIRE command.
  • Check remaining time using the TTL command.
  • Use SETEX for 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. 1. First, set the data:
bash
123456789101112
   SET session:token_xyz "active"
   ```
2. Attach the time bomb (in seconds):
   ```bash
   EXPIRE session:token_xyz 60
   ```
*(Redis returns `1` to confirm the timer has started).*

If you wait 61 seconds and type `GET session:token_xyz`, Redis will return `(nil)`. The data was physically deleted from RAM without you doing anything!

### 4. The TTL Command (Time To Live)
How do you know how much time is left on the clock? You ask Redis for the **Time To Live (TTL)**.

bash TTL session:token_xyz

123456789
*(Returns an integer, e.g., `45`, meaning 45 seconds remaining).*

**Special TTL Return Values:**
- If it returns `-1`: The key exists, but it has NO expiration. It will live forever.
- If it returns `-2`: The key does not exist (it has already exploded or was never created).

### 5. Efficiency: SETEX
Running `SET` and then `EXPIRE` requires two separate trips to the database. Professional developers combine them into a single, highly-efficient command: **`SETEX`** (Set with Expiration).

bash SETEX authcode99 300 "847291"

1234
*(This instantly creates the key `auth_code_99` with the value `"847291"` and attaches a 300-second timer).*

### 6. Removing Expiration (PERSIST)
What if a user clicks a checkbox that says "Keep me logged in forever"? You need to disarm the time bomb.

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. 1. User requests the Homepage.
  1. 2. The application checks Redis: GET homepagecache.
  1. 3. If it exists, serve it instantly!
  1. 4. If it does NOT exist (it expired), the application runs a heavy 3-second MySQL query to build the homepage.
  1. 5. The application saves the new result in Redis for 10 minutes: SETEX homepagecache 600 "<html>..."
  1. 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. 1. User requests a login code.
  1. 2. The backend generates a random 6-digit number (123456).
  1. 3. The backend stores it in Redis, valid for exactly 5 minutes:
SETEX otp:user
55 300 "123456"
  1. 4. 6 minutes later, the user types 123456 into the website.
  1. 5. The backend checks Redis: GET otp:user55.
  1. 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. 1. What command instantly creates a String key, assigns a value, and attaches a lifespan in seconds simultaneously?
  1. 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 rate
limit: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.

17. Next Chapter Recommendation

We have stated repeatedly that if the server loses power, all data in RAM is destroyed. But what if we want the speed of RAM *and* the safety of a hard drive? In Chapter 9: Redis Persistence and Data Durability, we will learn how Redis magically saves memory to disk.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·