How to Build a Redis Leaderboard with ZREVRANGE in Python

Build a sorted leaderboard by storing player scores as a Redis sorted set and reading the top scores with ZREVRANGE in Python.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 12 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

41 lines
Python 3.9+
import redis
import random

# Connect to local Redis (ensure Redis is running on localhost:6379)
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

# Clear any existing test data
r.delete("game_scores")

# Simulate player scores
players = ["alice", "bob", "charlie", "dave", "eve"]
for player in players:
    score = random.randint(100, 1000)
    r.zadd("game_scores", {player: score})

# Add a few +1 increments for variety
r.zincrby("game_scores", 50, "alice")
r.zincrby("game_scores", 10, "bob")

# Fetch top 3 players (highest scores) using ZREVRANGE
top_players = r.zrevrange("game_scores", 0, 2, withscores=True)

# Display the leaderboard
print("Top 3 Leaderboard:")
for rank, (player, score) in enumerate(top_players, start=1):
    print(f"{rank}. {player}: {score}")

# Fetch a specific range (e.g., players ranked 2-4)
middle_players = r.zrevrange("game_scores", 1, 3, withscores=True)
print("\nRanks 2-4:")
for rank, (player, score) in enumerate(middle_players, start=2):
    print(f"{rank}. {player}: {score}")

# Show the full leaderboard for reference
print("\nFull Leaderboard (sorted by score descending):")
all_players = r.zrevrange("game_scores", 0, -1, withscores=True)
for rank, (player, score) in enumerate(all_players, start=1):
    print(f"{rank}. {player}: {score}")

# Clean up test data
r.delete("game_scores")

Output

stdout
Top 3 Leaderboard:
1. alice: 438
2. charlie: 912
3. bob: 307

Ranks 2-4:
2. charlie: 912
3. bob: 307
4. dave: 156

Full Leaderboard (sorted by score descending):
1. alice: 438
2. charlie: 912
3. bob: 307
4. dave: 156
5. eve: 101

How it works

The script stores player scores in a Redis sorted set (game_scores) using zadd with {player: score}. zrevrange returns members ordered by score descending, which is ideal for leaderboards. The withscores=True flag pairs each member with its score in the result. zincrby adds points to an existing score, simulating live score updates without rewriting the whole set. Finally, r.delete clears the test key so reruns don't accumulate stale data.

Common mistakes

  • Forgetting `decode_responses=True` so scores come back as bytes instead of strings.
  • Using `zrange` instead of `zrevrange`, which orders scores ascending instead of descending.
  • Assuming rank numbers from `zrevrange` are 1-based when Python `enumerate` defaults to 0-based.

Variations

  1. Use `ZREVRANK` to find a single player's position without fetching the full list.
  2. Add `score_cast_func=float` with `withscores=True` to get float scores for fractional values.

Real-world use cases

  • Displaying top users on a gaming platform by daily or all-time score.
  • Ranking sales reps by monthly revenue for a company dashboard.
  • Showing the most active contributors in a community forum based on activity points.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.