Dragonfly

Redis Sorted Set: Expire Key (Detailed Guide w/ Code Examples)

Use Case(s)

Setting an expiration time for keys in Redis is crucial for managing memory efficiently and ensuring that outdated data is automatically removed. This is particularly useful in scenarios such as caching, session management, and implementing TTL (Time-To-Live) features for dynamic content.

Code Examples

To set an expiration for a key in a Redis sorted set, you typically use the EXPIRE or PEXPIRE command. Below are examples in Python, Node.js, and Golang:

Python

Using the redis-py library:
CODE_BLOCK_PLACEHOLDER_0

Node.js

Using the ioredis library:
CODE_BLOCK_PLACEHOLDER_1

Golang

Using the go-redis library:
CODE_BLOCK_PLACEHOLDER_2

Best Practices

Common Mistakes

FAQs

Q: Can I update the expiration time of a key?
A: Yes, calling EXPIRE again on the same key updates its expiration time.

Q: What happens when a key expires?
A: The key will be automatically deleted from the database once it reaches its expiration time.

Q: Is there a way to persistently store expired keys?
A: By default, expired keys are removed and not stored. However, you can use events to log or take action when keys expire.

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