When writing data into Redis, there may be a point at which data is no longer needed. We can remove the data explicitly with DEL, or if we want to remove an entire key after a specified timeout, we can use what’s known as expiration. When we say that a key has a time to live, or that it’ll expire at a given time, we mean that Redis will automatically delete the key when its expiration time has arrived.
Having keys that will expire after a certain amount of time can be useful to handle the cleanup of cached data. If you look through other chapters, you won’t see the use of key expiration in Redis often (except in sections 6.2, 7.1, and 7.2). This is mostly due to the types of structures that are used; few of the commands we use offer the ability to set the expiration time of a key automatically. And with containers (LISTs, SETs, HASHes, and ZSETs), we can only expire entire keys, not individual items (this is also why we use ZSETs with timestamps in a few places).
In this section, we’ll cover commands that are used to expire and delete keys from Redis automatically after a specified timeout, or at a specified time. After reading this section, you’ll be able to use expiration as a way of keeping Redis memory use low, and for cleaning up data you no longer need.
Table 3.13 shows the list of commands that we use to set and check the expiration times of keys in Redis.
Command | Example use and description |
---|---|
PERSIST | PERSIST key-name — Removes the expiration from a key |
TTL | TTL key-name — Returns the amount of time remaining before a key will expire |
EXPIRE | EXPIRE key-name seconds — Sets the key to expire in the given number of seconds |
EXPIREAT | EXPIREAT key-name timestamp — Sets the expiration time as the given Unix timestamp |
PTTL | PTTL key-name — Returns the number of milliseconds before the key will expire (available in Redis 2.6 and later) |
PEXPIRE | PEXPIRE key-name milliseconds — Sets the key to expire in the given number of milliseconds (available in Redis 2.6 and later) |
PEXPIREAT | PEXPIREAT key-name timestamp-milliseconds — Sets the expiration time to be the given Unix timestamp specified in milliseconds (available in Redis 2.6 and later) |
You can see a few examples of using expiration times on keys in the next listing.
In sections 2.1, 2.2, and 2.5, we used a ZSET with timestamps to keep a listing of session IDs to clean up. By using this ZSET, we could optionally perform analytics over our items when we cleaned sessions out. But if we aren’t interested in analytics, we can instead get similar semantics with expiration, without needing a cleanup function. Can you update the update_token() and add_to_cart() functions to expire keys instead of using a “recent” ZSET and cleanup function?