Designing a Real-Time Leaderboard
Difficulty: Beginner Topics: Redis Sorted Sets, Sharding, Real-Time Updates Asked at: Dream11, Riot Games, Amazon, Google · Prerequisites: Caching
1. Understanding the Problem
You’re building a game or competition with millions of players. Players earn scores, and you need to show a ranked leaderboard in real-time. Anyone can check their rank, see the top players, or see who’s around them - all in under 50ms.
Real examples: Dream11 fantasy cricket (live scoring), Riot Games ranked mode (100M+ players), Duolingo weekly leaderboards, Strava segments.
2. Naive First Cut
flowchart LR
GAME["Game Server"]
DB[("DB<br/>players table")]
USER["Player"]
GAME --> DB
USER --> DB
Store scores in a SQL table. Query rankings with ORDER BY score DESC.
-- Get top 10
SELECT * FROM players ORDER BY score DESC LIMIT 10;
-- Get my rank
SELECT COUNT(*) + 1 FROM players WHERE score > (SELECT score FROM players WHERE id = 42);
Why this breaks:
ORDER BY score DESCon 10M rows = full table sort every query
💡 The problem is that the work scales with the whole table rather than with the 100 rows you asked for, so the query gets slower as the game gets more popular. Learn more →- “My rank” requires counting ALL players with higher scores = O(N) per query
- At 100K rank queries/sec during a live event, the database melts
- Every score update reshuffles the index - write-heavy workloads degrade reads
- No way to serve “ranks around me” efficiently without scanning
We need a data structure that keeps players sorted automatically and answers rank queries in O(log N), not O(N).
3. Prior Art We’re Drawing From
- Redis Sorted Sets - Skip-list backed sorted set giving O(log N) for all rank operations. The de-facto standard for real-time leaderboards. Used by Dream11, Riot Games, and most gaming platforms. (Redis documentation)
- Riot Games Leaderboard - Handles 100M+ ranked players across multiple regions with composite scoring (MMR + LP). Uses Redis with regional sharding. (Riot Engineering)
💡 MMR (matchmaking rating) and LP (league points) are two separate ranking numbers Riot tracks. “Composite” means folding both into one sortable score, because a sorted set can only order by one number. - Discord Activity Status - Real-time presence and activity leaderboards for millions of concurrent users using Redis pub/sub + sorted sets. (Discord Engineering)
💡 Redis Pub/Sub broadcasts a message to whoever is subscribed at that moment and stores nothing for later. That is fine for “your rank changed” and useless as a record of what happened.
4. Functional Requirements
Core (Top 3)
- Update a player’s score - when a player completes an action (wins a match, answers a question), their score changes
- Get top N players - show the leaderboard: top 10, top 100, etc.
- Get a player’s rank - “what position am I?” among all players
Below the Line
- Get players around a specific rank (e.g., rank 99–101)
- Multiple leaderboards (daily, weekly, all-time)
- Real-time push updates (WebSocket) when ranks change
💡 Worth flagging: Deep Dive 4 ends up recommending WebSocket push anyway, and it appears in the final architecture. Scope moved during the design, which is normal - but it moved without being called out. - Anti-cheat validation
5. Non-Functional Requirements
| NFR (non-functional requirement) | Target |
|---|---|
| Latency | < 50ms for rank queries and score updates |
| Throughput | 50K score updates/sec + 100K rank reads/sec during live events |
| Availability | 99.99% - leaderboard is the main engagement feature |
| Scale | 10M+ players per leaderboard |
6. Scale Estimation (Back-of-Envelope)
- Users: 10M players, 1M concurrent during live events
- Write QPS: 50K score updates/sec during live events
💡 QPS is queries (here, writes) per second. 50,000 writes a second is the number that rules out a relational table and forces an in-memory structure, so it is worth holding on to. Learn more → - Read QPS: 100K rank queries/sec (leaderboard page loads)
- Storage: ~6GB in Redis for 10M entries (key + score + overhead)
7. Core Entities
- Player - user with a unique ID and a current score
- Score - numeric value representing the player’s performance
- Leaderboard - a named sorted collection (e.g.,
leaderboard:weekly:2026-W26) - Rank - player’s position (1 = highest score)
8. API / System Interface
POST /v1/scores
Body: { playerId, score, gameId }
Response: 200 { newRank: 1547 }
GET /v1/leaderboard?top=100
Response: [{ playerId, score, rank }, ...]
GET /v1/leaderboard/rank?playerId=player_42
Response: { rank: 1547, score: 1500 }
GET /v1/leaderboard/around?playerId=player_42&range=5
Response: [5 above, player_42, 5 below] with ranks
Security note: Score updates should only come from trusted game servers (server-to-server auth), never directly from client apps. Clients can only READ ranks.
9. High-Level Design
Let’s build this incrementally, one requirement at a time.
FR1: Update a Player’s Score
The first thing we need: when a player scores, update the leaderboard instantly. The naive SQL approach fails at scale (see above). We need a data structure designed for sorted data with fast updates.
The solution: Redis Sorted Set (ZSET).
💡 A Redis Sorted Set stores (score, member) pairs and keeps them sorted automatically. Internally it uses a skip list - like a linked list with “express lanes” - giving O(log N) for insert, update, and rank lookup. For 10M players: log₂(10M) ≈ 23 comparisons. Microseconds.
New components:
- Game Server - the backend running your game logic. Knows when a player’s score changes. Authoritative source of truth for scores.
- Leaderboard Service - API layer that translates business requests into Redis commands.
- Redis Sorted Set - the star.
ZADDto add/update scores, maintains sorted order automatically.
flowchart LR
GAME["Game Server"]
API["Leaderboard Service"]
REDIS[("Redis Sorted Set<br/>ZADD")]
GAME -->|"1. POST player score"| API
API -->|"2. ZADD to sorted set"| REDIS
Step-by-step flow:
- Player wins a match → Game Server calculates new score (1500)
- Game Server calls Leaderboard Service:
POST /scores { playerId: "player_42", score: 1500 } - Leaderboard Service executes:
ZADD leaderboard 1500 "player_42" - Redis updates the skip list - player is now in sorted position. Done in ~0.1ms.
- Service returns the player’s new rank (optional:
ZREVRANK leaderboard "player_42")
Why Redis and not a database? At 50K writes/sec during live events, a database index rebuild would lag behind. Redis keeps everything in memory with O(log N) operations - microsecond response regardless of dataset size. This one is not deferrable: the whole product is a sorted structure under constant mutation, and a sorted set is the data structure for that. Everything around it is deferrable, and the rest of this page is about what we are not building yet.
What we have deliberately left broken. A score update is now one O(log N) operation. Three assumptions baked into step 3 do not hold, and all three are non-functional:
- There is exactly one Redis, in exactly one region.
ZADD leaderboardnames a single key on a single instance. Players on the other side of the planet pay a cross-ocean round trip on every interaction in a product whose entire claim is “real-time”. That is Deep Dive 1. - The score is the only thing we sort by. A sorted set orders equal scores by member name, so two players tied on 1500 are ranked alphabetically. Nobody designed that; it is what we get for free, and it is visible to users as unfairness. That is Deep Dive 2.
- That key lives forever.
leaderboardis an all-time structure with no notion of a season, so there is no way to start a fresh week without destroying the current one. That is Deep Dive 3.
FR2: Get Top N Players
Now players want to see the leaderboard. “Show me the top 100.” With our Redis Sorted Set already maintaining sorted order, this is trivial.
No new components needed - Redis already has this built in.
Step-by-step flow:
- Player opens leaderboard page →
GET /leaderboard?top=100 - Leaderboard Service executes:
ZREVRANGE leaderboard 0 99 WITHSCORES - Redis returns 100 players sorted by score (highest first) - O(log N + 100)
- Service returns the ranked list to the client
sequenceDiagram
participant U as Player
participant API as Leaderboard Service
participant R as Redis
U->>API: GET /leaderboard?top=100
API->>R: ZREVRANGE leaderboard 0 99 WITHSCORES
R-->>API: 100 players with scores
API-->>U: Ranked list with positions
But what about durability? Redis is in-memory - if it restarts, the leaderboard is gone. We need a persistent backup.
New component:
- Durable Store (Postgres / DynamoDB) - source of truth. Every score update is also written here. If Redis goes down, we rebuild the Sorted Set from this store.
flowchart LR
GAME["Game Server"]
API["Leaderboard Service"]
REDIS[("Redis Sorted Set<br/>live rankings")]
DB[("Durable Store<br/>Postgres or DynamoDB")]
USER["Player"]
GAME -->|"1. Submit new score"| API
API -->|"2. ZADD score"| REDIS
API -->|"3. INSERT for durability"| DB
USER -->|"4. GET rank or top-N"| API
Why two stores? Redis gives microsecond rank lookups (essential for 100K QPS). The durable store (Postgres or DynamoDB) gives persistence — if Redis restarts, we rebuild from it. Pick Postgres if you need ad-hoc SQL queries over history; pick DynamoDB if you want zero-ops and infinite scale with simple key-value access patterns.
What we have deliberately left broken. The read path is a single Redis command, which is
genuinely fast. It is also completely uncoordinated: every reader runs its own
ZREVRANGE, and during a tournament final a million players ask for the identical top 100
within the same second. Each answer is ~5KB, so a million of them is 5GB of response
traffic a second from one node — and the node is not CPU-bound, it is out of network
interface. The irony worth noting is that the more players care about the leaderboard, the
more certain it is to be unavailable. That is Deep Dive 4.
FR3: Get a Player’s Rank
The most frequent query: “What’s MY rank?” With 10M players, this must be instant.
Still no new components - Redis Sorted Set handles this natively.
ZREVRANK leaderboard "player_42" → returns 1546 (0-indexed)
O(log N). For 10M players: ~23 operations internally. Microseconds.
Step-by-step flow:
- Player taps “My Rank” →
GET /leaderboard/rank?playerId=player_42 - Service executes:
ZREVRANK leaderboard "player_42"→ returns 1546 - Service also gets score:
ZSCORE leaderboard "player_42"→ returns 1500
💡ZSCOREreads one member’s score. Its write-side twinZINCRBYadds a delta to a score inside Redis, which is safer than read-then-write because no second writer can slip in between the two halves. - Returns
{ rank: 1547, score: 1500 }(converting 0-indexed to 1-indexed)
“Players around me” is equally simple:
ZREVRANGE leaderboard 1541 1551 WITHSCORES → 11 players around rank 1547
This completes all three core functional requirements with just Redis and a durable store.
What we have deliberately left broken. Nothing new, and that is worth saying explicitly
rather than leaving a gap. Rank is the single most requested value in the product — far more
often than the top 100 — and it goes down the same uncached path as FR2, so it is the larger
half of Deep Dive 4’s problem rather than a separate one. The ZREVRANK itself is cheap; it
is the million simultaneous callers that are not.
Now let’s address scale.
10. Technology Choices
| Tier | Purpose | Primary Pick | Alternatives | Why Primary Wins Here |
|---|---|---|---|---|
| Ranking Engine | Real-time sorted scores + rank queries | Redis Sorted Sets | DynamoDB, Cassandra, custom skip-list | O(log N) rank/update; the industry standard for leaderboards |
| Durable Store | Rebuild source if Redis fails | Postgres | MySQL, DynamoDB, CockroachDB | ACID writes for score events; small dataset fits one instance |
| Event Bus | Fan-out score events to aggregators | Kafka | Kinesis, Pulsar, RabbitMQ | Ordered per-partition replay lets global aggregator merge regionally |
| Real-time Push | Live rank updates to clients | WebSocket | SSE, Long Polling, gRPC stream | Bi-directional; players need instant rank changes during live events |
💡 Three things from this table. ACID (atomicity, consistency, isolation, durability) is the guarantee that a write either happens completely or not at all, which is why the durable store is relational. SSE (Server-Sent Events) is a one-way stream from server to browser over an HTTP response that is left open, and long polling fakes the same thing by holding a request open until there is news. Caffeine below is an in-process cache library for the JVM - it lives inside the service, not on another machine, so a lookup is not even a network hop. | Cache | Top-N leaderboard snapshot | Redis (separate key) | Memcached, Caffeine | Same Redis cluster; avoids cross-system hop for hot reads |
Why Redis over a SQL ORDER BY? A sorted set gives O(log N) for rank lookup and score update — microseconds for 10M entries. SQL requires a full sort or counting query per rank request, which collapses under 100K reads/sec during live events.
11. Data Modeling
Redis (Ranking Engine — real-time sorted scores):
Key: "leaderboard:{gameId}:{period}" → Sorted Set (score = playerScore, member = playerId)
Examples:
"leaderboard:dream11:match_42" → Sorted Set
"leaderboard:duolingo:weekly_2026_03" → Sorted Set
Postgres (Durable Store — rebuild source):
CREATE TABLE score_events (
id BIGSERIAL PRIMARY KEY,
player_id UUID NOT NULL,
game_id VARCHAR(64) NOT NULL,
score_delta INTEGER NOT NULL,
event_type VARCHAR(32), -- match_win, question_correct, bonus
created_at TIMESTAMP NOT NULL DEFAULT now()
);
CREATE INDEX idx_scores_player ON score_events(player_id, created_at DESC);
CREATE INDEX idx_scores_game ON score_events(game_id, created_at DESC);
Redis (Top-N Snapshot Cache):
Key: "lb:top100:{gameId}:{period}" → String (serialized JSON of top 100 with names + scores)
TTL: 5 seconds (hot cache to reduce ZREVRANGE calls from many concurrent viewers)
Access Patterns:
| Query | Data Source | How |
|---|---|---|
| Update score | Redis | ZINCRBY leaderboard:{gameId}:{period} delta playerId — O(log N) |
| Get top 10 | Redis | ZREVRANGE leaderboard:{gameId}:{period} 0 9 WITHSCORES — O(log N + 10) |
| Get my rank | Redis | ZREVRANK leaderboard:{gameId}:{period} playerId — O(log N) |
| Get players around me | Redis | Get rank with ZREVRANK, then ZREVRANGE rank-5 rank+5 |
| Rebuild after failure | Postgres → Redis | SELECT player_id, SUM(score_delta) FROM score_events GROUP BY player_id → bulk ZADD |
How Rank Query Works for 10M Players in O(log N):
- Redis sorted set is backed by a skip list. Each node tracks the span (number of elements between nodes at each level)
ZREVRANK playerIdtraverses the skip list from top → bottom, summing spans — this gives the exact rank in O(log N) time (~24 hops for 10M entries)- No counting query, no full scan. A single
ZREVRANKon 10M entries takes ~10μs - Score update (
ZINCRBY) re-positions the element in the skip list — also O(log N) - For leaderboards > 100M entries: shard by score range (0-1000 on shard 1, 1001-5000 on shard 2, etc.) and compute global rank by summing counts from higher shards
12. Deep Dives
1) One Redis in one region. What does the game feel like for the other two thirds of the world?
Problem: Your game operates worldwide. Players in Asia, Europe, and US all compete. If Redis lives in us-east-1 (an AWS region in Northern Virginia), Asian players get 200ms latency on every interaction. That’s unacceptable for “real-time.”
Bad: the single global Redis FR1 built. ZADD leaderboard resolves to one instance in one region, so geography decides your experience.
The structure itself is not the problem — the ZADD is still ~0.1ms. The round trip to reach it is 150-250ms from Asia to us-east-1, which means the network is 2,000 times the cost of the operation. We optimised the part that was already free. And it is paid on every interaction, not just the slow ones, so a player in Singapore experiences a fundamentally different product from one in Virginia despite identical code.
It is also a single failure domain for every player on the planet, and the region it sits in gets the best experience purely because that is where someone happened to deploy first.
Good: Regional Redis instances. Each region has its own leaderboard. Writes are local (<5ms). Players see their regional ranking instantly.
Great: Regional Redis for writes + async global aggregation for unified rankings. A Kafka-based pipeline merges regional scores into a global leaderboard with 100-500ms lag. For a leaderboard, this is invisible to users.
💡 This is the multi-region pattern: each region owns its own writes so a player never pays the cost of crossing an ocean, and a background job stitches the regions together afterwards. Note that “merge” is doing a lot of work in the diagram below - for a player who only plays in one region it is a copy, and for a player with scores in several it has to be a sum, not a last-write. Learn more →
In simple terms: Each region (US, EU, Asia) has its own leaderboard for instant local updates. A background job merges them into one global leaderboard every few hundred milliseconds. Users don’t notice the tiny delay.
flowchart LR
G1["Game Server US"]
G2["Game Server EU"]
R1[("Redis US")]
R2[("Redis EU")]
K["Kafka<br/>score events"]
AGG["Global Aggregator"]
RG[("Redis Global")]
G1 -->|"1. ZADD local"| R1
G2 -->|"2. ZADD local"| R2
R1 -->|"3. publish"| K
R2 -->|"4. publish"| K
K -->|"5. merge regions"| AGG
AGG -->|"6. ZADD global"| RG
New components:
- Kafka (score events): the ordered, replayable log each region publishes into. It exists so the Global Aggregator can consume every region’s changes at its own pace, and can replay them after a failure.
- Global Aggregator: consumes all regions and maintains the one unified sorted set. “Merge” here means summing a player’s deltas across regions rather than taking the latest one - for a system whose product is an exact ranking, that distinction is the whole component.
- Redis Global: the unified sorted set the worldwide top-100 is read from, kept separate from the regional sets so a global read never crosses an ocean mid-query.
- Reading the publish arrows: the diagram draws steps 3 and 4 starting at Redis, but a Redis sorted set emits no change feed. In practice the Leaderboard Service - the component that performed the
ZADD- is also what publishes the event.
Consistency tradeoff: The global leaderboard lags regional by 100-500ms (Kafka consumer lag). For a leaderboard, this is perfectly acceptable - no one notices their global rank updating 300ms late.
2) Two players tie on 1500 and Aaron beats Zeus. Who actually should rank higher?
Problem: Redis Sorted Sets break ties lexicographically by member name. If Player A and Player B both have score 1500, their rank order is alphabetical. But you probably want “whoever scored first ranks higher.”
In simple terms: Two players both have 1500 points. Who gets the higher rank? Redis will just sort by their name alphabetically - that’s unfair. We need a better tie-breaker.
Bad: accept the lexicographic ordering FR1 gets by default. ZADD leaderboard 1500 "player_42" supplies a score and a member, so when scores tie the sorted set falls back to comparing member names — and nobody chose that.
This is the most insidious class of defect on the page because it is not a failure, it is an unexamined default that happens to be a product decision. “Aaron” outranks “Zeus” on every tie, permanently, and at the top of a leaderboard with a prize attached that is a fairness complaint we cannot defend. Ties are not rare either: scores in most games are coarse — round numbers, capped values, fixed rewards — so the top of the board is where ties cluster most.
Worth noting it is also silent. Nothing errors, no metric moves, and the system looks correct to everyone who does not happen to be tied.
Good: Encode timestamp into the score itself. Combine the actual score with the time they achieved it into ONE number:
effective_score = actual_score × 10_000_000_000 + (MAX_TIMESTAMP - timestamp)
How this works with an example:
- Player A scores 1500 at timestamp 1000 → effective = 1500 × 10B + (MAX - 1000)
- Player B scores 1500 at timestamp 2000 → effective = 1500 × 10B + (MAX - 2000)
- Player A’s effective score is HIGHER (because MAX-1000 > MAX-2000)
- So Player A ranks above Player B (earlier scorer wins)
Redis stores scores as float64, which is exact on integers only up to 2^53. With a 10^10 multiplier that caps the base score at ~900K before the millisecond tie-break starts rounding away. The timestamp term must also stay under 10^10, so use an offset from a recent epoch rather than a raw epoch-millisecond value, which would overflow into the score field.
Great: For complex tie-breaking (score → then win-rate → then games played), use a composite score with weighted fields packed into a single number. Alternatively, maintain a secondary sorted set for the tiebreaker dimension and resolve in the application layer.
💡 “Packing” means reserving ranges of digits (or bits) for each field inside one number, so the single number sorts by the first field, then the second, then the third. The two options trade differently: packing keeps everything in one sorted set but fixes the precision of each field forever, while a second sorted set keeps the fields independent and moves the tie-break into your own code.
3) The season ends at midnight. How do we start a fresh board without a blank one?
Problem: Many games have weekly/seasonal leaderboards that reset. How do you atomically start a fresh leaderboard without downtime?
In simple terms: Every Monday, the leaderboard should start fresh (everyone back to 0). But how do you swap to a new empty leaderboard without players seeing a blank page for even a second?
Bad: DEL leaderboard, then let it refill. This is the only option FR1 left us, because FR1 named exactly one key with no season in it — so the all-time board and this week’s board are the same object, and starting a new week means destroying the old one.
Two things go wrong. Between the DEL and the first writes, every rank query returns nothing: not an error, an empty leaderboard, so clients render “unranked” for every player. And the gap is not 100ms in practice — it lasts until enough players have scored to make the board look populated, which at the start of a season could be minutes.
The worse loss is permanent. DEL destroys last season’s standings, so there is no history, no “your best week”, and no way to answer a dispute about a prize awarded last month. A reset should be a transition between two things that both exist; FR1’s single key makes it a deletion.
Good: Use time-bucketed keys: leaderboard:weekly:2026-W26. When the week changes, new writes go to the new key. Old key stays readable until archived. No deletion needed.
Great: Redis RENAME for atomic swap:
RENAME leaderboard:current leaderboard:archive:2026-W25
This is atomic - zero gap. In a single operation: the current leaderboard becomes the archive, and a new empty leaderboard:current can be created immediately. Persist the archive to the durable store for historical queries, then delete from Redis after a day.
4) A million players ask for the same top 100 in the same second. Why does that saturate a NIC?
💡 A NIC is the network interface card - the network port on the machine. Its bandwidth is a ceiling entirely separate from the CPU’s, and nothing about operations per second tells you when you are close to it, which is the whole point of this deep dive.
Problem: During a tournament final, 1M players all load the leaderboard simultaneously. They’re all asking for the same “top 100.” That’s 1M identical ZREVRANGE calls hitting Redis.
In simple terms: A million people asking the exact same question (“who’s in the top 100?”) at the same time. Even though each individual question is cheap, a million of them overwhelms even Redis.
Bad: let every request hit Redis directly, which is exactly what FR2 and FR3 do — neither puts anything between the reader and the sorted set.
The trap is that the operation looks cheap, so this looks fine. Each ZREVRANGE 0 99 is O(log N + 100), a few microseconds of CPU. Redis is nowhere near CPU-bound. What breaks is the wire: each response carries 100 members with scores, around 5KB, and a million of them in a second is 5GB/sec — roughly 40 Gbps out of one network interface. The node does not slow down gracefully; it runs out of a resource nobody was watching, because the metric everyone watches is ops/sec and ops/sec says the node is fine.
💡 The 5GB-to-40Gbps step is a unit conversion worth doing slowly: storage and payloads are quoted in bytes, network links in bits, and there are 8 bits to a byte - so 5 gigabytes per second is 40 gigabits per second (Gbps). Learn more →
And every one of those million responses is byte-identical. We are spending 5GB/sec to send the same 5KB a million times, in a product where the answer changes at most once a second.
Good: Application-level cache. Cache the “top 100” result with a 1-second TTL. First request computes it from Redis, caches the result. The next 999,999 requests in that second are served from cache. Only 1 request/second actually hits Redis.
💡 The thing to watch is the moment the entry expires: all million readers miss together and all of them try to recompute. That is a cache stampede, and the standard fixes are to let only the first miss through (request coalescing) and to keep serving the expired copy while it refreshes. Learn more →
Great: Dedicated “Top-K Cache” service with 1s TTL + WebSocket push for live updates. Instead of players polling “show me the top 100” repeatedly, the server pushes the updated top 100 to all connected players once per second via WebSocket. Zero polling, zero Redis load from viewers.
How it works:
- A background job runs
ZREVRANGEonce per second → gets the latest top 100 - Compares with previous top 100 → computes the diff (who moved up/down)
- Pushes the diff to all connected WebSocket clients
- Client updates the UI smoothly (player 5 moved to position 3, new score: 2450)
13. Design Self-Audit
| Question | Answer |
|---|---|
| Hot key problem? | The leaderboard IS a single key. But Redis ZSET handles 100K+ ops/sec per key. For extreme load, cache top-N results. |
| Redis goes down? | Rebuild from the durable store (Postgres or DynamoDB). Takes minutes for 10M entries. During rebuild, serve stale data from a read replica or return “temporarily unavailable.” |
💡 Two caveats on the rows above. A hot key is one key taking all the traffic, and because the shard is chosen by the key it cannot be spread by adding nodes - note also that Deep Dive 4 argues at length that ops/sec is the wrong metric here, so “100K+ ops/sec per key” does not actually settle the question. A read replica is a copy of a store kept current by the primary that can serve reads but not writes; Redis has no replica in any diagram here, so the rebuild is reading from the durable store. Learn more → | Memory budget? | 10M entries × ~600 bytes = ~6GB in Redis. Comfortable for any cloud Redis instance. | | Anti-cheat? | Only game servers (authenticated) can submit scores. Never trust client-submitted scores. |
14. Core Flows
Flow: Score Update (Full)
sequenceDiagram
participant G as Game Server
participant API as Leaderboard Service
participant R as Redis
participant DB as Durable Store
G->>API: POST /scores playerId=42 score=1500
API->>R: ZADD leaderboard 1500 player_42
R-->>API: OK
API->>R: ZREVRANK leaderboard player_42
R-->>API: 1546
API->>DB: INSERT INTO scores (player_id, score, ts)
DB-->>API: OK
API-->>G: 200 newRank=1547
Non-obvious failure: What if the Redis write succeeds but the DB insert fails? The live leaderboard shows the new score, but if Redis restarts later, this score is lost during rebuild. Solution: log failed DB writes to a dead-letter queue and retry. Or make the DB write synchronous (acceptable at 50K WPS - writes per second - for a single INSERT).
💡 A dead-letter queue is where a message goes after delivery has failed too many times, so it can be inspected and replayed rather than silently lost. The cleaner fix for the underlying dual-write problem is the outbox pattern: write the event into the same transaction as the data, and ship it from there.
15. Final Architecture
This diagram brings together every “Great” choice from the deep dives: regional Redis for low-latency writes, a Kafka pipeline feeding a global aggregator (Deep Dive 1), a durable store for rebuilds, and a Top-K cache with WebSocket push for read amplification (Deep Dive 4).
💡 Read amplification here means one logical answer being fetched a million times. The fix is to compute it once and copy it outward, not to compute it faster - which is why the answer is a cache plus push rather than a bigger Redis node.
flowchart TD
GAME["Game Servers<br/>per region"]
API["Leaderboard Service"]
R1[("Regional Redis<br/>live rankings")]
DB[("Durable Store<br/>Postgres or DynamoDB")]
K["Kafka<br/>score events"]
AGG["Global Aggregator"]
RG[("Redis Global<br/>unified rankings")]
CACHE["Top-K Cache<br/>1s TTL"]
WS["WebSocket Push"]
USER["Players"]
GAME -->|"Submit score update"| API
API -->|"ZADD to regional Redis"| R1
API -->|"Persist for durability"| DB
R1 -->|"Publish score change"| K
K -->|"Merge regional scores"| AGG
AGG -->|"ZADD to global Redis"| RG
CACHE -->|"Serve top-K from global"| RG
CACHE -->|"Feed live leaderboard"| WS
WS -->|"Push rank updates"| USER
USER -->|"Fetch cached rankings"| CACHE
New components in this picture:
- Durable Store (Postgres or DynamoDB): the append-only record of every score event. Redis is in memory, so this is the only thing a rebuild can read from - which is why it was introduced mid-FR2 rather than as a requirement of its own.
- Top-K Cache (1s TTL - time to live, how long a cached copy may be served before it is refreshed): one cached copy of the top-100 answer, served to everybody for a second at a time. It exists because a million identical reads should cost one computation and a million copies, not a million computations (Deep Dive 4).
- WebSocket Push: holds an open connection per viewing player and pushes the new top-100 when it changes, so the client stops asking. This is the component the “Below the Line” list originally excluded.
- What is missing from this diagram: there is no path for “my rank”, even though the design states it is the single most requested value in the product. It would be a read from Regional Redis (
ZREVRANK) rather than from the Top-K Cache, because one player’s rank is not a shared answer and cannot be cached for everybody.
How it works end-to-end (write path):
- Game Server reports score — calls the Leaderboard Service API with player ID and new score
- Regional Redis updated — ZADD writes the score to the local Redis sorted set (O(log N))
- Score event published to Kafka — regional change streamed for global aggregation
- Global Aggregator merges — consumes from all regions, updates Redis Global unified sorted set
How it works end-to-end (read path):
- Player requests leaderboard — hits the Top-K Cache (1s TTL, absorbs millions of identical reads)
- Cache miss reads from Redis Global — ZREVRANGE fetches top-N from the unified sorted set
- Live rank updates pushed — WebSocket Push streams position changes to connected players viewing the board
Key Technologies
| Term | What it is |
|---|---|
| Redis Sorted Set (ZSET) | O(log N) operations for insert, rank lookup, and range queries. The backbone of real-time leaderboards. |
| Skip List | Internal data structure Redis uses for sorted sets. Linked list with express lanes for fast traversal. |
| ZADD | Add or update a member’s score. O(log N). |
| ZREVRANK | Get rank of a member (0 = highest score). O(log N). |
| ZREVRANGE | Get members by rank range (top 10 = range 0-9). O(log N + K). |
What’s Expected at Each Level
Mid-level
Propose Redis Sorted Set for real-time ranking. Understand ZADD for updates and ZREVRANK for rank queries. Explain why SQL ORDER BY doesn’t scale - it’s O(N log N) per query vs O(log N) in Redis. Know that Redis is in-memory and needs a persistent backup (Postgres or DynamoDB).
Senior
Discuss regional sharding - local Redis per geography for low-latency writes. Explain tie-breaking with timestamp encoding. Propose dual-store (Redis for speed, Postgres/DynamoDB for durability). Discuss the “1M viewers asking for top 100” problem and how application-level caching with short TTL solves it.
Staff+
Design the tiered architecture for global live events: regional Redis + Kafka + global aggregator. Discuss WebSocket push for live rank updates (only push diffs for visible positions). Address read amplification with a dedicated Top-K cache. Cover anti-cheat (server-authoritative scoring), weekly resets via atomic RENAME, and memory budgeting (~6GB per 100M entries).
🎯 Key Takeaways
- Redis Sorted Set gives O(log N) rank queries and updates - microseconds for millions of players
- ZREVRANGE for top-N, ZREVRANK for “my rank” - both sub-millisecond
- Separate hot store (Redis) from durable store (Postgres or DynamoDB) for speed + durability
- Cache the top-K during live events to handle millions of identical reads
Related Designs
- Rate Limiter - Redis patterns, counters, sliding windows
- URL Shortener - caching and CDN patterns
- Twitter Feed - real-time updates pushed to users
Related Concepts
Understand the building blocks used in this design:
- Caching → — Redis sorted sets serve real-time rank queries in-memory
- Database Sharding → — partitions scores across segments when a single node can’t hold the set
- Consistency Models → — trades exact rank freshness against read latency at scale
Discussion
Newest first