How to Set Expiration on Key in Redis: Simple Guide
To set expiration on a key in Redis, use the
EXPIRE command followed by the key name and the time in seconds. This makes the key automatically delete after the specified time. You can also use SET with the EX option to set a key with expiration in one step.Syntax
The main command to set expiration on a key is EXPIRE key seconds. Here, key is the name of the key, and seconds is how long Redis keeps the key before deleting it automatically.
You can also set expiration when creating a key using SET key value EX seconds, which sets the key and expiration together.
redis
EXPIRE mykey 60 SET mykey "hello" EX 60
Example
This example shows how to set a key with a value and then set it to expire after 10 seconds. After 10 seconds, the key will no longer exist.
redis
SET session_token "abc123" EXPIRE session_token 10 TTL session_token
Output
(integer) 10
Common Pitfalls
- Setting expiration on a key that does not exist returns 0 and does nothing.
- Using
EXPIREwith a negative or zero time deletes the key immediately. - For persistent keys, remember expiration is in seconds, not milliseconds (use
PEXPIREfor milliseconds).
redis
EXPIRE missing_key 10 # returns 0 because key does not exist EXPIRE mykey 0 # deletes mykey immediately
Quick Reference
| Command | Description |
|---|---|
| EXPIRE key seconds | Set expiration time in seconds on an existing key |
| PEXPIRE key milliseconds | Set expiration time in milliseconds on an existing key |
| SET key value EX seconds | Set key with value and expiration in seconds |
| TTL key | Check remaining time to live of a key in seconds |
| PERSIST key | Remove expiration from a key |
Key Takeaways
Use EXPIRE to set expiration time in seconds on existing keys.
Use SET with EX option to set key and expiration together.
Expiration time is in seconds; use PEXPIRE for milliseconds.
EXPIRE returns 0 if the key does not exist.
Use TTL to check how much time is left before a key expires.