Design Problem: A Leaderboard, with Ranks for Ten Million Members, Who Comes First in a Tie, and Time Decay for Trending Talks
System Design series · Part 9 Design problems (6 of 7)
- Design Problem: A URL Shortener, from Estimates and Code Generation to Phishing Abuse
- Design Problem: A News Feed, Push vs Pull, and the Celebrity Problem
- Design Problem: A Chat System, Where Direct Messages and a 50,000-Person Live Chat Room Are Two Different Problems
- Design Problem: Flash Sale Ticketing, and How Much Each Layer Must Turn Away When 500,000 People Chase 10,000 Seats
- Design Problem: A Notification System Where Verification Codes Cannot Wait Behind 10 Million Newsletters
- Design Problem: A Leaderboard, with Ranks for Ten Million Members, Who Comes First in a Tie, and Time Decay for Trending Talks
- Design Problem: A Distributed Scheduler, Where a Million Delayed Tasks Must Each Run Only Once, at the Right Time
System Design series Part 9-6 | Previous: Notification System | Next: Distributed Scheduler | Series map
Read first: Part 7-4 Batch and Stream Processing.
Scenario and problem
The talk platform is launching learning points: you earn points by attending talks, passing the quiz after a talk, and completing learning paths. A points leaderboard is published every week, and the top 100 get rewards. On top of that, the home page has to show “trending talks in the last 24 hours”.
Functional requirements
- The top 100 of the weekly leaderboard, and “my rank”
- Rankings among friends
- On a tie, whoever reached the score first ranks higher (there are rewards, so the rule has to be clear)
- Trending talks: sorted by sign-ups in the last 24 hours, with more recent sign-ups weighted higher
Scale estimate
| Item | Estimate |
|---|---|
| Members in the ranking | 10 million |
| Points updates | 2 million daily active users × 5 a day = 10 million a day, about 116 a second on average |
| Peak points updates | When a live talk ends, 50,000 viewers submit the quiz within 1 minute → about 1,000 a second |
| Viewing the top 100 | About 50 a second |
| Viewing my rank | About 500 a second (every profile page shows it) |
- Points updatesYou earn points by attending talks, passing the quiz after a talk, and completing learning paths. 10 million members are in the ranking, with about 116 points updates a second on average.
- The minute a live talk endsWhen a live talk ends, 50,000 viewers submit the quiz within 1 minute, and points updates peak at about 1,000 a second.
- The top 100 and my rankThe top 100 of the weekly leaderboard get rewards and are viewed about 50 times a second; every profile page shows "my rank", about 500 times a second. Rankings among friends are needed too.
- Breaking tiesThere are rewards, so the rule has to be clear: on a tie, whoever reached the score first ranks higher.
- Trending talks in the last 24 hoursThe home page sorts trending talks by sign-ups in the last 24 hours, with more recent sign-ups weighted higher.
The simplest approach and its limits
Store points in a member_points table, with an index on points:
-- Top 100: uses the index, fast
SELECT member_id, points FROM member_points ORDER BY points DESC LIMIT 100;
-- My rank: count how many people have more points than me
SELECT COUNT(*) + 1 FROM member_points WHERE points > :myPoints;The top 100 is no problem. For a member ranked 5,000,000th, “my rank” has to scan 5 million entries in the index to count them (Indexes and B+Trees post), a few hundred milliseconds each time; at 500 a second, that is most of the database’s load. If you cache the result, the rank goes stale, because other people’s points keep changing.
Core mechanism
Sorted sets: a rank is O(log N)
Internally, a Redis sorted set keeps both a hash table (member → score) and a skip list (ordered by score), and each node records the distance it spans, so:
| Operation | Command | Complexity |
|---|---|---|
| Update a score | ZADD / ZINCRBY |
O(log N) |
| Top 100 | ZREVRANGE 0 99 WITHSCORES |
O(log N + 100) |
| My rank | ZREVRANK |
O(log N) |
| How many people are at or above a score | ZCOUNT |
O(log N) |
With 10 million members, log N is about 23, and “my rank” drops from a few hundred milliseconds to under 1 millisecond.
Memory: each member takes roughly tens of bytes to 100 bytes in the sorted set. Add the separate hash that stores the points, and 10 million members come to about 1 to 2 GB (a rough estimate that depends on the Redis version and encoding), which fits on a single node.
Throughput: a sorted set is one key, so it can live on only one Redis node and cannot be spread across the nodes of a cluster. A peak of 1,000 updates plus 550 reads a second is not a problem for a single node. Updates go through Kafka, so the queue absorbs sudden spikes, and a leaderboard that updates a few seconds late is acceptable.
On a tie, whoever got there first ranks higher
A sorted set orders members with the same score by the lexicographic order of the member names, which looks random to users. The rule is “whoever got there first ranks higher”, so the time has to be encoded into the score as well:
score = points × 2²¹ + (seconds left until the end of the week)- A week is 604,800 seconds, less than 2²¹ (2,097,152), so the seconds left fit in the low 21 bits
- The earlier you reach a points total, the more seconds are left, the higher the score, and the higher the rank
- Sorted set scores are 64-bit floating-point numbers, so integers are exact only up to 2⁵³ (News Feed ran into the same problem). With 21 bits taken, points can go up to about 2³² = 4.3 billion, far more than enough
But this also means you cannot just use ZINCRBY: after adding points, the time in the low bits also has to be replaced with the time of this award. So store each person’s points separately in a hash, and use a Lua script to “add the points, compute the new score, write it to the sorted set” atomically (Flash Sale Ticketing used the same approach).
If the business rule is “same points, same rank” (1, 2, 2, 4), the rank becomes “the number of people with more points than me + 1”: use ZCOUNT to count the members whose score is greater than (my points + 1) × 2²¹.
Redis is not the ledger
The source of truth for points is the points ledger in the database: every award records its source (which quiz, which talk), the source has a unique key, and the same quiz never awards points twice (Idempotency post). The leaderboard is derived from the ledger:
flowchart LR
Q[Quiz passed, talk attended] --> L[(Points ledger<br/>unique source)]
L -->|outbox| K[[Kafka<br/>points-awarded]]
K --> U["Leaderboard updater<br/>Lua: dedupe, add points, compute score"]
U --> R[(Redis<br/>this week's hash and sorted set)]
L -.->|rebuild when Redis loses data| R
API[Leaderboard API] --> R
- Updates must be idempotent: Kafka is at-least-once, so the same points event may be processed twice, and
HINCRBYis not idempotent. The Lua script first doesSET NXon the ledger ID and skips anything already processed - It can be rebuilt: when Redis loses data, aggregate the ledger by week: each member’s total points for the week and the time of their latest award give the same score
- The week is decided by when the event happened: a quiz submitted at 23:59:59 on Sunday and processed at 00:00:01 on Monday still belongs to the previous week. The weekly leaderboard is settled only at 01:00 on Monday, leaving an hour for late events (the grace period from the Batch and Stream Processing post). Week boundaries follow the platform’s time zone (Asia/Taipei)
Reads
- Top 100: everyone sees the same list, so cache it in the application’s memory for 5 seconds, which keeps the 50 requests a second from all hitting the same hot key (Caching post)
- My rank: different for each person, so query
ZREVRANKdirectly - Friend rankings: at most 500 friends; use a pipeline to fetch all friends’ scores at once and sort them in the application
- Ranks far down the list: for a member ranked around 5,000,000th, instead of showing “rank 4,999,872”, show “ahead of 50% of members”. Percentiles can be computed from a histogram of the points distribution, with no need for an exact rank
When the scale grows further
A single sorted set is limited by one node’s memory and CPU. When membership grows to hundreds of millions:
- Shard by member: N sorted sets, each holding a share of the members. The top 100 is the merge of the top 100 from each of the N shards; an exact rank takes one
ZCOUNTon each of the N shards, added up - Rank only the top exactly: put only members whose points exceed a threshold into the sorted set, and show everyone else a percentile
Trending talks: buckets plus time decay
“Sign-ups in the last 24 hours” is a sliding window. The approach is one bucket per hour:
- When each sign-up is confirmed, run
ZINCRBY lectureId 1on the sorted set for the current hour; each bucket is set to expire after 25 hours - Every minute, a scheduled job merges the last 24 buckets with weights (
ZUNIONSTORE ... WEIGHTS) into one result. The weights decay with time; for example, the bucket from k hours ago has weight 0.9ᵏ - Reads go straight to the merged result, and the top 20 is also cached for 1 minute
The computation runs only in the scheduled job, once a minute, no matter how many reads there are. This is the sliding window from the Batch and Stream Processing post, approximated with buckets.
Comparing options
| Decision | Choice | Rejected alternatives and why |
|---|---|---|
| Data structure for ranking | Redis sorted set | SQL COUNT(*): slow for members ranked low; computing every rank in a periodic batch: ranks are not real time |
| Tie rule | Encode the time in the low bits of the score | Order by member name: random to users; shared ranks: you have to agree with the business on how to split the rewards |
| Source of truth | The points ledger in the database; Redis can be rebuilt | Only in Redis: points lost in a failover cannot be recovered |
| Update path | Ledger → Kafka → Lua (deduplication) | Writing to Redis synchronously in the API: cannot stay consistent with the database transaction |
| Trending talks | Hourly buckets + weighted merge | Computing on every read: cost grows with the number of reads; total sign-ups only: old popular talks stay on the list forever |
In Java
1. The points ledger
CREATE TABLE point_ledger (
id BIGINT PRIMARY KEY,
member_id BIGINT NOT NULL,
source_type VARCHAR(32) NOT NULL, -- QUIZ_PASSED, LECTURE_ATTENDED
source_id BIGINT NOT NULL,
points INT NOT NULL,
occurred_at TIMESTAMP(3) NOT NULL,
UNIQUE KEY uk_source (member_id, source_type, source_id),
KEY idx_occurred (occurred_at)
);The server computes points from the source; it never accepts a score sent by the client.
2. Updating the leaderboard
@Component
public class WeeklyLeaderboard {
static final ZoneId PLATFORM_ZONE = ZoneId.of("Asia/Taipei");
private static final long TIE_BITS = 1L << 21; // 2,097,152 > seconds in a week
// KEYS[1] processed ledger ID, KEYS[2] points hash, KEYS[3] leaderboard sorted set
// ARGV[1] member ID, ARGV[2] points this time, ARGV[3] seconds left until the end of the week, ARGV[4] TTL of the dedup record in seconds
private static final RedisScript<Long> AWARD = RedisScript.of("""
if redis.call('SET', KEYS[1], '1', 'NX', 'EX', ARGV[4]) == false then
return -1
end
local points = redis.call('HINCRBY', KEYS[2], ARGV[1], ARGV[2])
local remaining = tonumber(ARGV[3])
local old = redis.call('ZSCORE', KEYS[3], ARGV[1])
if old then
remaining = math.min(remaining, tonumber(old) % 2097152) -- events out of order: keep the later time
end
redis.call('ZADD', KEYS[3], points * 2097152 + remaining, ARGV[1])
return points
""", Long.class);
private final StringRedisTemplate redis;
public WeeklyLeaderboard(StringRedisTemplate redis) {
this.redis = redis;
}
@KafkaListener(topics = "points-awarded", groupId = "weekly-leaderboard")
public void onAwarded(PointsAwarded event) {
Week week = Week.of(event.occurredAt()); // by when the event happened, not when it is processed
long remaining = Duration.between(event.occurredAt(), week.end()).toSeconds();
String tag = "{lb:" + week.id() + "}"; // e.g. {lb:2026-W48}: keys for the same week share a slot
redis.execute(AWARD,
List.of(tag + ":applied:" + event.ledgerId(), tag + ":points", tag + ":rank"),
Long.toString(event.memberId()), Integer.toString(event.points()),
Long.toString(remaining), Long.toString(Duration.ofHours(1).toSeconds()));
}
public List<RankedMember> top(Week week, int n) {
Set<ZSetOperations.TypedTuple<String>> tuples =
redis.opsForZSet().reverseRangeWithScores("{lb:" + week.id() + "}:rank", 0, n - 1);
List<RankedMember> result = new ArrayList<>();
int rank = 1;
for (ZSetOperations.TypedTuple<String> t : tuples) {
long points = t.getScore().longValue() / TIE_BITS; // drop the time in the low bits
result.add(new RankedMember(rank++, Long.parseLong(t.getValue()), points));
}
return result;
}
public OptionalLong rankOf(Week week, long memberId) {
Long zeroBased = redis.opsForZSet().reverseRank("{lb:" + week.id() + "}:rank", Long.toString(memberId));
return zeroBased == null ? OptionalLong.empty() : OptionalLong.of(zeroBased + 1);
}
public record Week(String id, Instant end) {
static Week of(Instant at) {
LocalDate date = at.atZone(PLATFORM_ZONE).toLocalDate();
LocalDate monday = date.with(DayOfWeek.MONDAY);
String id = "%d-W%02d".formatted(date.get(IsoFields.WEEK_BASED_YEAR), date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
return new Week(id, monday.plusWeeks(1).atStartOfDay(PLATFORM_ZONE).toInstant());
}
}
}- The week ID uses the ISO week (
IsoFields.WEEK_BASED_YEAR), not the calendar year: December 28, 2026 belongs to 2026-W53, and so does January 1, 2027. A week ID built from the calendar year splits the week that spans the new year into two - Dedup records are kept for only 1 hour: Kafka redeliveries (a consumer crash, a rebalance) usually happen within a few minutes. At 10 million awards a day, keeping them for 14 days would pile up over 100 million keys and more than 10 GB, and because of the hash tag they would all sit on the same node, bigger than the leaderboard itself. To reprocess older events (after resetting offsets, for example), do not replay the events; rebuild the week from the ledger instead
- When events arrive out of order (for example, one award succeeds later on a retry), the low bits keep the later time, which matches a rebuild from the ledger with
MAX(occurred_at) - After the weekly leaderboard is settled, set it to expire, and save the top 100 back to the database
3. Friend rankings
public List<FriendRank> friendsOf(Week week, long memberId, List<Long> friendIds) {
String key = "{lb:" + week.id() + "}:rank";
List<Long> ids = new ArrayList<>(friendIds);
ids.add(memberId);
List<Object> scores = redis.executePipelined(new SessionCallback<Object>() {
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Object execute(RedisOperations operations) {
for (Long id : ids) {
operations.opsForZSet().score(key, Long.toString(id));
}
return null;
}
});
List<FriendRank> ranks = new ArrayList<>();
for (int i = 0; i < ids.size(); i++) {
Double score = (Double) scores.get(i);
ranks.add(new FriendRank(ids.get(i), score == null ? 0 : (long) (score / 2097152), score == null ? -1 : score));
}
ranks.sort(Comparator.comparingDouble(FriendRank::sortKey).reversed());
return ranks;
}The caller gets the friend list from the friend service. It is capped (500 people), so a pipeline fetches all the scores in one round trip.
4. Trending talks: a weighted merge of the last 24 buckets
@Component
public class TrendingLectures {
private static final DateTimeFormatter HOUR = DateTimeFormatter.ofPattern("yyyyMMddHH");
// KEYS[1] result, KEYS[2..] hourly buckets; ARGV holds each bucket's weight, in order
private static final RedisScript<Long> MERGE = RedisScript.of("""
local args = {'ZUNIONSTORE', KEYS[1], #KEYS - 1}
for i = 2, #KEYS do table.insert(args, KEYS[i]) end
table.insert(args, 'WEIGHTS')
for i = 1, #ARGV do table.insert(args, ARGV[i]) end
redis.call(unpack(args))
redis.call('EXPIRE', KEYS[1], 600)
return #KEYS - 1
""", Long.class);
private final StringRedisTemplate redis;
public TrendingLectures(StringRedisTemplate redis) {
this.redis = redis;
}
public void onRegistrationConfirmed(long lectureId, Instant at) {
String bucket = "{trend}:" + HOUR.format(at.atZone(WeeklyLeaderboard.PLATFORM_ZONE));
redis.opsForZSet().incrementScore(bucket, Long.toString(lectureId), 1);
redis.expire(bucket, Duration.ofHours(25));
}
@Scheduled(cron = "0 * * * * *")
public void merge() {
ZonedDateTime now = ZonedDateTime.now(WeeklyLeaderboard.PLATFORM_ZONE);
List<String> keys = new ArrayList<>(List.of("{trend}:current"));
List<String> weights = new ArrayList<>();
for (int k = 0; k < 24; k++) {
keys.add("{trend}:" + HOUR.format(now.minusHours(k)));
weights.add(Double.toString(Math.pow(0.9, k))); // the older the sign-ups, the lower the weight
}
redis.execute(MERGE, keys, weights.toArray());
}
}ZUNIONSTOREtreats a bucket that does not exist as an empty set, so hours with no sign-ups, right after launch or late at night, do not cause errors- The merged result is replaced as a whole, so readers never see a half-finished merge
- Every server runs this scheduled job. The results are the same, so it does no harm, but it wastes resources; to run it on only one server, use ShedLock from the Distributed Locks post
The code above is written from the official documentation for Spring Boot 4.1, Spring Data Redis 4.1 (
RedisScript,executePipelined), Spring for Apache Kafka, and Java 21 (IsoFields), and has not been compiled or run.PointsAwarded,RankedMember, andFriendRankare illustrative types.
Pitfalls and gotchas
- Breaking ties by member name: who wins a reward depends on the lexicographic order of member IDs, which leads to disputes
- Still using
ZINCRBYafter encoding the time into the score: the times in the low bits get added together, and the order is scrambled - Scores above 2⁵³: the floating-point number loses precision, and neighboring scores become equal
- Deciding the week by processing time: points from the last moment of the week get counted in the next week
- Building week IDs from the calendar year across a new year: the same week is split into two leaderboards
- Redis as the only record: a failover loses a few seconds of points, and they cannot be recovered
- Non-idempotent updates: a redelivered event adds the points twice
- Computing the trending list on every read: the more reads, the higher the Redis CPU
Threat model
| STRIDE | Threat | On the talk platform | Defense |
|---|---|---|---|
| Spoofing | Fake accounts farming points | Registering many accounts to attend free talks and submit quizzes, then concentrating the points in one account; signing up with fake accounts to push a talk up the trending list | Leaderboards with rewards require verified accounts; the trending list counts only confirmed sign-ups, once per member per talk (8-5) |
| Tampering | Client-reported scores; resent points requests | Editing a “quiz passed, 100 points” request; submitting the same quiz 50 times | Points are computed only by the server, from the source; the ledger’s unique key on the source |
| Repudiation | Rank disputes | A member insists “I clearly got there before them” | The ledger keeps the source and time of every award, so ranks can be recomputed |
| Information disclosure | The leaderboard exposes personal data; enumerating ranks | The leaderboard shows real names; a “look up any member’s rank” API is used to track a specific person’s learning | Show nicknames only, and let members choose not to be public; the rank API can look up only your own rank and the public top 100 |
| Denial of service | Expensive range queries | GET /leaderboard?limit=10000000 makes Redis return the whole leaderboard |
A cap on page size; the top 100 is read from the cache |
| Elevation of privilege | Adjusting points in the back-office tool | An insider adds points for themselves or a friend | Point adjustments are also written to the ledger, with “manual adjustment” as the source, and need two-person review and an audit log entry |
When to use it, and when not to
- Use SQL: up to a few hundred thousand people in the ranking, or you need only the top N, not everyone’s exact rank
- Use a Redis sorted set: you need real-time personal ranks, and the number of people fits within one node’s capacity
- Shard or approximate: when the number reaches hundreds of millions, or one node cannot keep up with the writes; first ask the business whether everyone really needs an exact rank
- Periodic batch computation: when updating ranks once a day is enough, such as a monthly contribution ranking
References
- Redis Documentation — Sorted sets,
ZUNIONSTORE,ZREVRANK: https://redis.io/docs/latest/develop/data-types/sorted-sets/ - William Pugh, “Skip Lists: A Probabilistic Alternative to Balanced Trees”, Communications of the ACM, 1990
- Spring Data Redis Reference — Scripting, Pipelining: https://docs.spring.io/spring-data/redis/reference/
- Java SE API —
java.time.temporal.IsoFields - Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments