Redis Expiration
Any key in Redis can be given a time to live (TTL). When the time is up, Redis deletes the key automatically. Expiration is what makes Redis such a good cache: you store a value, say how long it stays fresh, and never write clean-up code.
EXPIRE and TTL
EXPIRE key seconds sets a timeout on an existing key and returns 1 (or 0 if the key does not exist). TTL key returns the remaining seconds:
SET weather:hanoi "31C, sunny"
TTL weather:hanoi
EXPIRE weather:hanoi 600
TTL weather:hanoi
EXPIRE weather:lyon 600
TTL weather:lyonredis> SET weather:hanoi "31C, sunny"
OK
redis> TTL weather:hanoi
(integer) -1
redis> EXPIRE weather:hanoi 600
(integer) 1
redis> TTL weather:hanoi
(integer) 600
redis> EXPIRE weather:lyon 600
(integer) 0
redis> TTL weather:lyon
(integer) -2
TTL has two special replies that are easy to mix up:
| Reply | Meaning |
|---|---|
-1 |
the key exists but has no expiry |
-2 |
the key does not exist (or has already expired) |
0 or more |
seconds left |
PEXPIRE and PTTL do the same in milliseconds.
Setting the value and the expiry together
Calling SET and then EXPIRE takes two round trips, and if your program crashes in between, the key never expires. SET can do both at once with EX (seconds) or PX (milliseconds). SETEX is the older form of SET ... EX.
SET otp:5551234 "482913" EX 300
TTL otp:5551234
SETEX page:/home 60 "<html>...</html>"
TTL page:/home
SET counter:once 1 EX 90 NX
SET counter:once 2 EX 90 NX
GET counter:onceredis> SET otp:5551234 "482913" EX 300
OK
redis> TTL otp:5551234
(integer) 300
redis> SETEX page:/home 60 "<html>...</html>"
OK
redis> TTL page:/home
(integer) 60
redis> SET counter:once 1 EX 90 NX
OK
redis> SET counter:once 2 EX 90 NX
(nil)
redis> GET counter:once
"1"
Writing a value removes its expiry
This rule surprises many people: overwriting a key with SET (or GETSET, MSET ...) clears its TTL. Commands that change a value in place, such as INCR, APPEND, LPUSH or HSET, keep it. Use KEEPTTL when you want to overwrite but keep the timer:
SET banner "Sale!" EX 100
SET banner "Big sale!"
TTL banner
EXPIRE banner 100
SET banner "Huge sale!" KEEPTTL
TTL banner
INCR hits
EXPIRE hits 100
INCR hits
TTL hitsredis> SET banner "Sale!" EX 100
OK
redis> SET banner "Big sale!"
OK
redis> TTL banner
(integer) -1
redis> EXPIRE banner 100
(integer) 1
redis> SET banner "Huge sale!" KEEPTTL
OK
redis> TTL banner
(integer) 100
redis> INCR hits
(integer) 1
redis> EXPIRE hits 100
(integer) 1
redis> INCR hits
(integer) 2
redis> TTL hits
(integer) 100
PERSIST: removing a timeout
PERSIST turns a volatile key back into a permanent one:
SET draft "unsaved text" EX 30
PERSIST draft
TTL draft
PERSIST draftredis> SET draft "unsaved text" EX 30
OK
redis> PERSIST draft
(integer) 1
redis> TTL draft
(integer) -1
redis> PERSIST draft
(integer) 0
The second PERSIST returns 0 because there was no timeout left to remove.
Absolute expiry times
Instead of "in N seconds" you can give a Unix timestamp with EXPIREAT (seconds) or PEXPIREAT (milliseconds), or SET ... EXAT. EXPIRETIME returns the stored timestamp. A timestamp in the past deletes the key immediately:
SET promo:newyear "20% off"
EXPIREAT promo:newyear 1798761600
EXPIRETIME promo:newyear
SET old:promo "expired deal"
EXPIREAT old:promo 1000000000
EXISTS old:promo
EXPIRETIME old:promoredis> SET promo:newyear "20% off"
OK
redis> EXPIREAT promo:newyear 1798761600
(integer) 1
redis> EXPIRETIME promo:newyear
(integer) 1798761600
redis> SET old:promo "expired deal"
OK
redis> EXPIREAT old:promo 1000000000
(integer) 1
redis> EXISTS old:promo
(integer) 0
redis> EXPIRETIME old:promo
(integer) -2
1798761600 is 2027-01-01 00:00 UTC. Absolute times are useful when a value must disappear at a fixed moment, such as the end of a sale, regardless of when it was written.
Conditional expiry
EXPIRE accepts NX (only if no expiry yet), XX (only if there is one), GT (only if the new TTL is greater) and LT (only if smaller). GT is handy for "extend, but never shorten" logic:
SET session:abc "user 7"
EXPIRE session:abc 100 XX
EXPIRE session:abc 100 NX
EXPIRE session:abc 50 GT
EXPIRE session:abc 300 GT
TTL session:abcredis> SET session:abc "user 7"
OK
redis> EXPIRE session:abc 100 XX
(integer) 0
redis> EXPIRE session:abc 100 NX
(integer) 1
redis> EXPIRE session:abc 50 GT
(integer) 0
redis> EXPIRE session:abc 300 GT
(integer) 1
redis> TTL session:abc
(integer) 300
How Redis deletes expired keys
Redis combines two strategies:
- Lazy expiry: when a client touches a key, Redis first checks whether it has expired and deletes it if so. An expired key is never returned.
- Active expiry: a background job samples keys with a TTL several times per second and deletes the expired ones, so keys nobody reads are cleaned up too.
As a result, expired keys may occupy memory for a short while, but they are never visible to clients.
Tip: If thousands of cache keys are written at the same time with the same TTL, they also expire at the same time, and your database gets hit by all the misses at once. Add a small random jitter to TTLs in application code (for example 600 ± 60 seconds) to spread them out.
Test yourself
What does TTL return for a key that exists but has no expiry?
- 0
- -1
- -2
- (nil)
A key has a TTL of 100 seconds. You run SET key newvalue. What happens to the TTL?
- It stays 100
- It is reset to 100
- It is removed: the key becomes permanent
- The SET fails
Which command stores a value with a 60-second expiry in one step?
- SET key value EX 60
- SET key value TTL 60
- EXPIRE key value 60
- SETTTL key 60 value