Sorted Sets
Leaderboards, rate limiting, and range queries
Skills taught: redis.sorted-sets
Sorted Set Fundamentals
Sorted Sets store unique members, each with a floating-point score. Members are always returned in score order. They combine a hash table (O(1) score lookup) with a skip list (O(log N) range queries).
# Add members with scores
ZADD scores 1500 "alice" 2000 "bob" 1800 "carol"
# Update score (ZADD is upsert)
ZADD scores 2200 "alice" # alice now has 2200
# Get score of a member
ZSCORE scores "alice" # "2200"
# Rank (0-indexed, lowest score = rank 0)
ZRANK scores "alice" # 1 (second lowest)
ZREVRANK scores "alice" # 1 (second highest)
# Range by rank (ascending)
ZRANGE scores 0 2 WITHSCORES # bottom 3
ZRANGE scores 0 2 WITHSCORES REV # top 3 (descending)
# Range by score
ZRANGEBYSCORE scores 1700 2500 # between 1700 and 2500
ZRANGEBYSCORE scores -inf +inf # all members
# Count members in score range
ZCOUNT scores 1700 2500 # count in range
# Remove members
ZREM scores "carol" # remove one
ZREMRANGEBYRANK scores 0 1 # remove bottom 2
Building a Real-Time Leaderboard
// Add or update a player's score
async function addScore(playerId, points) {
await redis.zIncrBy('leaderboard:global', points, playerId);
}
// Get top N players
async function getTopPlayers(n) {
// ZRANGE with REV returns highest scores first
const result = await redis.zRangeWithScores('leaderboard:global', 0, n - 1, { REV: true });
return result.map((entry, i) => ({
rank: i + 1,
playerId: entry.value,
score: entry.score,
}));
}
// Get a player's rank and score
async function getPlayerStats(playerId) {
const [rank, score] = await Promise.all([
redis.zRevRank('leaderboard:global', playerId), // 0-indexed from top
redis.zScore('leaderboard:global', playerId),
]);
return { rank: rank + 1, score };
}
// Get players around a rank
async function getNeighbours(playerId, range = 5) {
const rank = await redis.zRevRank('leaderboard:global', playerId);
const start = Math.max(0, rank - range);
const end = rank + range;
return redis.zRangeWithScores('leaderboard:global', start, end, { REV: true });
}
Sliding-Window Rate Limiter
Sorted Sets implement a precise sliding-window rate limiter by storing request timestamps as scores. Only requests within the last N seconds count.
async function isRateLimited(userId, limit = 100, windowMs = 60000) {
const now = Date.now();
const windowStart = now - windowMs;
const key = `rate:${userId}`;
const pipeline = redis.pipeline();
// 1. Remove requests outside the window
pipeline.zRemRangeByScore(key, 0, windowStart);
// 2. Add current request
pipeline.zAdd(key, { score: now, value: `${now}-${Math.random()}` });
// 3. Count requests in window
pipeline.zCard(key);
// 4. Reset TTL
pipeline.expire(key, Math.ceil(windowMs / 1000));
const results = await pipeline.exec();
const requestCount = results[2][1]; // zCard result
return requestCount > limit;
}
Priority Queue
// Priority queue: lower score = higher priority
async function enqueue(task, priority) {
await redis.zAdd('tasks:priority', { score: priority, value: JSON.stringify(task) });
}
// Dequeue highest priority task (lowest score)
async function dequeue() {
const result = await redis.zPopMin('tasks:priority');
return result ? JSON.parse(result.value) : null;
}
// Blocking dequeue
async function dequeueBlocking(timeout = 30) {
const result = await redis.bzPopMin('tasks:priority', timeout);
return result ? JSON.parse(result.value) : null;
}
Tip: Use ZINCRBY instead of ZADD to add to a score atomically. This is perfect for vote counts, page view tallies, and leaderboard point additions.
Frequently Asked Questions
Can sorted set scores be negative?
Yes. Scores are double-precision floats and can be any value including negative numbers or ±infinity.
What is ZRANGEBYLEX?
ZRANGEBYLEX returns members in lexicographic order when all members have the same score. It's used for autocomplete and prefix searches.
How do I implement weekly leaderboards that reset?
Create a key like leaderboard:2026-W45 with an expiry set to the end of the week. Each week gets a fresh key; old ones auto-expire.