Redis Key Expiration

Expiry of key

  • Set expiry In seconds
    • EX <seconds>
  • Set expiry In Milliseconds
    • PX <milliseconds>
  • Check Time To live in seconds
    • ttl <keyname>
  • Check Time To live in milliseconds
    • pttl <keyname>
  • -1 return from ttl says that key is never gonna expire
  • -2 return from ttl says that key does not exist
  • Explicity set an expiry for an key / Change an expiry of a existing key
    • expire <key> <seconds>
    • pexpire <key> <milliseconds>
  • Remove expiry
    • persist <keyname>

Setting Expiry in seconds

In Seconds

Setting Expiry in milliseconds

In milliseconds

Changing the expiry of thekey

Changing the expiry at runtime

Persisting an expiry of key

Persisting a key (Removing an expiry)

How does Redis Handle Key Expiration

There are two ways in which redis handles key expiration

  • Passive
    • When the key is called, it is checks/compared with the keys time to live to the current time
    • It the time is past time to expire then it removes the key from redis cache and returns -2 (-2 i.e key does not exist)
  • Active
    • Active key expiration runs 10 times per second
    • Redis test 20 random keys from the set of keys with an associated expiry
    • This deletes all the keys that are expired
    • If more than 25% keys are expired then it will start again from step 1

Leave a Comment