Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

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.

CODE_BLOCK_PLACEHOLDER_0
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.

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

Best Practices

Common Mistakes

FAQs

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?

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