Real-Time Ranking Service for Competitive Gaming Platforms
System DesignModel answerLast updated
Build a backend that handles millions of score updates per second, returns a player's exact position plus surrounding ranks in milliseconds, and supports friend-only views.
Context
You're building the core ranking infrastructure for a competitive gaming platform with a massive global player base. Players compete across thousands of different games, and they expect to see their exact standing instantly after each match. Beyond viewing the top performers, players want to know where they rank and who's directly competing with them—the handful of players just ahead and just behind.
Core Features
Your system must support:
-
Score Updates: Players submit their best performance for a particular game. Only genuine improvements should propagate through the system.
-
Rank with Context: When a player queries their standing, return their precise rank along with
kplayers ranked immediately above them andkplayers immediately below (e.g., ifk=5, show ranks 45-55 when the player is rank 50). -
Consistent Tie Resolution: When multiple players achieve identical scores, break ties in a predictable way. Earlier achievements rank higher than later ones with the same score. If timestamps also match, use player identifiers as the final discriminator.
-
Social Filtering: Players can view rankings filtered to only their friend network, showing where they stand among people they know.
Scale Constraints
- User Base: 100 million daily active players competing across 10,000 different games
- Write Traffic: System-wide peak of 100,000 score submissions per second; a single viral game might generate 40,000 writes/sec
- Read Traffic: 250,000 ranking queries per second globally; hot games see 100,000 reads/sec
- Latency Target: 99th percentile response time under 50 milliseconds for rank queries
- Consistency Model: Slight delays (1-2 seconds) are acceptable for viewing others' ranks, but a player must never see their own best score decrease
What to Address
Your design should cover:
- API contracts for submitting scores and querying ranks
- Storage and indexing choices that enable fast rank computation and range retrieval
- Tie-breaking implementation that encodes multiple sorting criteria without precision loss
- Scaling strategy for games whose traffic exceeds single-node capacity
- Friend filtering approach and the trade-offs between precomputing versus computing on demand
Hints
Hint 1
Most score submissions don't improve a player's personal best—filter aggressively before writing to expensive indexes
Hint 2
Redis sorted sets provide O(log N) rank lookup and range queries, but a single instance can't handle 40k writes/sec for one game
Hint 3
Encode score and timestamp into a single numeric value to leverage native sorted set ordering, but watch out for floating-point precision limits
Hint 4
For friend leaderboards, consider which is cheaper: writing every score update to 200+ friend-specific indexes, or reading a few hundred entries on demand
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Understanding the Scale
Before choosing technologies, translate requirements into concrete numbers:
- Data volume: 100M daily users across 10k games suggests roughly 1 billion lifetime (player, game) records. At ~100 bytes per entry in memory, that's around 100 GB—manageable in a distributed cache.
- Hot game scenario: A viral game might have 50M active players (5 GB in one sorted collection). Memory isn't the bottleneck; throughput is—40k writes/s plus 100k reads/s against a single primary exceeds typical Redis capacity.
- Write efficiency: Most submissions don't beat existing personal bests. Filtering these early dramatically reduces load on ranking indexes.
- Consistency window: 1-2 second staleness is acceptable for viewing others, but a player's own score must never appear to regress.
2. API Design
POST /v1/games/{game_id}/scores
Request: {player_id, score, idempotency_key}
Response: {current_best, is_improvement}
GET /v1/games/{game_id}/ranks/nearby
Parameters: player_id, k (default 10), scope (global|friends)
Response: {
player_rank,
entries: [{rank, player_id, score, timestamp}]
}
GET /v1/games/{game_id}/ranks/top
Parameters: n (default 100), scope (global|friends)
Response: {entries: [...]}
Key decisions:
- Server-assigned timestamps prevent clients from manipulating tie-breaks
- Idempotency keys prevent duplicate processing during retries
- For deep pagination beyond nearby context, use cursor-based approaches (
after_rank=) rather than offsets
3. Storage Architecture
Primary Store (PostgreSQL/DynamoDB/Cassandra)
player_records(game_id, player_id, season_id)
-> best_score, achieved_timestamp, version
Use conditional writes: UPDATE ... WHERE best_score < :new_score. This ensures a player's best never regresses, regardless of retry storms or event reordering. Only actual improvements generate events to downstream systems.
In-Memory Ranking Index (Redis Sorted Sets)
Key: rank:{game_id}:{season}:{partition}
Member: zero-padded player_id (fixed width)
Score: composite ranking value (see section 4)
Operations:
ZRANK player_idreturns position in O(log N)ZRANGE start_rank end_rankretrieves neighbors in O(log N + k)
Both operations complete in under 1ms, leaving 45+ ms for network, fan-out, and tail latency.
Event Stream (Kafka)
Partition by (game_id, player_id) to maintain per-player ordering. Only improvements flow through, dramatically reducing volume.
4. Tie-Breaking Mechanism
Requirement: Higher score wins → earlier timestamp wins → lower player_id wins.
Solution: Encode score and inverted time into one integer:
composite_score = (score << TIME_BITS) | (MAX_TIME - seconds_since_epoch)
Precision constraints: Redis sorted sets use IEEE 754 doubles, which guarantee integer exactness only up to 2^53.
Example allocation:
- 23 bits for score (supports values up to ~8.4 million)
- 30 bits for time (covers ~34 years at second resolution)
- Total: 53 bits
Why this works: A higher game score always produces a larger composite value regardless of timestamp. When scores match, the subtracted timestamp makes earlier achievements score higher. Redis sorted sets automatically handle the player_id tie-break through lexicographic member ordering.
Implementation detail: Store -composite_score and use ascending order (ZRANGE instead of ZREVRANGE). This makes lexicographic member ordering align with the desired player_id tie-break direction. Then rank = ZRANK(player) + 1.
5. Partitioning Hot Games
Write Filtering Layer
Before hitting ranking indexes, cache each player's current best. The conditional write in the primary store already drops non-improvements; an additional in-memory cache (per-player TTL ~5 min) absorbs the majority of the 40k writes/s.
Bucket by Score Range
Split one game's ranking into M sorted sets based on composite score ranges:
rank:{game}:{season}:bucket_0 // top tier
rank:{game}:{season}:bucket_1 // second tier
...
Choose boundaries from previous season's score distribution to balance bucket sizes. Hot buckets can be subdivided dynamically.
Rank Computation
global_rank = (sum of players in higher buckets) + rank_within_bucket
Maintain a lightweight counts service that tracks bucket sizes and their prefix sums, refreshed every few hundred milliseconds. Staleness of 1 second is within tolerance.
When nearby queries span bucket boundaries, fetch the tail of one bucket and head of the next, then merge results.
Bucket Migration
When a score improvement moves a player between buckets:
- Add to new bucket (idempotent)
- Remove from old bucket (idempotent)
Brief overlaps during migration are handled by client-side deduplication by player_id.
Read Scaling
- Serve queries from read replicas of each bucket
- Precompute top-N every 500ms and cache at the edge
- Route cold games to shared Redis clusters; only promote games above traffic thresholds to dedicated bucketed infrastructure
6. Friend Leaderboards
Fan-out on Write
Write each improvement to every friend's personal leaderboard:
- Cost: 100k improvements/s × 200 avg friends = 20M writes/s
- Memory: 200× expansion per game
- Problem: Users with thousands of friends become bottlenecks
- Most materialized views never get read
Fan-out on Read (Recommended)
- Fetch player's friend list (cached, ~200 IDs)
- Intersect with players who have scores in this game using
games_played:{player_id}sets - Pipeline
HMGETfor ~50 friends who actually play this game frombest:{game}:{season} - Sort in-memory and compute friend-relative ranks
Cost analysis:
- ~75k friend-scoped queries/s (assuming 30% of reads request friend view)
- × 50 active friends per query
- = ~4M pipelined lookups/s across the cluster
- Cache each viewer's friend leaderboard for 1-2 seconds
Decision: Fan-out on read wins. It's simpler, always consistent with source of truth, has no write amplification, and scales well within the latency budget.
7. Latency Budget Breakdown (p99 < 50ms)
| Component | Time |
|---|---|
| API gateway routing | ~5 ms |
| Bucket count lookup (cached) | <1 ms |
| Redis ZRANK + ZRANGE | ~2 ms |
| Friend path: list fetch + pipelined reads | ~10-15 ms |
| Network overhead and margin | remainder |
8. Key Design Principles
- Non-regression guarantee: Conditional writes at the source of truth, not cache-level logic
- Precision awareness: Understand floating-point limits when encoding multi-field sort keys
- Write amplification: Filter aggressively before expensive indexes; most submissions are no-ops
- Partitioning trigger: Use traffic thresholds, not game popularity, to decide when to split
- Consistency model: Distinguish between "my own view" (strongly consistent) and "viewing others" (eventual)
- Fan-out trade-offs: Materialize only what you'll actually read; compute the rest on demand
9. Monitoring and Failure Modes
Watch for:
- Bucket imbalance as player skill distributions shift
- Thundering herd on season rollover or new game launch
- Stale count services making rank computations drift beyond tolerance
- Hot players (streamers, celebrities) creating localized hotspots in specific buckets
Common mistakes candidates make:
- Trying to scale a single sorted set beyond one node's capacity without partitioning
- Using offset-based pagination for deep queries (O(N) operation)
- Relying on client-provided timestamps for tie-breaking (enables cheating)
- Materializing friend leaderboards for all player-game pairs (massive waste)
- Forgetting that Redis
ZADDwithoutGTflag allows score regression