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:
import redis # Connect to Redis r = redis.Redis(host='localhost', port=6379, db=0) # Add elements to the sorted set r.zadd('myzset', {'one': 1, 'two': 2}) # Set expiration of 10 seconds on the key r.expire('myzset', 10) # Verify the TTL ttl = r.ttl('myzset') print(f'Time to live: {ttl} seconds')
Node.js
Using the ioredis
library:
const Redis = require('ioredis'); const redis = new Redis(); async function run() { // Add elements to the sorted set await redis.zadd('myzset', 1, 'one', 2, 'two'); // Set expiration of 10 seconds on the key await redis.expire('myzset', 10); // Verify the TTL const ttl = await redis.ttl('myzset'); console.log(`Time to live: ${ttl} seconds`); } run().catch(console.error);
Golang
Using the go-redis
library:
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" "time" ) func main() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // Add elements to the sorted set rdb.ZAdd(ctx, "myzset", &redis.Z{Score: 1, Member: "one"}, &redis.Z{Score: 2, Member: "two"}) // Set expiration of 10 seconds on the key rdb.Expire(ctx, "myzset", 10*time.Second) // Verify the TTL ttl, err := rdb.TTL(ctx, "myzset").Result() if err != nil { panic(err) } fmt.Printf("Time to live: %v\n", ttl) }
Best Practices
- Use expiration settings to manage memory usage effectively, especially for cache-like structures.
- Monitor the TTL values to ensure that critical data does not expire unexpectedly.
- Combine
EXPIRE
with persistence mechanisms like RDB or AOF to avoid data loss on restarts.
Common Mistakes
- Setting an expiration on the wrong key or forgetting to set it altogether.
- Assuming that expired keys will be immediately removed; they are lazily deleted when accessed or by the Redis internal process.
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
- Redis Sorted Set: Get Highest Score
- Redis Sorted Set: Create
- Redis Sorted Set: Get by Key
- Redis Sorted Set: Limit Size
- Redis Sorted Set: Same Score
- Redis Sorted Set: Sorting by Multiple Fields
- Redis Sorted Set TTL
- Redis Sorted Set: Sort by Date
- Redis Sorted Set: Check Exists
- Redis Sorted Set: Remove by Score
- Redis Sorted Set: Rate Limit
- Redis Sorted Set: Custom Order
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