Introducing Dragonfly Cloud! Learn More

Get Keys By TTL in PHP Redis (Detailed Guide w/ Code Examples)

Use Case(s)

Often in applications, there is a need to retrieve keys from a Redis store based on their time-to-live (TTL). This is particularly useful in cases where the application needs to do some cleanup or processing on keys that are about to expire.

Code Examples

Unfortunately, as of my knowledge cutoff in September 2021, Redis does not support directly retrieving keys by their TTL values. However, you can iterate over all keys and get their TTLs. Below is an example using PHP and the predis library:

require 'vendor/autoload.php'; $client = new Predis\Client(); $keys = $client->keys('*'); foreach($keys as $key){ $ttl = $client->ttl($key); if($ttl != -1) { echo $key . ' has a TTL of ' . $ttl . " seconds.\n"; } }

In this code snippet, we're creating a new connection to the Redis server with Predis, then fetching all keys and iterating over them. For each key, we get its TTL and print it out only if it's not -1 (which signifies that the key does not expire).

Best Practices

  • Fetching all keys from a Redis instance (especially using KEYS command) can be resource-intensive, especially for large data sets. Use this operation sparingly, perhaps during less busy hours, and consider using SCAN instead for production systems.

  • If you frequently need to fetch keys by TTL, consider maintaining a separate Redis Sorted Set where the score of each entry is the expiry timestamp. This can allow more efficient fetching of keys by TTL.

Common Mistakes

  • One common mistake is not checking for a TTL of -1. This signifies that the key does not expire, and could lead to incorrect results if not properly handled.

  • Another mistake is using this method frequently or on production systems with large volumes of data. The KEYS command can be resource-intensive and should be used sparingly.


Q: Can I get keys by TTL directly in Redis?

A: No, as of my knowledge cutoff in September 2021, Redis does not support directly retrieving keys based on their TTL values. You can, however, iterate through each key and check its TTL individually.

Was this content helpful?

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.