'How to set expire timeout for redis set key only for the first key save?

I have case where i need to save values to redis SET structure under given key so i am using command from my code in the loop

    SADD key value
    EXPIRE KEY 100

However, i would like to set expiration time only on first save of the set key. Is it possible to set expire time only at the moment of first set key creation ? it is also should be noted that i can use EXISTS key call to redis to check if key exist and depending on that set expiration time or not - but this operation is not atomic.



Solution 1:[1]

To answer the question - no, there isn't such a command.

As you noted, this could be worked around with EXISTS. To address the atomicity (and save on network) requirement you can use a Lua script (see EVAL).

Solution 2:[2]

Redis 7.0 has a new option "NX -- Set expiry only when the key has no expiry". So, you could solve the problem with EXPIRE KEY 100 NX.

However, that it doesn't matter if you call EXPIRE KEY 100 1 or, let's say, 5 times. The key will expire after 100 seconds, thus checking EXISTS key is also an option.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Itamar Haber
Solution 2 user3270865