Search code examples
pythonredisredis-py

Redis set ttl on key idempotently


I'm trying to use pipelines to process hundreds of thousands of keys being constantly added to a redis database.

Is there an idempotent method in Redis of setting the ttl if it does not exist on a key?


Solution

  • A Lua script would be the most potent approach - see EVAL's documentation for more details on how to compose such scripts, and refer to SCRIPT LOAD and EVALSHA for running them.

    Something like the following example should fix you up:

    if tonumber(redis.call('TTL', KEYS[1])) < 1 then
      redis.call('EXPIRE', KEYS[1], ARGV[1])
    end