How to Set Timeout in Redis: Commands and Examples
In Redis, you set a timeout on a key using the
EXPIRE command to specify seconds before the key expires. Alternatively, use SET with the EX option to set a key with an expiration in one step. You can also use PEXPIRE to set timeout in milliseconds.Syntax
Redis provides several commands to set a timeout on keys:
EXPIRE key seconds: Sets expiration in seconds.PEXPIRE key milliseconds: Sets expiration in milliseconds.SET key value EX seconds: Sets key with value and expiration in seconds atomically.
These commands make the key automatically deleted after the timeout.
redis
EXPIRE mykey 60 PEXPIRE mykey 1500 SET mykey "value" EX 30
Example
This example shows how to set a key with a 10-second timeout using EXPIRE and how to set a key with expiration using SET with EX option.
redis
127.0.0.1:6379> SET session_token "abc123" OK 127.0.0.1:6379> EXPIRE session_token 10 (integer) 1 127.0.0.1:6379> TTL session_token (integer) 10 127.0.0.1:6379> SET cache_item "data" EX 5 OK 127.0.0.1:6379> TTL cache_item (integer) 5
Output
(integer) 1
(integer) 10
OK
(integer) 5
Common Pitfalls
Common mistakes when setting timeouts in Redis include:
- Using
EXPIREon a key that does not exist returns 0 and does not set timeout. - Setting expiration with
SETwithoutEXorPXoption does not set timeout. - Confusing seconds and milliseconds when using
EXPIREvsPEXPIRE.
redis
127.0.0.1:6379> EXPIRE missing_key 10 (integer) 0 # Correct way to set key and expiration together 127.0.0.1:6379> SET new_key "value" EX 10 OK
Output
(integer) 0
OK
Quick Reference
| Command | Description | Timeout Unit |
|---|---|---|
| EXPIRE key seconds | Set expiration time in seconds | Seconds |
| PEXPIRE key milliseconds | Set expiration time in milliseconds | Milliseconds |
| SET key value EX seconds | Set key with value and expiration in seconds | Seconds |
| TTL key | Get remaining time to live in seconds | Seconds |
| PTTL key | Get remaining time to live in milliseconds | Milliseconds |
Key Takeaways
Use EXPIRE to set timeout in seconds on existing keys.
Use SET with EX option to set key and timeout atomically.
PEXPIRE sets timeout in milliseconds for finer control.
Check TTL to see how much time is left before expiration.
EXPIRE returns 0 if the key does not exist, so ensure key exists first.