0
0
Redisquery~5 mins

TTL-based expiry in Redis

Choose your learning style9 modes available
Introduction
TTL-based expiry helps automatically remove data after a set time, keeping your database clean and saving space.
You want to store temporary login tokens that expire after 10 minutes.
You need to cache website data that should refresh every hour.
You want to keep user session data only while the user is active.
You want to automatically delete old notifications after a day.
You want to limit how long a message stays in a chat app.
Syntax
Redis
EXPIRE key seconds
TTL key
PERSIST key
EXPIRE sets the time in seconds before the key is deleted.
TTL shows how many seconds remain before the key expires.
PERSIST removes the expiry from the key.
Examples
Set a key 'mykey' with value 'hello' that expires in 10 seconds.
Redis
SET mykey "hello"
EXPIRE mykey 10
Check how many seconds remain before 'mykey' expires.
Redis
TTL mykey
Remove the expiry from 'mykey' so it stays forever.
Redis
PERSIST mykey
Sample Program
Create a key 'session_token' that expires in 5 seconds, check TTL, then remove expiry and check TTL again.
Redis
SET session_token "abc123"
EXPIRE session_token 5
TTL session_token
PERSIST session_token
TTL session_token
OutputSuccess
Important Notes
TTL returns -1 if the key exists but has no expiry.
If the key does not exist, TTL returns -2.
Use PERSIST to cancel expiry if you want to keep the key longer.
Summary
TTL-based expiry automatically deletes keys after a set time.
Use EXPIRE to set the expiry time in seconds.
Use TTL to check remaining time and PERSIST to remove expiry.