How to Implement a Simple Redis Leaderboard

Leave your reply

Introduction

Learn how to create a simple leaderboard in Redis. Redis is a popular key-value store which is optimized for speed and flexibility. Redis's sorted sets are a perfect fit for implementing a leaderboard, which has made Redis a popular choice for many gaming apps and websites.

Requirements

  • A Cloud Server running Linux (CentOS 7 or Ubuntu 14.04).
  • Redis installed and running. See our article on Installing Redis on a 1&1 IONOS Linux Cloud Server if needed.

Sorted Sets

For this project we will be using sorted sets to maintain the high score list. A sorted set is a collection of strings, which are ordered by a sorting score you set. Although scores can be repeated, strings cannot.

This means that all you need to do to update a user's score is simply add that user to the sorted set again, this time with the new score. This will have the effect of updating the existing string with the new score.

We will be using the ZADD command to update scores, ZRANK to get a player's rank, and ZRANGE to pull a list of the top 5 players.

Add Data to the Leaderboard

Let's start by adding some test data to the leaderboard. From the command line, log in to Redis with the command:

sudo redis-cli

ZADD to Add Data

Next, use the zadd command to add players and their scores. The syntax of zadd is:

zadd [set name] [score] [string]

For this example we will name our set leaderboard, the score will be the player's current points in the game, and the string is the player's name.

Add three players with the following three commands:

zadd leaderboard 1 "Alice"
zadd leaderboard 30 "Bob"
zadd leaderboard 5300 "Carol"

ZREVRANGE to List Data

You can list this data with the zrevrange command. This command takes two arguments:

zrevrange [set name] [first position] [second position]

It returns all the results between those two positions, sorted by score in reverse order, highest score first. (The opposite of zrevrange is zrange, which returns results sorted with the lowest score first.)

Note that Redis uses standard Unix notation, which means that the first item in a list is number 0, the second item is number 1, and so forth. To get the top three scores, we will use the command:

zrevrange leaderboard 0 2

To get the top 100 scores, the command would be:

zrevrange leaderboard 0 99

And so forth.

Let's list top three scores:

127.0.0.1:6379> zrevrange leaderboard 0 2
1) "Carol"
2) "Bob"
3) "Alice"

As you can see, Carol is in first place, Bob is in second, and Alice is trailing in third place.

We can also add withscores to the command, so that it returns their scores as well:

127.0.0.1:6379> zrevrange leaderboard 0 2 withscores
1) "Carol"
2) "5300"
3) "Bob"
4) "30"
5) "Alice"
6) "1"

Next, let's add a fourth person:

zadd leaderboard 25 "Don"

We still only want to show the top three players, though:

127.0.0.1:6379> zrevrange leaderboard 0 2
1) "Carol"
2) "Bob"
3) "Don"

ZADD to Update Data

Over the weekend, Alice works hard and manages to earn a lot of points. We can update Alice's score simply by adding her again, this time with the new score:

zadd leaderboard 31 "Alice"

If we list the top three players again, we can see that Alice is now in second place, and Don is no longer listed on the leaderboard:

127.0.0.1:6379> zrevrange leaderboard 0 2
1) "Carol"
2) "Alice"
3) "Bob"

ZREM to Remove Data

Several players have been complaining that Carol's score is suspiciously high. When you check your game's logs, you find evidence that she has been cheating. After banning Carol from the game, you need to remove her from the leaderboard with the zrem command.

The syntax for zrem is:

zrem [set name] [string]

Let's remove Carol from the leaderboard with the command:

zrem leaderboard "Carol"

When we refresh the standings, Alice is now in the top spot:

127.0.0.1:6379> zrevrange leaderboard 0 2
1) "Alice"
2) "Bob"
3) "Don"

Choosing a Redis Client

You will need a Redis client to serve as an interface between Redis and your programming language of choice. For this project we will be using PHP, but there are Redis clients available for dozens of languages. The official Redis website maintains a full list of Redis clients by programming language. Recommended clients are marked with a gold star.

The recommended PHP clients are phpredis which is compiled and installed as a PHP module, and Predis which is a PHP library. We will be using Predis for this tutorial, but phpredis is an excellent client as well.

Install and Test Predis

The easiest way to install Predis is to download it from the official Pear channel. On Ubuntu 14.04, you will first need to install Pear with the command:

sudo apt-get install php-pear

Connect to the official Pear server and install Predis with the commands:

sudo pear channel-discover pear.nrk.io
sudo pear install nrk/Predis

Once this has finished, you can test the Predis installation with a simple PHP script. Move to your main web directory and create a new file called predis-test.php with the command:

sudo nano predis-test.php

Put the following content in to this file:

<?php
require "Predis/Autoloader.php";
Predis\Autoloader::register();

$client = new Predis\Client();
$client->set('test', 'Hello world!');
$message = $client->get('test');

echo $message;

?>

Save and exit the file, then view the file in a browser at http://example.com/predis-test.php. If Predis is installed and connecting to Redis, the page will say "Hello world!"

Show Leaderboard Results on a Website

As a final matter, let's display the top three high scores in a table. To do this, we will need to have PHP put the contents of the array into an HTML table.

In your web directory, create a new file called leaderboard.php with the command:

sudo nano leaderboard.php

Put the following content into this file:


<?php
require "Predis/Autoloader.php";
Predis\Autoloader::register();

$client = new Predis\Client();

$scores = $client->zRevRange('leaderboard', 0, 2, array('withscores' => true));

?>

<table cellpadding="0" cellspacing="5" >
  <tr>
    <td><b>Player</b></td>
    <td><b>Score</b></td>
  </tr>

<?php
  foreach($scores as $key => $index) {
    ?>
    <tr>
      <td><?php echo $key; ?></td>
      <td><?php echo $index; ?></td>
    </tr>
<?php
  }
?>

</table>

Save and exit the file, then view the file in a browser at http://example.com/leaderboard.php. You will see the top three scores in our current leaderboard standings.