Design a Multiplayer Game Ranking System
System DesignModel answerLast updated
Build a backend that tracks player scores, displays global and friend rankings, shows a player's position with nearby competitors, and supports multiple time periods.
You're building the backend infrastructure for a competitive multiplayer game's ranking system.
Your system must handle:
-
Score submission: Accept and process score updates from active game sessions. Expect significant write traffic from thousands of concurrent players.
-
Global rankings: Retrieve the top-performing players (configurable limit, typically 10–100 entries) sorted by score.
-
Friend rankings: For any given player, show how they and their friends compare, sorted by performance.
-
Contextual positioning: Given a player, return their current rank plus a window of players immediately above and below them in the standings.
-
Time-based views: Support separate rankings for different periods—today, this week, the current competitive season, and lifetime statistics.
-
Performance requirements: Read queries for ranking displays must complete quickly even as the player population and submission rate grow large.
Your task is to design this system end-to-end. Cover the requirements (functional and scale assumptions), API contracts, storage architecture, how you'll maintain sorted rankings efficiently, handling ties between equal scores, read optimization strategies, horizontal scaling, consistency guarantees, protecting against fraudulent submissions, and operational considerations like rebuilds and archival.
Explain your reasoning for key decisions and discuss trade-offs where alternatives exist.
Hints
Hint 1
Separate durable storage of score events from the structures you use for fast rank queries—they serve different purposes
Hint 2
In-memory sorted data structures can handle millions of ranking operations per second; consider what happens when a single ranking grows beyond one machine's capacity
Hint 3
Computing friend rankings on every request is feasible when friend lists are small; compare fan-out-on-write versus fan-out-on-read
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Multiplayer Game Ranking System
1. Requirements and Scale
Functional requirements:
- Accept score updates, using the highest score per player per time window (alternatively, cumulative scoring where scores add up)
- Query top N globally (N typically 100, up to 1,000 for pagination)
- Show rankings within a player's social circle
- Display a player's current rank and nearby competitors (±10 positions)
- Maintain separate rankings: daily, weekly, seasonal, and all-time
Scale assumptions:
- 100 million registered players, 20 million daily active users
- Each active player completes ~10 sessions daily → ~200 million score events per day
- Average write rate: ~2,300/sec, peak: ~23,000/sec
- Four time windows per event means ~100,000 ranking updates/sec at peak
- Read traffic: ~50,000/sec peak, heavily skewed toward top rankings and personal rank lookups
- Target read latency: p99 under 50ms
Non-functional:
- Eventual consistency acceptable (scores visible within 1–5 seconds)
- High availability; ranking system failures shouldn't lose score data
- Tamper-resistant score validation
2. API Design
POST /api/scores
Body: { session_id, player_id, game_id, score, timestamp, signature }
Response: 202 Accepted
GET /api/rankings/{game_id}/{period}/top?limit=100
Response: [{ player_id, score, rank }, ...]
GET /api/rankings/{game_id}/{period}/players/{player_id}/context?range=10
Response: { rank, score, above: [...], below: [...] }
GET /api/rankings/{game_id}/{period}/players/{player_id}/friends?limit=50
Response: [{ player_id, score, rank }, ...]
Period format: daily-2026-11-06, weekly-2026-W45, season-fall-2026, alltime
The 202 status signals asynchronous processing—ranking updates happen outside the request path.
3. Architecture Overview
Game Servers → API Gateway → Message Queue (Kafka/Kinesis)
↓
┌───────────────┴────────────────┐
↓ ↓
Score Validator Ranking Processor
(fraud detection) (updates storage)
↓ ↓
Quarantine DB ┌──────────────┴──────────┐
↓ ↓
Durable Store (Postgres/DynamoDB) Ranking Cache (Redis)
↑
Client ← API ← CDN/Cache ← Ranking Read Service ───────────────────────┘
↑
Friends Service
Why this design:
- Message queue absorbs traffic spikes and decouples submission from processing
- Partition queue by
player_idto maintain per-player ordering - Durable store is the source of truth; ranking cache can be rebuilt
- Idempotent consumers using
session_idas deduplication key allow safe replays
4. Storage Strategy
Durable layer (PostgreSQL, Cassandra, or DynamoDB):
score_submissions: append-only log of all events (session_id, player_id, game_id, score, timestamp, validated)best_scores: materialized view per (game_id, period, player_id) → (score, achieved_at)
Ranking layer (Redis sorted sets):
- One sorted set per (game_id, period):
rank:{game_id}:{period} - Member:
player_id, score: composite ranking value (see below) - TTL on time-bounded sets (daily expires after 7 days, weekly after 8 weeks)
5. Ranking Mechanics
Redis sorted sets provide O(log N) insertion, rank lookup, and range queries—exactly what we need.
Core operations:
- Top N:
ZREVRANGE key 0 99 WITHSCORES - Player rank:
ZREVRANK key player_id - Context window:
ZREVRANGE key max(0, rank-10) rank+10
Tie-breaking: Equal scores must have deterministic ordering. Encode both score and timestamp into one value:
composite_score = game_score × 2³² + (2³² - 1 - seconds_since_epoch)
Higher game scores dominate; for ties, earlier timestamps win. This fits in a double (53-bit precision) for scores up to ~2 million. For larger scores, use coarser time granularity or handle ties in application logic.
Update semantics:
- Best-score mode:
ZADD key GT composite_score player_id(only updates if new score is higher) - Cumulative mode:
ZINCRBY key score_delta player_idplus separate timestamp storage
6. Scaling Strategies
Distributing write load:
- Shard Redis cluster by (game_id, period) so different rankings hit different nodes
- Pipeline updates to all four time windows in one request
- Each Redis node can handle 100K+ operations/sec; multiple nodes provide headroom
Handling massive rankings:
A single all-time ranking with 100M players is ~10GB—fits on one Redis node, but creates a hot key.
Option 1 (recommended for most cases): Keep one key per ranking, scale reads with replicas. Writes at 25K/sec are well within Redis capacity for a single key.
Option 2: Hash-shard each ranking into M sub-rankings (e.g., by player_id hash).
- Top N: scatter-gather top N from each shard, merge in application (M×N items)
- Exact rank: parallel
ZCOUNTacross shards for scores higher than player's score - Complexity increases; only needed for extreme write loads
Option 3: Approximate ranks for long-tail players. Compute exact ranks only for top 100K; everyone else sees "Rank ~3.2M, Top 15%" derived from score distribution histograms updated every minute.
Friend rankings:
With small friend lists (median ~100, max ~5,000), compute on-demand:
- Fetch friend IDs from friends service (cached)
- Batch
ZMSCORE key friend_id1 friend_id2 ...(one Redis call) - Sort in application: O(F log F), negligible for F < 5,000
- Cache result per (player, period) for 30–60 seconds
Fan-out-on-write (maintaining per-player friend ranking sets) multiplies write cost by average friend count—only worthwhile if friend lists are tiny and reads vastly outnumber writes.
Time windows:
Each period gets its own key. Rollover is automatic—new day's key starts empty. A background job finalizes completed periods:
- Snapshot to durable storage for awards/history
- Set expiration on Redis key
- Trigger reward distribution if needed
7. Caching and Read Optimization
Hot path optimization:
- Top 100 global rankings: refresh every 1–5 seconds, serve from CDN/edge cache
- Personal rank queries: cache per player for 5–10 seconds (stale rank is acceptable)
- Use consistent hashing for cache keys to spread load
Common mistakes to avoid:
- Don't query the durable store for every ranking read—it can't deliver sub-50ms latency at scale
- Don't try to maintain perfect real-time consistency; eventual consistency significantly simplifies the design
- Don't forget pagination cursors for top-N queries beyond the first page
8. Consistency and Trade-offs
Rankings are eventually consistent by design:
- Scores appear in rankings 1–5 seconds after submission
- Different time windows may update at slightly different times
- Personal rank might briefly lag behind global top-N
This is acceptable because:
- Players don't notice sub-second delays in ranking updates
- Perfect consistency would require distributed transactions, destroying write throughput
- The durable store provides a consistent source of truth for disputes
9. Anti-Cheat and Validation
Submission integrity:
- Game servers sign score payloads with HMAC
- Validation service checks signatures and flags anomalies (impossible scores, suspicious timing patterns)
- Quarantined scores don't update rankings until manually reviewed
Rate limiting:
- Per-player submission rate limits
- Monitor for sudden rank jumps that indicate cheating
10. Operational Concerns
Rebuilding rankings: Idempotent consumers mean you can rebuild from the durable store:
- Spin up new Redis cluster
- Stream
best_scorestable through ranking processor - Validate against current rankings
- Swap traffic atomically
Monitoring:
- Write lag (submission time to ranking visibility)
- Cache hit rates
- p99 read latency by query type
- Redis memory usage and eviction rates
Capacity planning: Each ranking window's memory = players × 100 bytes. Daily: ~2GB, all-time: ~10GB per game. Pre-shard if approaching node limits.
This architecture scales from thousands to hundreds of millions of players while maintaining fast reads and reliable writes.