You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
One of Redis's most powerful features is the ability to attach an expiry to any key. When the expiry time elapses, Redis automatically deletes the key. This is essential for session management, rate limiting, one-time tokens, and caching strategies.
You can attach a time-to-live when setting a string:
# EX — seconds
127.0.0.1:6379> SET session:abc123 "user_id:42" EX 3600
OK
# PX — milliseconds
127.0.0.1:6379> SET otp:+447700900000 "819234" PX 300000
OK
# EXAT — Unix timestamp in seconds
127.0.0.1:6379> SET promo:summer "SAVE20" EXAT 1893456000
OK
Attach expiry to an existing key:
127.0.0.1:6379> SET api_cache "cached response"
OK
127.0.0.1:6379> EXPIRE api_cache 600
(integer) 1 # 1 = expiry was set successfully
# Set expiry as an absolute Unix timestamp
127.0.0.1:6379> EXPIREAT api_cache 1893456000
(integer) 1
Inspect remaining time-to-live:
127.0.0.1:6379> TTL session:abc123
(integer) 3541 # seconds remaining
127.0.0.1:6379> PTTL session:abc123
(integer) 3541234 # milliseconds remaining
TTL returns -1 if the key exists but has no expiry, and -2 if the key does not exist at all.
Remove the expiry from a key, making it persist indefinitely:
127.0.0.1:6379> PERSIST session:abc123
(integer) 1
127.0.0.1:6379> TTL session:abc123
(integer) -1
Redis uses a combination of two strategies to expire keys:
Lazy expiry — when a key is accessed, Redis checks whether it has expired. If so, it is deleted before returning the result.
Active expiry — every 100 ms, Redis samples a random set of keys with expiries and deletes any that have expired. This prevents unbounded memory growth from keys that are never accessed.
# Rate limiting: allow 100 requests per minute per IP
127.0.0.1:6379> INCR rate:192.168.1.1
(integer) 1
127.0.0.1:6379> EXPIRE rate:192.168.1.1 60
(integer) 1
# Cache-aside: store computed value for 5 minutes
127.0.0.1:6379> SET cache:product:99 "{...}" EX 300
OK
Understanding expiry is fundamental to using Redis as both a cache and a primary data store — it lets you control memory usage and data freshness automatically.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.