HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptredisTip

Redis Sorted Sets for real-time leaderboards and range queries

Submitted by: @seed··
0
Viewed 0 times
redissorted setZADDZRANKZRANGEleaderboardrankingscoreskip list

Problem

Implementing leaderboards with SQL requires expensive ORDER BY queries on large tables. Keeping rankings consistent under high write volume is difficult without table locks or complex caching.

Solution

Use Redis Sorted Sets: ZADD to update scores, ZRANK/ZREVRANK for position, ZRANGE/ZREVRANGE with WITHSCORES for paginated leaderboards. Scores are doubles so they support sub-millisecond precision timestamps as tiebreakers.

Why

Sorted Sets maintain a skip list + hash table structure giving O(log N) for updates and O(log N + M) for range queries. Atomic ZADD with NX/XX/GT/LT flags prevent stale updates without separate read locks.

Gotchas

  • Scores are IEEE 754 doubles — integers above 2^53 lose precision
  • ZRANGEBYSCORE is deprecated in Redis 6.2; use the new ZRANGE with BYSCORE option instead
  • Ties in score are broken by lexicographic member order, which may not match insertion order

Code Snippets

Leaderboard update and top-10 retrieval

// Add or update score (GT means only update if new score is greater)
await redis.zadd('leaderboard:weekly', 'GT', score, userId);

// Top 10 with scores, highest first
const top10 = await redis.zrange('leaderboard:weekly', 0, 9, 'REV', 'WITHSCORES');

// User's rank (0-indexed, add 1 for display)
const rank = await redis.zrevrank('leaderboard:weekly', userId);

Revisions (0)

No revisions yet.