Dragonfly

Redis Update Value Without Changing TTL in Python (Detailed Guide w/ Code Examples)

Use Case(s)

Updating a value in Redis without altering its existing Time-To-Live (TTL) is often needed when the expiration policy is crucial. For example:

Code Examples

Example 1: Using getset to Update Value While Retaining TTL

import redis

# Connect to Redis
client = redis.StrictRedis(host='localhost', port=6379, db=0)

key = 'my_key'
new_value = 'new_value'

# Fetch current TTL
ttl = client.ttl(key)  # Returns -2 if the key does not exist, or -1 if it exists but has no associated expire

if ttl > 0:
    # Only update the value if the key exists and has an associated expire
    client.set(key, new_value, ex=ttl)
else:
    # If key does not have an expiration or does not exist, set the value without TTL
    client.set(key, new_value)

Explanation:

  1. Connect to the Redis server.
  2. Fetch the current TTL of the key.
  3. Check if the TTL is positive.
  4. Update the value while retaining the original TTL using the ex parameter.
  5. Handle cases where the key has no TTL or does not exist.

Example 2: Atomic Update with Lua Script

import redis

# Connect to Redis
client = redis.StrictRedis(host='localhost', port=6379, db=0)

key = 'my_key'
new_value = 'new_value'

# Lua script to update value and retain TTL
lua_script = """
local ttl = redis.call('ttl', KEYS[1])
if ttl > 0 then
    redis.call('set', KEYS[1], ARGV[1])
    redis.call('expire', KEYS[1], ttl)
else
    redis.call('set', KEYS[1], ARGV[1])
end
"""

# Execute Lua script
client.eval(lua_script, 1, key, new_value)

Explanation:

  1. Connect to the Redis server.
  2. Define a Lua script that:
  1. Execute the Lua script using client.eval.

Best Practices

Common Mistakes

FAQs

Q: What happens if the key does not exist?
A: The scripts and examples provided will handle this by either setting the key without TTL or doing nothing, depending on the specific implementation details.

Q: Can I use other methods to fetch TTL and update values?
A: Yes, you can use pipeline transactions to fetch and update values, though Lua scripting is generally preferred for atomicity and simplicity.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost