Lesson 2
Using Sorted Sets for Leaderboards
Using Sorted Sets for Leaderboards

Welcome to the next exciting part of our Redis-based backend system project. In this unit, we will focus on building leaderboard functionality using Redis's sorted sets. Building a leaderboard is a popular use case for many applications, such as games and competitive platforms. You’ve got a good handle on managing user data from previous lessons, so let’s build on that foundation.

What You'll Build

Let's briefly review what we’ll focus on in this unit. Our main tasks will be:

  1. Adding user scores to a leaderboard: We will store user scores using Redis sorted sets.
  2. Retrieving the leaderboard: We will fetch and display the top users and their scores.
  3. Getting a user's rank and score: We will retrieve the ranking and score of a specific user.

Below are some key parts of the code you will be working with to perform these tasks.

Python
1import redis 2import json 3from datetime import timedelta 4 5# Connect to Redis 6client = redis.Redis(host='localhost', port=6379, db=0) 7 8client.zadd('leaderboard', {'user1': 100}) 9client.zadd('leaderboard', {'user2': 200}) 10client.zadd('leaderboard', {'user3': 150}) 11 12leaderboard = client.zrevrange('leaderboard', 0, 2, withscores=True) 13print(leaderboard) 14 15rank = client.zrevrank('leaderboard', 'user3') 16score = client.zscore('leaderboard', 'user3') 17print(rank, score)

This example demonstrates how to add a score for a user, retrieve the top scores, and fetch a user’s rank and score. You are familiar with the zadd and zrevrange commands from previous lessons. These commands are used to add scores and retrieve the leaderboard, respectively.

Now let's understand the zrevrank and zscore commands. The zrevrank command returns the rank of a member in a sorted set, with the highest score being ranked first. The zscore command retrieves the score of a member in a sorted set. They both get the set name and the member as parameters.

Now that you have an overview, let's dive into the practice section to start implementing these components. Your hands-on work will strengthen your understanding, setting you up for success in creating robust backend features.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.