Dragonfly Cloud is now available in the AWS Marketplace - learn more

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:

  • Caching frequently updated data while maintaining the original expiration time.
  • Updating session data where each user's session has a fixed expiration time.

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:
    • Retrieves the current TTL of the key.
    • Sets the new value.
    • Re-applies the original TTL if it was positive.
  3. Execute the Lua script using client.eval.

Best Practices

  • Always check for the existence of a key and its TTL before updating to avoid unintended behavior.
  • Use Lua scripts for atomic operations to prevent race conditions, especially in a multi-client environment.

Common Mistakes

  • Forgetting to handle keys that do not exist or have no TTL, leading to unexpected results.
  • Overwriting the key without preserving its original TTL due to logic errors.

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?

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