DEL, EXPIRE and TTL
Wordcraft caches each profile as a hash, cache:profile:asha, so the slow database query runs rarely. But a cache that never forgets serves stale data forever, and one that nobody cleans fills memory. Every key in Redis, whatever its type, can be deleted on demand or given a lifetime.
The rule
DEL removes now, EXPIRE removes later, TTL tells you when.
These commands work on whole keys of any type: strings, hashes, lists, sets and sorted sets alike.
127.0.0.1:6379> HSET cache:profile:asha name Asha level 7
(integer) 2
127.0.0.1:6379> EXPIRE cache:profile:asha 60
(integer) 1
127.0.0.1:6379> TTL cache:profile:asha
(integer) 60
127.0.0.1:6379> TTL player:asha
(integer) -1
127.0.0.1:6379> DEL cache:profile:asha cache:profile:ghost
(integer) 1
127.0.0.1:6379> TTL cache:profile:asha
(integer) -2DEL key [key ...]deletes keys and replies with how many actually existed. Above, only one of the two was there.EXPIRE key secondsreplies1when the lifetime was set and0when the key does not exist. When time runs out, Redis deletes the key by itself.TTL keyreplies with the seconds left, or one of two special values:
| TTL reply | Meaning |
|---|---|
| a positive number | seconds until the key is deleted |
-1 |
the key exists and has no expiry |
-2 |
the key does not exist |
PERSIST key removes an expiry, turning the key back into a permanent one. PEXPIRE and PTTL do the same jobs in milliseconds.
What keeps and what clears a lifetime. Changing a value in place (HSET, INCR, APPEND, LPUSH) keeps the expiry. Replacing the key with a plain SET clears it, unless you add EX or KEEPTTL.
The shortcut
Read a TTL reply by its sign: positive is a countdown, -1 is forever, -2 is gone.
Create it
SET session:9f2c asha EX 1800makes a key that lives 30 minutes.
Two more details are worth knowing. EXPIRE with zero or a negative number deletes the key straight away. And EXISTS key [key ...] replies with how many of the named keys exist, which is a quick way to check before you act. For very large keys, UNLINK does the same job as DEL but frees the memory in the background.
Drills
Answer fast — trust the rule.
player:asha exists; player:zoe does not. What does DEL player:asha player:zoe reply?
TTL leaderboard replies -1. What does that mean?
What does EXPIRE cache:profile:zoe 60 reply when that key does not exist?
word:today has 500 seconds to live. You run SET word:today comet. What does TTL word:today reply now?
A hash has 60 seconds to live and you run HSET on one of its fields. What happens to the expiry?
Remember
- DEL removes now, EXPIRE removes later, TTL tells you when.
- Positive is a countdown, -1 is forever, -2 is gone.
- In-place changes keep an expiry; a plain SET wipes it.
