Node Redis: Get Keys by TTL (Detailed Guide w/ Code Examples)

Use Case(s)

  • To retrieve all keys from a Redis database that have a specific Time to Live (TTL) value, particularly useful when working with data that requires time-bound invalidation.
  • When performing clean-up tasks in Redis, like deleting keys that are about to expire.

Code Examples

Unfortunately, there is no direct method in Redis to fetch keys based on their TTL. We can however achieve it by iterating over all the keys and checking their TTL.


const redis = require('redis'); const client = redis.createClient(); client.keys('*', (err, keys) => { keys.forEach(key => { client.ttl(key, (err, ttl) => { if(ttl === 'your_desired_ttl') { // Replace 'your_desired_ttl' with the desired TTL value console.log(key); } }); }); });

In this code, we first get all the keys using keys('*'). Then for each key, we get the TTL using ttl(key) function. If the TTL equals our desired TTL, we print out the key.

Best Practices

  • While the above approach works, it's not efficient on large databases as it iterates over all the keys. Consider redesigning your application so that you don't need to do this.
  • Avoid using KEYS command in production environment because it may affect performance. Instead, use SCAN command which is safer for production.

Common Mistakes

  • Trying to directly get keys by TTL. Redis does not support this natively.


Q: Can I get keys directly using their TTL in Redis?

A: No, Redis does not support getting keys directly based on their TTL. You have to iterate over keys and check TTL for each key.

Was this content helpful?

Start building today

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