Introducing Dragonfly Cloud! Learn More

Redis Sorted Set TTL (Detailed Guide w/ Code Examples)

Use Case(s)

  • Expiring temporary leaderboard entries after a certain time.
  • Automatically removing outdated data from sorted sets.

Code Examples

To add an element to a sorted set with an expiration time (TTL):

Python

import redis import time client = redis.StrictRedis(host='localhost', port=6379, db=0) # Add an element to the sorted set client.zadd('myset', {'element': 1}) # Set TTL for the sorted set client.expire('myset', 60) # Expires in 60 seconds # Example to verify the TTL ttl = client.ttl('myset') print(f"TTL of myset: {ttl} seconds")

Node.js

const redis = require('redis'); const client = redis.createClient(); client.on('connect', () => { console.log('Connected to Redis...'); // Add an element to the sorted set client.zadd('myset', 1, 'element', (err, res) => { if (err) throw err; // Set TTL for the sorted set client.expire('myset', 60, (err, res) => { if (err) throw err; // Get TTL of the sorted set client.ttl('myset', (err, ttl) => { if (err) throw err; console.log(`TTL of myset: ${ttl} seconds`); client.quit(); }); }); }); });

Golang

package main import ( "fmt" "time" "github.com/go-redis/redis/v8" "golang.org/x/net/context" ) func main() { ctx := context.Background() client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // Add an element to the sorted set client.ZAdd(ctx, "myset", &redis.Z{ Score: 1, Member: "element", }) // Set TTL for the sorted set client.Expire(ctx, "myset", 60*time.Second) // Example to verify the TTL ttl, _ := client.TTL(ctx, "myset").Result() fmt.Printf("TTL of myset: %v\n", ttl) }

Best Practices

  • Ensure that the TTL is sufficient to meet your application's requirements before setting it.
  • Monitor TTL values to avoid unexpected deletions in critical systems.

Common Mistakes

  • Forgetting to use the same key name when setting the TTL as used in adding elements.
  • Assuming TTL applies to individual elements within the sorted set rather than the sorted set itself.

FAQs

Q: Can I set a TTL on individual elements within a sorted set? A: No, Redis does not support setting TTLs on individual elements within a sorted set, only on the entire set.

Was this content helpful?

Start building today 

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