Skip to the workspace
Pebellslearn by building
Hashes  ›  Lesson

DEL, EXPIRE and TTL

expire 12 minDEL removes whole keys of any type, EXPIRE gives a key a lifetime in seconds, and TTL reports the seconds left, -1 for no expiry, or -2 for a missing key.

redis / DEL, EXPIRE and TTL

Explore each scene at your own pace.

01 · The rule

The rule

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) -2
  • DEL key [key ...] deletes keys and replies with how many actually existed. Above, only one of the two was there.
  • EXPIRE key seconds replies 1 when the lifetime was set and 0 when the key does not exist. When time runs out, Redis deletes the key by itself.
  • TTL key replies 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.