How to Return a Key’s Value and Set its Expiry in a Single Operation in Redis

In Redis, typically when we want to return a key’s value, we use the GET command. But there’s also a GETEX command (introduced in Redis 6.2.0) that allows us to get the value and return it’s expiry at the same time.

Example

Suppose we set the following key without an expiry:

SET color "Blue"

Result:

OK

Let’s check its time to live:

TTL color

Result:

(integer) -1

This result means that the key exists but it has no associated expiry.

Now let’s use the GETEX command to return the value and set an expiry for the key:

GETEX color EX 3600

Result:

"Blue"

It returns the value from the key and sets its timeout.

Let’s check the current time to live again:

TTL color

Result:

(integer) 3556

This time we get an integer reply with the current time to live. This value has reduced from the timeout that we set, because it’s constantly reducing until it expires. Therefore, if we wait a little, then run the command again, we get a smaller timeout:

TTL color

Result:

(integer) 3471

Remove the Timeout

We can remove the timeout by using the PERSIST option:

GETEX color PERSIST

Result:

"Blue"

This example returns the value from the key and removes its timeout.

Let’s check the current time to live again:

TTL color

Result:

(integer) -1

Once again it returns an integer reply of -1, which means that the key has no expiry.

Other Timeout Options

We can alternatively use PX to set the expiry in milliseconds, EXAT to specify a Unix time in seconds, or PXAT to specify a Unix time in milliseconds.