NOTE

Designing a Leaderboard System

A ranking system starts with requirements and presentation, followed by ranking updates and queries. These notes examine implementation and maintenance using approaches such as sorted sets.

System DesignCreated Updated 3 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is the Requirement?

  • Requirement ticket
  • Prototype

2. Why Build It?

  • What problem does it solve?
  • Can the requirement be omitted?
  • Can the requirement be simplified?

3. Requirement Analysis

Use examples from the system to understand the concepts.

3.1. What Does the Existing Flow Look Like?

Ask operations or product to demonstrate the flow. Review read/write flows and back-office / user-facing flows.

3.2. What Does the New Flow Look Like?

  1. Roles in the system and what each role can do
  2. What the flow looks like when each role performs an action

3.3. QPS Estimation

Use variables to estimate the number of participants and the number of hotspot objects online. The public version does not retain real production counts or capacity.

4. Design

4.1. Storage Design

Overwrite: zadd 1_2_3 1 member
Increment or decrement: zincrby 1_2_3 5 member
Read by descending score: zrevrange 1_2_3 0 -1 withscores

4.2. API Design


ReadRankReq {
    business_id
    rank_scope
    start
    limit
    optional timestamp
    optional self_member
    optional order_type
}

ReadRankRsp {
    rank_list[{member_id, score, rank}]
    optional self_rank
    optional total
}

UpdateRankReq {
    business_id
    rank_scope
    operations[{member_id, score, op_type}]
    request_id   // idempotency
}

UpdateRankRsp {
    results[{member_id, score}]
}

DeleteRankMemberReq {
    business_id
    rank_scope
    member_ids[]
}

4.2.1. Read Leaderboard Details by Rank

  • req
    • appid
    • rankid
    • subrankid
    • start
    • limit
    • me
  • rsp
    • list
      • member
      • score
    • me
      • member
      • score

4.2.2. Update Leaderboard

  • req
    • appid
    • rankid
    • subrankid
    • list
      • member
      • score
      • orderNo (idempotency)
      • opType (overwrite / increment)
  • rsp
    • list
      • member
      • score

4.3. Architecture Design

Consider security, high concurrency, high availability, and maintainability together.

  1. Split into microservices
  2. Draw the application architecture diagram
  3. Draw the sequence diagram

4.4. Code Design

4.4.1. update

pipeline + EvalSha Lua + fallback Eval Lua.

The score is score + '.' + 9 9999 9999 9999 - current timestamp (1 6523 5401 7172), so that when scores are equal, the member who reached the score first ranks higher.

function update(rank_key, member, score, request_id, op_type, ttl):
    atomically:
        if request_id has been processed:
            return previous result
        mark request_id processed with ttl
        if op_type == SET:
            ZADD rank_key score member
        else if op_type == INCR:
            ZINCRBY rank_key score member
        if rank_key is newly created:
            EXPIRE rank_key ttl
        return ZSCORE rank_key member

4.4.2. get

  • getByRank
// Sort by score in descending order
zrevrange 1_2_3 start start+limit-1 withscores
// Sort by score in ascending order
zrange 1_2_3 start start+limit-1 withscores

Remove the fractional part: strings.Split("", ".")[0]

  • getByMember
function getByMember(rank_key, member, order):
    score = ZSCORE(rank_key, member)
    if score does not exist:
        return not_found
    rank = order == ASC ? ZRANK(rank_key, member) : ZREVRANK(rank_key, member)
    return rank, score

getMember and getRank can also be wrapped in Lua.

4.5. Idempotency Design

Add an orderNo to writes, generated by the business caller, to keep retries idempotent. Wrap it in a Lua script together with the leaderboard update.

4.6. Handling High Concurrency

Leaderboard characteristics:

  1. Only the top entries need to be displayed, not the entire leaderboard.
  2. The workload is read-heavy and write-light.

4.6.1. High-Concurrency Writes

Use a message queue to absorb bursts. Since the workload is usually read-heavy, writes are not normally the first optimization target.

4.6.2. High-Concurrency Reads

The display path reads Top N, the user’s score and rank, then aggregates profile data.

Profile data is suitable for a read-through local cache: when aggregating profiles, read local memory first; on a miss, fetch the profile from the user-profile service and cache it. Since profiles change infrequently, expiration can handle refreshes.

Leaderboards and individual scores change frequently, so cache hit rates and consistency need separate evaluation. Benchmark a single key first; if Redis meets the requirements, avoid over-optimizing.

Consider a local hotspot cache for extremely popular leaderboards.

4.7. Hot Leaderboards

  • Detect hot keys
    1. Preconfigure known hotspots.
    2. Monitor Top-N keys by access volume.
  • Handle hot keys
    • Let Redis handle ordinary hotspots.
    • For extreme hotspots, dual-write Redis and a local in-memory read copy.

General flow:

  1. Optionally disable leaderboards for hotspot objects that do not need them.
  2. For hotspot objects that do need leaderboards, write Redis first and update local cache through replayable events.
  3. On node startup, load a snapshot from Redis, replay from the event position, and only serve the local copy after catching up.
  4. Serve Top N from local cache; query personal rank from Redis.
  5. Query ordinary leaderboards directly from Redis.

4.8. Very Large Leaderboards

  • Detect large keys by configuration or member-count monitoring.
  • Split large leaderboards.
    • Write: hash the member to a suffix and write to a zset shard.
    • Read:
      • Option 1: query Top N from all shards in parallel, then merge and sort in memory; fresher results, but lower efficiency.
      • Option 2: periodically aggregate Top N from all shards and cache the results as a read-only view; less timely, but more efficient.
  • A user’s score and rank may fall outside the top entries. A separate personal score/rank read model can prevent personal queries from continually hitting the large leaderboard key.

4.9. Reconciliation

The business side retains score-change records, and the leaderboard side retains processed-update records or a checkpoint.

Periodically compare a recent safe window. If a difference is found, resend the missing update and rely on request_id for idempotent repair.

5. Effort Estimation

  • Estimate one API at roughly 0.5–2 days.

6. Development

7. Testing

  • Redis: update throughput, Top-N query throughput, personal-rank query throughput
  • Message queue: per-partition consumption throughput and replay speed
  • Service: local sorted-set queries, Redis queries, hotspot replay time after startup

8. Release

  1. Release checklist
  2. Deployment

9. Operations

9.1. Redis Global Replication

Refer to the multi-region replication discussion in the frequency-control note.

10. Optimization

11. Summary

  1. Compare solutions
  2. Problems encountered and how they were solved
  3. Design highlights
    • Why a particular component was introduced
  4. Pain points and improvements
    • How to handle an N-fold increase in request volume and data volume
    • Refactoring

12. Reference

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub