Introducing Dragonfly Cloud! Learn More

Redis Update TTL on Read in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

Updating the TTL (Time to Live) on a key every time it is read can be useful in scenarios like session management, where you want to extend the session timeout whenever the user interacts with the system. This helps keep active sessions alive while expiring inactive ones automatically.

Code Examples

Example 1: Basic TTL Update on Read

This example demonstrates how to update the TTL of a key each time it is read using the node-redis library.

const redis = require('redis'); const client = redis.createClient(); // Function to get key and update TTL async function getKeyAndUpdateTTL(key, ttl) { return new Promise((resolve, reject) => { client.get(key, (err, value) => { if (err) return reject(err); if (value === null) return resolve(null); // Update TTL client.expire(key, ttl, (expireErr) => { if (expireErr) return reject(expireErr); resolve(value); }); }); }); } // Usage example const key = 'session:user123'; const ttl = 3600; // 1 hour getKeyAndUpdateTTL(key, ttl) .then(value => { console.log(`Value: ${value}`); }) .catch(err => { console.error(`Error: ${err}`); });

In this example, whenever getKeyAndUpdateTTL is called, it retrieves the key's value and resets its TTL to 1 hour.

Example 2: Using Promises with Async/Await

For better readability and modern JavaScript practices, you can use async/await with promises.

const { promisify } = require('util'); const redis = require('redis'); const client = redis.createClient(); const getAsync = promisify(client.get).bind(client); const expireAsync = promisify(client.expire).bind(client); async function getKeyAndUpdateTTL(key, ttl) { try { const value = await getAsync(key); if (value !== null) { await expireAsync(key, ttl); } return value; } catch (err) { throw err; } } // Usage example (async () => { const key = 'session:user456'; const ttl = 1800; // 30 minutes try { const value = await getKeyAndUpdateTTL(key, ttl); console.log(`Value: ${value}`); } catch (err) { console.error(`Error: ${err}`); } })();

This version uses promisify to convert callback-based functions into promise-based ones, making the code cleaner and easier to follow.

Best Practices

  • Handle Errors Gracefully: Always include error handling to manage various failure scenarios, such as Redis server unavailability.
  • Use Appropriate TTL Values: Choose TTL values that make sense for your application to avoid keys expiring too soon or lingering unnecessarily long.
  • Minimize Redis Operations: Batch read and update operations together when possible to reduce the number of round trips to the Redis server, thus improving performance.

Common Mistakes

  • Ignoring Error Handling: Failing to handle errors from Redis commands can result in unexpected crashes or data inconsistencies.
  • Setting Inappropriate TTLs: Setting TTLs that are too short might lead to keys expiring before they are accessed again, while TTLs that are too long might keep unused keys around unnecessarily.
  • Not Checking Key Existence: Always check if the key exists before attempting to update its TTL to avoid unnecessary operations.


Q: Can I update TTL without reading the value? A: Yes, you can directly use the EXPIRE command if you only need to reset the TTL without fetching the value.

Q: What happens if the key does not exist? A: If the key does not exist, the EXPIRE command will do nothing, ensuring no new key is created inadvertently.

Q: Is there a performance impact when updating TTL frequently? A: Frequent TTL updates can increase the load on your Redis server, so it's important to balance TTL updates with overall system performance requirements.

Was this content helpful?

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.