Design a Real-Time Gaming Leaderboard Engine
System DesignModel answerLast updated
Architect a high-throughput, low-latency leaderboard platform handling tens of millions of active players and millions of concurrent score updates.
Architect a scalable backend system for a competitive mobile gaming application with 50 million Daily Active Users (DAU). The platform must handle continuous high-frequency score modifications while maintaining accurate global rankings.
Requirements
Functional Requirements
updateScore(userId, score): Record a new score achieved by a user.getTopPlayers(k): Return the list of top $k$ ranked players globally (where $k \le 1000$).getRank(userId): Return the current global rank and score for a specific player.getNearbyPlayers(userId, k): Return the $k$ players positioned directly above and below a given user in rank.
Non-Functional Requirements
- High Write Throughput: The system must sustain peak workloads of 1–2 million score updates per second globally.
- Low Latency Reads: Top-tier leaderboards and rank lookups must respond within tens of milliseconds (99th percentile under 50ms).
- Scalability & Availability: The architecture must scale linearly and remain highly available.
- Data Integrity & Real-Time Accuracy: Minor rank propagation delays (up to a few seconds) are acceptable (eventual consistency), but data must be durable against crashes.
Key Deliverables
- Data Model & Storage Engine Selection: Select appropriate data structures and persistent storage solutions, detailing trade-offs.
- High-Level System Architecture: Diagram/outline component interactions from ingestion to serving reads.
- Sharding & Partitioning Strategy: Explain how data is distributed across nodes to solve both compute and write bottlenecks for global ranks.
- API Specification: Define endpoints, payloads, and idempotency guarantees.
Hints
Hint 1
Calculate total memory footprint vs. network/CPU bandwidth. The core bottleneck is often write IOPS and network fan-out, not memory storage.
Hint 2
Consider how to handle global rank calculations across multiple partitioned nodes without requiring expensive cross-node synchronization.
Hint 3
Distinguish between the fast in-memory ranking index and the durable persistent storage of truth.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & Scale Estimation
Traffic & Volume Estimates
- Active Players (DAU): 50 Million. Total registered players: ~100 Million.
- Peak Write Rate: 50M users playing multiple short matches per day generates average traffic of ~500K updates/sec, peaking at 1.5M to 2M updates/sec.
- Read Rate: High. Opening app lobbies, finishing matches, and browsing friends' ranks generates ~200K queries/sec for top-ranks and nearby positions.
Storage Estimates
- Each player entry requires:
userId(16 bytes UUID) +score(8 bytes integer/float) + metadata/timestamps (16 bytes) ≈ 40 bytes. - Total payload per player in an indexed data structure (including pointer overhead): ~100 bytes.
- 100 Million players $\times$ 100 bytes = ~10 GB memory total.
- Takeaway: Memory capacity is not the bottleneck; CPU throughput, network bandwidth, and lock contention during score updates are the critical constraints.
2. API Design
Ingest Score Update
POST /v1/leaderboards/{boardId}/scores
// Request Payload
{
"userId": "usr_99x82a",
"score": 14500,
"matchId": "mtch_771029",
"timestamp": 1718040000
}
Response: 202 Accepted (Processed asynchronously).
- Idempotency:
matchIdprevents duplicate processing of retried requests.
Get Top $k$ Players
GET /v1/leaderboards/{boardId}/top?limit=100
// Response
{
"boardId": "season_5_global",
"rankings": [
{ "rank": 1, "userId": "usr_001", "score": 98500 },
{ "rank": 2, "userId": "usr_304", "score": 97120 }
]
}
Get User Rank & Nearby Competitors
GET /v1/leaderboards/{boardId}/users/{userId}/rank
GET /v1/leaderboards/{boardId}/users/{userId}/nearby?range=5
3. Data Storage & Indexing Strategy
Why Relational Databases Fail at Scale
A traditional B-Tree indexed SQL database (SELECT rank FROM scores WHERE score > user_score) requires $O(N)$ scanning or frequent index splits. Executing millions of write updates per second causes massive log contention, row locking, and unmanageable disk I/O.
In-Memory Ranking Store: Redis Sorted Sets (ZSET)
Redis ZSETs rely on a combination of a Skip List and a Hash Map, offering optimal performance primitives:
| Operation | Command | Complexity | Description |
|---|---|---|---|
| Update Score | ZADD / ZINCRBY | $O(\log N)$ | Modifies node position in skip list |
| Fetch Top $K$ | ZREVRANGE 0 K-1 | $O(\log N + K)$ | Traverses skip list from highest head |
| Exact Rank | ZREVRANK | $O(\log N)$ | Uses skip list span counts |
| Range by Score | ZRANGEBYSCORE | $O(\log N + K)$ | Fetches nearby relative elements |
Tie-Breaking Strategy
When scores match, early achievers should rank higher. We construct a 64-bit composite score: $$\text{Composite Score} = (\text{Raw Score} \ll 32) + (\text{MAX_TIMESTAMP} - \text{AchievedTimestamp})$$ This guarantees that equal raw scores yield a higher composite score for earlier timestamps without secondary lookups.
Persistence Strategy (Source of Truth)
Redis is treated as an ephemeral in-memory index. An append-only distributed NoSQL store (such as Apache Cassandra or Amazon DynamoDB) serves as the durable storage layer.
Schema (user_scores table):
partition_key: board_id, clustering_key: user_id
Attributes: score, updated_at, last_match_id
4. High-Level Architecture
+--------------------+
| Mobile Client |
+---------+----------+
|
[ API Gateway / CDN ]
|
+-----------------+-----------------+
| |
(Write Path) (Read Path)
| |
v v
+------------------+ +-------------------+
| Ingest API Svc | | Leaderboard Read |
+--------+---------+ | Service |
| +---------+---------+
v |
+------------------+ |
| Kafka Cluster | |
| (by userId hash) | |
+--------+---------+ |
| |
v |
+------------------+ |
| Stream Workers | |
| (Batch/Coalesce) | |
+----+--------+----+ |
| | |
| +------------+ |
v v v
+--------------+ +------------------------------------+
| Cassandra DB | | Redis ZSET Cluster |
| (Durable) | | (Hash-Sharded / Merged Read Layer) |
+--------------+ +------------------------------------+
Components Walkthrough
- Ingest API: Receives score submission, authenticates request tokens, validates payload, and publishes an event to Kafka. Returns
202 Acceptedimmediately. - Kafka Event Buffer: Partitioned by
userId. Buffers rapid-fire score entries to protect downstream datastores from transient spikes. - Stream Processing Workers:
- Reads mini-batches (e.g., 100ms windows).
- Write Coalescing: If a player submits 5 updates within 100ms, only the highest/latest score is dispatched.
- Writes asynchronously to Cassandra for durability.
- Issues pipelined
ZADDcommands to Redis.
- Read Service & Top-K Local Cache: Serves player queries. Top-100 entries are cached in local API service memory and refreshed every 500ms to offload Redis traffic.
5. Partitioning Strategy (Scaling Beyond a Single Redis Node)
A single Redis master node maxes out at ~100K–200K non-pipelined operations per second. To sustain 2M writes/sec, data must be partitioned across nodes.
Option A: Score-Range Sharding (Not Recommended)
Sharding nodes by score ranges (e.g., Node 1: 0–1,000; Node 2: 1,001–2,000) makes calculating overall global rank easier, but creates severe issues:
- Extreme Write Hotspots: Most players cluster in mid-to-low score ranges.
- Costly Cross-Node Moves: Every time a player's score crosses a range boundary, a multi-step cross-shard transaction is required.
Option B: Hash Sharding by userId (Recommended Solution)
Distribute players deterministically across $N$ shards using hash(userId) % N.
[ Write Score ] [ Get Global Rank ]
| |
hash(userId) % N Compute user score S
| from user's own shard
v |
+---------------+ Scatter ZCOUNT(S, +inf)
| Target Shard | across ALL N shards
+---------------+ |
Sum counts across shards:
Global Rank = 1 + Σ counts
How Operations Work under Hash-Sharding:
-
Score Update (
updateScore):- Deterministically routed to a single Redis shard based on
hash(userId) % N. - Latency: $O(\log(M))$ where $M = N / \text{shards}$. Extremely fast.
- Deterministically routed to a single Redis shard based on
-
Fetching Top $K$ Players (
getTopPlayers):- Scatter-Gather Pattern: The Read API requests
ZREVRANGE 0 K-1from all $N$ shards simultaneously. - Merges $N \times K$ returned elements in memory and sorts them to find the overall global top $K$.
- Performance Cost: Fetching $10 \text{ shards} \times 100 \text{ items} = 1,000 \text{ items}$. Sorting 1,000 items takes $<1\text{ms}$. Results are cached at the edge/in-memory for 500ms.
- Scatter-Gather Pattern: The Read API requests
-
Fetching Exact Rank (
getRank):- Step 1: Query the specific shard for
userIdto obtain their score $S$. - Step 2: Scatter a
ZCOUNT shard_i (S +inf]command across all $N$ shards in parallel to count how many players have a higher score than $S$. - Step 3: $\text{Global Rank} = 1 + \sum_{i=1}^{N} \text{count}_i$.
- Latency: Executed via fast parallel non-blocking Redis operations (takes ~2–5ms).
- Step 1: Query the specific shard for
-
Fetching Nearby Players (
getNearbyPlayers):- Get target user's score $S$.
- Fetch $K$ entries above and below $S$ from all shards using
ZRANGEBYSCORE. - Scatter-gather merge the candidates, rank them relative to the main user's rank, and return the closest window.
6. Micro-Optimizations & Edge Cases
Long-Tail Tiered Ranking (Approximate Ranks for Lower Tier)
For players outside the top 100,000, displaying exact rank 3,421,902 versus 3,421,905 provides little user value.
- Optimization: Maintain a coarse Histogram of Bucket Counts across the network (e.g., score ranges of width 100).
- For long-tail players, compute rank via cumulative bucket sums + local shard offset. This reduces read fan-out queries for non-competitive tiers.
Handling Leaderboard Resets & Seasons
- Append season identifier to key namespaces (e.g.,
lb_global_season_05). - Switch reads/writes to the new key at midnight UTC via dynamic configuration.
- Archive snapshot of previous season's final Redis scores to cold storage (S3/Parquet) for historical lookup.
7. Trade-offs Summary
| Architectural Decision | Trade-off Made | Rationale / Benefit |
|---|---|---|
| Hash-Sharded Redis vs. Single Redis Node | Increases read fan-out complexity for rank calculation | Eliminates write bottlenecks and allows linear memory/throughput horizontal scaling |
| Async Kafka Pipeline vs. Direct Redis Write | Introduced ~100–500ms eventual consistency lag | Absorbs massive write spikes; enables batching and deduplication before hitting index |
| Redis ZSET vs. Relational Index | Data lost on crash if unpersisted; secondary DB required | Redis skip lists offer $O(\log N)$ updates vs $O(N)$ index locks in SQL |