Build a Real-Time Leaderboard with Redis Sorted Sets
Use Redis sorted sets to implement real-time leaderboards with rank tracking, score updates, and top-N queries in O(log N) time
Overview
Every game team I’ve worked with has built the same thing at some point: a ORDER BY score DESC LIMIT 10 query that gets slower every season until someone finally moves it to Redis. Sorted sets (ZSETs) exist for exactly this — each member carries a score, and Redis keeps the whole set ordered, so rank lookups, increments, and top-N reads all land in O(log N).
This recipe builds a Leaderboard class on redis-py with score updates, rank queries, neighborhood lookups, daily/weekly boards, pagination, and the edge cases that bite in production: ties, missing members, and keys that never expire.
When to Use This
- Game leaderboards with real-time score updates
- Ranking systems for content popularity or user activity
- Any scenario where you need an ordered set with frequent, concurrent updates
Prerequisites
- Python 3.10+
redispackage (pip install redis)
Solution
1. Install Dependencies
pip install redis
2. Implement the Leaderboard
import logging
from redis import Redis
logger = logging.getLogger(__name__)
class Leaderboard:
def __init__(self, redis_client: Redis, key: str = "leaderboard"):
self.redis = redis_client
self.key = key
def add_score(self, member: str, score: float) -> int:
"""Add or update a member's score.
Args:
member: Unique member identifier (e.g., user ID).
score: Score to set.
Returns:
Number of new elements added (0 if updated existing).
"""
return self.redis.zadd(self.key, {member: score})
def increment_score(self, member: str, increment: float) -> float:
"""Increment a member's score by a delta.
Args:
member: Member identifier.
increment: Amount to add (can be negative).
Returns:
New score after increment.
"""
return self.redis.zincrby(self.key, increment, member)
def get_rank(self, member: str) -> int | None:
"""Get a member's rank (0-indexed, highest score first).
Args:
member: Member identifier.
Returns:
Rank (0 = top) or None if not on the leaderboard.
"""
rank = self.redis.zrevrank(self.key, member)
return rank
def get_score(self, member: str) -> float | None:
"""Get a member's current score."""
return self.redis.zscore(self.key, member)
def get_top_n(self, n: int = 10, offset: int = 0) -> list[dict]:
"""Get the top N members with scores, from `offset` (for pagination).
Args:
n: Number of top members to return.
offset: How many leaders to skip — page 2 of a 10-per-page board is offset=10.
Returns:
List of {member, score, rank} dicts, highest first.
"""
results = self.redis.zrevrange(
self.key, offset, offset + n - 1, withscores=True
)
return [
{"member": member.decode() if isinstance(member, bytes) else member,
"score": score, "rank": offset + idx}
for idx, (member, score) in enumerate(results)
]
def get_around_member(self, member: str, count: int = 5) -> list[dict]:
"""Get members ranked around a specific member.
Args:
member: Member to center on.
count: Number of members above and below.
Returns:
List of nearby members with scores and ranks.
"""
rank = self.redis.zrevrank(self.key, member)
if rank is None:
return []
start = max(0, rank - count)
end = rank + count
results = self.redis.zrevrange(
self.key, start, end, withscores=True
)
return [
{"member": m.decode() if isinstance(m, bytes) else m,
"score": s, "rank": start + idx}
for idx, (m, s) in enumerate(results)
]
def remove_member(self, member: str) -> int:
"""Remove a member from the leaderboard."""
return self.redis.zrem(self.key, member)
def total_members(self) -> int:
"""Get the total number of members on the leaderboard."""
return self.redis.zcard(self.key)
def clear(self) -> int:
"""Remove all members from the leaderboard."""
return self.redis.delete(self.key)
3. Use the Leaderboard
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
lb = Leaderboard(r, key="game:scores")
# Add scores
lb.add_score("alice", 1500)
lb.add_score("bob", 2300)
lb.add_score("charlie", 1800)
lb.increment_score("alice", 500) # alice now has 2000
# Get top 3
top3 = lb.get_top_n(3)
# [{'member': 'bob', 'score': 2300.0, 'rank': 0},
# {'member': 'alice', 'score': 2000.0, 'rank': 1},
# {'member': 'charlie', 'score': 1800.0, 'rank': 2}]
# Page 2 of the same board (ranks 3–5)
page2 = lb.get_top_n(3, offset=3)
# Get alice's rank
rank = lb.get_rank("alice") # 1
# Get players around alice — great for "you are here" UI
nearby = lb.get_around_member("alice", count=2)
4. Time-Based Leaderboards
Use Redis sorted sets with date-based keys for daily, weekly, or all-time leaderboards:
from datetime import date
class TimeBasedLeaderboard(Leaderboard):
def __init__(self, redis_client: Redis, game_id: str):
self.redis = redis_client
self.game_id = game_id
def _key(self, period: str = "all") -> str:
if period == "daily":
return f"lb:{self.game_id}:daily:{date.today().isoformat()}"
elif period == "weekly":
year, week, _ = date.today().isocalendar()
return f"lb:{self.game_id}:weekly:{year}-W{week}"
return f"lb:{self.game_id}:all"
def add_score(self, member: str, score: float, period: str = "all") -> int:
key = self._key(period)
return self.redis.zadd(key, {member: score})
def increment_score(self, member: str, increment: float, period: str = "all") -> float:
key = self._key(period)
return self.redis.zincrby(key, increment, member)
def get_top_n(self, n: int = 10, period: str = "all") -> list[dict]:
key = self._key(period)
results = self.redis.zrevrange(key, 0, n - 1, withscores=True)
return [
{"member": m, "score": s, "rank": idx}
for idx, (m, s) in enumerate(results)
]
5. Expire Old Leaderboards
Set TTLs on daily/weekly keys so old leaderboards clean themselves up. The trick is setting expiry only when the key has none — EXPIRE ... NX does that atomically, unlike a “did ZADD create the member?” check, which races with another writer expiring the key first:
class TimeBasedLeaderboard(Leaderboard):
# ... as above, plus:
def add_score_with_expiry(self, member: str, score: float,
period: str = "daily") -> int:
key = self._key(period)
result = self.redis.zadd(key, {member: score})
ttl = 86400 * 2 if period == "daily" else 86400 * 8
# NX: set the TTL only if the key doesn't already have one
self.redis.expire(key, ttl, nx=True)
return result
How It Works
ZADDadds or updates a member’s score — one command, ordered on write, nothing to sort on read.ZINCRBYatomically bumps a score. That’s the line that makes concurrent updates from several game servers safe; a read-modify-write in your app code isn’t.ZREVRANGEreturns members highest-first, and theoffsetargument is what makes pagination free — page N is just a different window on the same sorted set.ZREVRANKgives a member’s position, 0-indexed from the top, andget_around_memberbuilds a window around it for the “players near you” view.- Date-based keys (
lb:game:daily:2026-07-02) give you per-period boards for free;EXPIREsweeps the old ones.
Variants
Leaderboard with Ties
When members can share a score, Redis breaks the tie lexicographically by member name — almost never what you want. Encode a tiebreaker into the score instead, so earlier achievers rank higher:
def add_score_with_tiebreak(self, member: str, score: float, join_time: float) -> int:
# Composite score: score * 1e10 + (max_time - join_time)
composite = score * 10_000_000_000 + (10_000_000_000 - join_time)
return self.redis.zadd(self.key, {member: composite})
Percentile Rank
def get_percentile(self, member: str) -> float | None:
"""Get the member's percentile (0-100, higher is better)."""
rank = self.redis.zrevrank(self.key, member)
total = self.redis.zcard(self.key)
if rank is None or total == 0:
return None
return ((total - rank - 1) / total) * 100
Leaderboard with Member Metadata
Sorted sets store just member + score. Keep display names, avatars, or country flags in a per-member hash and join with one pipeline — one round trip instead of N:
def get_top_n_with_meta(self, n: int = 10) -> list[dict]:
top = self.get_top_n(n)
pipe = self.redis.pipeline()
for entry in top:
pipe.hgetall(f"user:{entry['member']}")
metas = pipe.execute()
for entry, meta in zip(top, metas):
entry["metadata"] = meta
return top
Friends-Only Leaderboard
For “beat your friends” boards, don’t maintain a separate sorted set per user — it explodes memory. Keep the global board and filter the member list client-side, or maintain a small per-user ZSET capped with ZREMRANGEBYRANK key 0 -101 to keep only the top 100 friends.
Best Practices
- Use
ZINCRBYfor concurrent updates — atomic; aZSCORE+ZADDread-modify-write loses updates under load. - Set TTLs on time-based keys with
NX— daily/weekly boards should expire, andexpire(key, ttl, nx=True)never clobbers an existing TTL. - Use pipelines for batch reads — the metadata join above is one round trip for the whole page.
- Keep member IDs short — the member string is stored per entry; long UUIDs add up at millions of members.
- For the wider caching picture — invalidation, L1/L2 layering — see the Complete Guide to Redis Caching Strategies and the cache-aside recipe.
Common Mistakes
- Using
ZRANGEinstead ofZREVRANGE—ZRANGEreturns lowest-first, which is almost never what a leaderboard wants. - Not handling missing members —
zscoreandzrevrankreturnNonefor absent members; crash here and your “view profile” page dies on every newcomer. - Storing metadata in the sorted set — ZSETs only hold member + score. A second hash per member keeps the board lean.
- Not expiring daily keys — without TTLs, a daily leaderboard creates a permanent key per game per day forever.
- Trusting client-submitted scores — for competitive games, compute or verify the score server-side before
ZINCRBY; a client that can write any score it wants will be abused within days.
Further Reading
- Redis sorted sets data type — the official reference for every ZSET command used here
- ZREVRANGE / ZRANGE command reference — pagination semantics and
WITHSCORES - Redis caching strategies guide — where leaderboards fit in a broader Redis architecture
Frequently Asked Questions
What is the time complexity of sorted set operations?
ZADD and ZINCRBY are O(log N). ZREVRANGE is O(log N + M) where M is the number of elements returned. ZREVRANK is O(log N).
How many members can a sorted set hold?
The hard cap is 2^32 - 1 members, though you'll hit memory limits way earlier — figure ~80-100 bytes per member.
Can I use floating-point scores?
Yep — Redis sorted sets accept double-precision floats. Be aware of floating-point comparison issues for exact ties.
How do I migrate a leaderboard to a new key?
Use ZUNIONSTORE to merge: ZUNIONSTORE new_key 1 old_key. Or dump and restore with DUMP/RESTORE.
What happens when two members have the same score?
Redis sorts by score first, then by member name lexicographically. If you need tie-breaking by timestamp, encode it in the score: score = actual_score * 1e10 + (max_timestamp - timestamp).
How do I expire old leaderboard entries automatically?
Sorted sets don't support per-member TTL. Use a separate sorted set as a "last seen" index and periodically remove stale members: ZREMRANGEBYSCORE leaderboard -inf <cutoff_score>. Alternatively, run a scheduled job that removes members whose last_active timestamp is older than your threshold.
What is the memory consumption of a sorted set?
Each member uses approximately 80–100 bytes (member name + score + skiplist pointers). A leaderboard with 1 million members uses roughly 80–100 MB. Monitor with MEMORY USAGE leaderboard_key.
Can I use Redis Cluster with sorted set leaderboards?
Yes, but all operations on a single sorted set must route to the same shard. Since sorted sets are single-key data structures, Redis Cluster handles this automatically via hash slot assignment. Cross-shard operations like ZUNIONSTORE require hash tags: {leaderboard}:daily and {leaderboard}:weekly.
Related Resources
Implement the Cache-Aside Pattern with Redis
Use the cache-aside pattern to read and write data through Redis, handling cache misses, stale reads, and write-through invalidation
RecipeMulti-Level Cache with In-Memory L1 and Redis L2
Cut Redis round-trips on hot keys: in-memory L1 for microsecond reads, Redis L2 for shared state, and pub/sub invalidation across instances
RecipeCache Function Results with Redis and TTL in Python
Build a Python decorator that caches function return values in Redis with configurable TTL, key generation, and cache invalidation
RecipeConnect to Redis
How to connect to Redis in Python, JavaScript, and Java — with AUTH, TLS, pooling, and the core data types you'll actually use.