Redis is truly the perfect solution for leaders. While you are introducing another technology, if you are using AWS, please note that ElastiCache was running Redis, was just launched this week .
Common Redis Commands:
zadd votes 5 "Andy" zadd votes 8 "Barry" zadd votes 5 "Carl" zadd votes 1 "Derek"
Then, to get the top rated leaders:
zrevrange votes 0 -1
See Redis docs for ZREVRANGE for more details .
For Ruby on Rails, I would advise you to take a look at my redis-objects gem, which is popular as it integrates easily with ActiveRecord. Assuming you have a table with a votes column as shown, you can update the rating while saving:
class User < ActiveRecord::Base include Redis::Objects sorted_set :rank, global: true after_save :update_rank def update_rank self.class.rank[id] = votes end end
Then extract the leaderboard:
User.rank.revrange(0, -1)
In this example, this will return id values ββthat can then be used to retrieve the entries as follows. (You can also save first_name or another unique value.)
ids = User.rank.revrange(0, -1) users = User.where(id: ids).all
You can paginate with revrange by passing different start / end values:
User.rank.revrange(0, 9) User.rank.revrange(10, 19)
You can easily wrap this with the self. method self. in User, who received the ranking page from Redis and returned DB records accordingly.