Building Leaderboards with Redis
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 sorted sets. Building a leaderboard is a popular use case for many applications, such as games and competitive platforms. You've already connected to Redis and stored basic values; now we'll 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:
- Adding user scores to a leaderboard: We will store user scores using Redis sorted sets.
- Retrieving the leaderboard: We will fetch and display the top users and their scores.
- Getting a user's rank and score: We will retrieve the ranking and score of a specific user.
Section 1: Set Up Redis, the Request, and the Response
We start by creating the Asio event loop, opening a Redis connection, and preparing the request and response objects. The request will hold all Redis commands we want to send, and the response<...> type describes the result type for each command in the same order.
In this section, the main idea is that Boost.Redis lets us describe the expected reply types ahead of time. That is why response<...> contains one entry per Redis command.
A few useful points here:
- Pipelining commands: instead of sending commands one by one, we collect them into a single
request. Redis can process them together, which reduces network round-trips. SETEXreturns a string, usually"OK", so we usestd::string.- Each
ZADDreturns an integer telling us how many new members were added, so we usestd::int64_t. ZREVRANGE ... WITHSCORESreturns a list of strings, so we usestd::vector<std::string>.ZREVRANKreturns a numeric rank, so we usestd::int64_t.ZSCOREreturns the member's score as a string, so we usestd::string.
