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

In this unit, we will work on three main tasks:

  1. Adding user scores to a leaderboard: Use Redis's sorted sets to store user scores efficiently.
  2. Retrieving the leaderboard: Fetch and display the top users along with their scores.
  3. Getting a user's rank and score: Retrieve a specific user's ranking and score from the leaderboard.

These tasks will demonstrate how Redis sorted sets help maintain order and provide efficient rank-based queries.

Adding User Scores to a Leaderboard

To add user scores to a leaderboard, we’ll use Redis’s zadd command. In Java, the zadd method of Jedis allows us to add a user with an associated score to a sorted set. Here’s the relevant portion of the User class:

// Add user score to the leaderboard using a pipeline
public static void addScoreWithPipeline(Pipeline pipeline, User user) {
    pipeline.zadd("leaderboard", user.getScore(), user.getUsername());
}

This method adds the user’s score to the "leaderboard" sorted set. As a reminder, pipelines allow multiple commands to be sent in one go, improving performance by reducing network latency.

In the Main class, this method is called for each user:

try (Pipeline pipeline = jedis.pipelined()) {
    for (User user : new User[]{user1, user2, user3}) {
        User.addScoreWithPipeline(pipeline, user);
    }
    pipeline.sync();
}

This snippet adds scores for multiple users in one batch operation with reduced communication overhead.

Retrieving the Leaderboard

To fetch and display the top users and their scores, we use Redis’s zrevrange command, which retrieves elements in descending order of scores. The getLeaderboard method handles this:

// Retrieve the top 10 users from the leaderboard
public static List<Tuple> getLeaderboard(Jedis jedis) {
    return jedis.zrevrangeWithScores("leaderboard", 0, 9);
}

Here’s how it’s used in the Main class to display the leaderboard:

System.out.println("Leaderboard: " + User.getLeaderboard(jedis));

This outputs a list of the top 10 users with their scores, formatted as [[username, score], ...].

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal