Traveling Tech Guy Traveling Tech Guy - 1 year ago 138
Node.js Question

How to get the TTL of multiple Redis keys from Node

I'm trying to show a view of all keys that look like 'myprefix:*' and their TTL.
I can then allow an admin to either expire a key, or 'touch it' (i.e. add an hour to the expiration).

I can use

redisClient.keys('myprefix:*', (err, keys) => {})
to get my keys, but the
command only accepts a single key, not an array. I don't want to iterate over the array and send n

I know I can probably use
to send a transaction of
commands, but I'm wondering if there's a better way (in JavaScript - not shell) to get all the keys and their TTL in one/two commands?

Answer Source

Finally resorted to using multi. I do understand both using keys and multi is highly not recommended in production. But the number of keys I'm handling right now is quite small (less than 10).

Using keys + multi to get the ttl of N keys results in 2 network trips, rather than N+1.

As it grows, I'll reevaluate the solution. I posted my code below if anyone ever needs it:

let getKeys = prefix => {
    return new Promise((resolve, reject) => {
      redisClient.keys(`${prefix}:*`), (err, keys) => {
        if(err) {
        else {
          let multi = redisClient.multi();
          keys.forEach(k => multi.ttl(k));
          multi.exec((err2, ttls) => {
            if(err2) {
            else {
              let result =, i) => ({key: k.replace(`${prefix}:`, ''), ttl: ttls[i]}));

This yields an array:

[ { key: '05460a69f7c0d313b7edfcca4f267cee', ttl: 3034 },
  { key: 'b1065bfa82408a10e2d2d0a50df1eef9', ttl: 3031 },
  { key: 'c3aeced2ef08f1c728f0b367c50a962a', ttl: 3019 } ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download