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.