Dan Tang
Dan Tang

Reputation: 1343

Different leaderboards for different levels using Redis

I'm new to Redis, and I'm trying to create leaderboards for different levels in a game (e.g. the game might have 20 levels, and I would like to create 20 different leaderboards).

Reading the documentation from AWS, it seems that sorted sets are the way to go, but would I need to create 20 different elastic cache instances?

Or would I do something like ZADD leaderboard:1, ZADD:leaderboard:2, where 1 or 2 corresponds to the id of the game?

Apologies if this is a stupid question as this is my first attempt at Redis.

Upvotes: 0

Views: 490

Answers (1)

Ersoy
Ersoy

Reputation: 9594

You don't need to create 20 different ElastiCache instances, you may just use one(you need to decide the instance type depending on size, network etc).

Whenever you need to add a new user to a level(update the score if he exists), you need to execute zadd with the key of the level, the user and the score(points in your domain). zadd also supports setting multiple user scores at once.

> ZADD leaderboard:1 154 "user273"
(integer) 1
> ZADD leaderboard:2 12 "user786"
(integer) 1
> ZADD leaderboard:3 221 "user:6817" 912 "user:21233"
(integer) 2

When user:123 entered to the leaderboard with the score of 15 and then he gets 19, his score(points) will be overwritten when you execute zadd.

You will have a sorted set with full of unique users with their corresponding scores. The tricky parts in here; If you are going to get the top 5 users then you need to use zrevrange instead of zrange because your rank will be smaller(numeric order) when your points are higher. In that case

zrevrange leaderboard:1 0 4 withscores

will give you the top 5 users at level 1. withscores is optional.

Upvotes: 2

Related Questions