How to Use TTL in Redis: Set Expiry for Keys Easily
In Redis, you use the
EXPIRE command to set a TTL (time to live) on a key, which makes the key automatically delete after the specified seconds. You can check the remaining TTL with TTL and remove the expiration with PERSIST.Syntax
The main commands to work with TTL in Redis are:
EXPIRE key seconds: Sets the expiration time in seconds for the given key.TTL key: Returns the remaining time to live of a key in seconds.PERSIST key: Removes the expiration from the key, making it permanent.
redis
EXPIRE mykey 60
TTL mykey
PERSIST mykeyExample
This example shows how to set a key with a TTL, check its remaining time, and then remove the TTL to keep the key forever.
redis
SET mykey "Hello" EXPIRE mykey 10 TTL mykey PERSIST mykey TTL mykey
Output
OK
1
10
1
-1
Common Pitfalls
Common mistakes when using TTL in Redis include:
- Setting TTL on keys that do not exist, which returns 0 and does nothing.
- Expecting TTL to work with commands that overwrite keys without resetting TTL.
- Confusing
TTLoutput:-1means no expiration,-2means key does not exist.
redis
EXPIRE nonexistentkey 10 # returns 0 because key does not exist SET mykey "Hello" EXPIRE mykey 10 SET mykey "World" TTL mykey # TTL may be reset or lost depending on command used
Output
0
OK
1
-2
Quick Reference
| Command | Description |
|---|---|
| EXPIRE key seconds | Set expiration time in seconds on a key |
| TTL key | Get remaining time to live of a key in seconds |
| PERSIST key | Remove expiration from a key |
| SET key value EX seconds | Set key with value and expiration in one command |
| DEL key | Delete a key immediately |
Key Takeaways
Use EXPIRE to set a TTL in seconds on a Redis key to auto-delete it after time.
Check remaining TTL with TTL; -1 means no expiration, -2 means key missing.
Use PERSIST to remove TTL and keep the key permanently.
Setting TTL on a non-existing key does nothing and returns 0.
Some commands may reset or remove TTL when overwriting keys.