Video in progress

For a leaderboard updated in real time, how do you keep the top 100 and a user's rank: TreeMap, skip list, heap or Redis ZSET?

With a single instance and a small volume, a ConcurrentSkipListMap or a TreeMap under a lock is enough, but a "what is this user's rank" query is O(n) in JDK structures. With many instances, a million players and a rank query, a Redis sorted set (skip list + rank) is the natural choice.

📖 Answer

I separate the requirements, because they call for different structures:

  • updating a score (thousands per second);
  • reading the top N;
  • the rank of a specific user;
  • the ±5 players around a user.

JDK options:

PriorityQueue is only good for the top N, but a score update is remove(Object) O(n) + offer. It doesn't suit a leaderboard.

TreeMap / ConcurrentSkipListMap with the key (score, userId), plus a Map<userId, score> next to it. An update means removing the old key and putting the new one, O(log n). The top N is the first N from descendingMap(). But the rank is headMap(key).size(), which is O(n): the size() of the range view counts the elements one by one. With a million players, that is a million steps per query.

record Key(long score, long userId) implements Comparable<Key> {
    public int compareTo(Key o) {
        int c = Long.compare(o.score, score);          // higher score first
        return c != 0 ? c : Long.compare(userId, o.userId); // tell equal scores apart
    }
}

To get the rank in O(log n), you need an "order statistic tree" that stores the number of elements below in every node. The JDK doesn't have one, so you write it yourself or get a library.

A Redis ZSET gives exactly this: ZADD, ZREVRANGE 0 99, ZREVRANK user, all O(log n), with spans stored inside the skip list. Several service instances see the same state.

Architecture aspects: Redis becomes a single point, so you need replication and persistence settings; very large leaderboards (tens of millions) get split into several ZSETs (season, region); the top 100 is cached and served every second, not recomputed on every request. If exact results matter (prizes), the final result is recomputed from the source data in the DB anyway.