medium general · part of Practice Questions · Senior SWE Roadmap
Requirements to clarify
- Functional: submit a score, retrieve a player’s current rank, retrieve the top-N players — all updating in near real-time.
- Non-functional: very high write volume (scores updating constantly during active play), rank queries must be fast, “top N” and “rank of player X” are both common queries.
Core components
- Sorted set data structure: a data structure that keeps elements ordered by score with O(log n) insert/update and O(log n) rank lookup (e.g., Redis’s sorted set, backed by a skip list) is the natural fit — far better than re-sorting an array on every update.
- Sharding for scale: for very large leaderboards (e.g., global, hundreds of millions of players), shard by a natural key (region, game mode) and maintain a smaller “top N per shard” that’s merged for a global view, rather than one giant global sorted structure.
- Real-time updates: score changes pushed to connected clients via WebSockets for a live-updating UI, rather than polling.
Key tradeoffs
- A single global sorted-set is simplest but becomes a write bottleneck at very large scale — sharding trades some implementation complexity for horizontal scalability, similar to the sharding tradeoff in other designs.