Go Redis: Sorted Set Leaderboard
In this tutorial, you'll learn about Go Redis: Sorted Set Leaderboard. We cover key concepts, practical examples, and best practices.
Redis sorted sets -- Use ZADD, ZRANGE, ZREVRANGE for leaderboards, rankings, and ordered data.
The Problem
Sorted set scores are float64. ZRANGE returns ascending, ZREVRANGE returns descending. Confusing these causes wrong rankings.
Wrong
rdb.ZAdd(ctx, "leaderboard", redis.Z{
Score: 100, Member: "Alice",
}).Err()
rank := rdb.ZRange(ctx, "leaderboard", 0, 0).Val()
Output:
// Returns lowest score first! Alice should be top.
Right
rdb.ZAdd(ctx, "leaderboard", redis.Z{Score: 100, Member: "Alice"})
rdb.ZAdd(ctx, "leaderboard", redis.Z{Score: 85, Member: "Bob"})
// Top players:
top, _ := rdb.ZRevRangeWithScores(ctx, "leaderboard", 0, 2).Result()
for _, z := range top {
fmt.Printf("%s: %.0f
", z.Member, z.Score)
}
Output:
Alice: 100
Bob: 85
Prevention
- Use ZRevRange for descending (high to low)
- Use ZRange for ascending (low to high)
- Use ZRevRank to get rank by member
- Use ZIncrBy to update score atomically
- Use ZRem to remove members
Common Mistakes with redis sorted set
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro