Rank millions of players in real time: top-K, a player's own rank and time windows.
“Design a real-time leaderboard for a game.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Asking before drawing | “Leaderboard” hides many choices: one board or many, daily or all-time, best score or total, and whether every player needs an exact rank. A strong candidate pins these down first. |
| Choosing the right data structure | The whole question is about keeping millions of scores in order. The interviewer wants to hear why a table with ORDER BY fails and why a sorted set works. |
| Scaling a single ordered thing | Ordering does not split across machines easily. Top-K, and my rank, are the hard queries once one node is not enough. |
| Time windows and correctness | Daily and weekly boards must reset cleanly, ignore duplicates, and survive a crash without double counting. |
| Trade-offs and honesty | Exact rank for 50 million players is expensive. Saying “top 12%” is a legitimate answer, and knowing when to offer it shows judgement. |
A leaderboard answers three questions fast: who is in the top K, what is my rank, and who is around me. We keep each board in an in-memory sorted set (Redis ZSET). Score updates arrive through a queue, so game servers never wait on the board, and a durable log lets us rebuild any board.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Which boards and windows, what a score is, ties, exact vs approximate rank, how fresh. |
| 2. Estimate | 3 | Updates per second, reads per second, memory per board, number of boards. |
| 3. API and data | 5 | Submit score, top K, my rank, around me. The sorted set layout and tie-break trick. |
| 4. High-level design | 8 | Score service, queue, updaters, Redis, durable store, read API with a cache. |
| 5. Deep dives | 15 | Why a sorted set, then scaling past one node, then time windows, then durability and double counting. |
| 6. Scale and failures | 7 | Hot board, Redis loss, late events, cheating, monitoring. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would do next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| One global board, or several: per game mode, per region, per friends list? | Each board is its own sorted set. Friends boards are a different shape of problem. | A global board per game mode, plus a friends board. | Board key includes game and mode. Friends board is computed on read from a small set. |
| Which time windows: daily, weekly, monthly, all-time? | Each window needs its own board and its own reset. | Daily, weekly and all-time. | Three boards written per update. Period in the key, with a TTL on old ones. |
| What is a score: a running total, the best single result, or the latest? | Total means add to the score. Best means keep the max. They update differently. | A running total of points earned. | Update is an atomic increment (ZINCRBY), not a replace. |
| How do we break ties? | Players will have equal scores. Without a rule, order changes between reads. | Whoever reached the score first ranks higher. | Store a composite score that includes time, so the order is stable. |
| How big is the top list, and does every player need an exact rank? | Exact rank for 50M players costs far more than the top 100. | Top 100 must be exact. Everyone else needs a rank, but “top 12%” is fine beyond the first 10,000. | Exact sorted set for the head, approximate buckets for the tail if needed. |
| How fresh must it be? | Real time means seconds, not minutes, and decides batch vs stream. | A player sees their own new rank within a second. The top 100 may lag by a couple of seconds. | Stream updates through a queue. Cache the top list for 1 to 2 seconds. |
| How many players and how many score updates? | Sets memory, throughput and shard count. | 50M registered, 5M active a day, about 20 updates each. | About 100M updates a day, about 10,000 a second at peak. |
| Can a player cheat, and who decides the score? | A leaderboard is a target for cheats. It decides who we trust. | The game server decides scores. Clients never send them. | Score service accepts only authenticated server calls, with idempotency keys and checks. |
| Do we need history, such as last week's final board? | Past boards must be kept, or can be deleted. | Keep the last 4 weeks and the top 100 forever. | TTL on old period keys, and a job that saves the final top list before expiry. |
| One region or many? | Cross-region writes to one board are slow and complex. | One region for now. Mention multi-region. | A single primary board. Say how you would extend it. |
| Assumption | Value |
|---|---|
| Registered players | 50 million |
| Daily active players | 5 million |
| Score updates per active player per day | 20 |
| Peak to average ratio | 8 |
| Leaderboard views per active player per day | 100 |
| Memory per sorted-set entry (id, score, structure overhead) | about 100 bytes |
| One Redis node, simple operations | about 25,000 per second used for this job (50% of a typical 50,000, leaving headroom) |
| Size of one update event in the log | about 50 bytes |
| What | Maths | Result |
|---|---|---|
| Score updates per day | 5,000,000 × 20 | 100 million |
| Updates per second (average) | 100,000,000 ÷ 86,400 | about 1,160 per second |
| Updates per second (peak) | 1,160 × 8 | about 9,300, call it 10,000 |
| Board writes per update (daily, weekly, all-time) | 10,000 × 3 | 30,000 sorted-set writes per second at peak |
| Leaderboard views per second (peak) | 5,000,000 × 100 ÷ 86,400 × 8 | about 46,000 per second |
| Commands per view (top list from cache, plus my rank and around me) | about 2 Redis commands | about 92,000 commands per second at peak |
| Memory, all-time board | 50,000,000 × 100 bytes | 5 GB |
| Memory, daily boards (only active players, 30 days kept) | 5,000,000 × 100 bytes × 30 | 15 GB |
| Memory, weekly boards (about 15M players, 8 weeks kept) | 15,000,000 × 100 bytes × 8 | 12 GB |
| Memory in total, with a replica | (5 + 15 + 12) GB × 2 | about 64 GB |
| Redis commands per second at peak, all boards | 30,000 writes + 92,000 reads = 122,000 | about 5 primaries at 25,000 each |
| Durable log per day | 100,000,000 × 50 bytes | 5 GB a day, about 150 GB for 30 days |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/scores | { eventId, playerId, game, points, ts } | 202 { accepted: true } | Server to server only. eventId is the idempotency key, so a retry never counts twice. Returns 202 because the board updates asynchronously. |
| GET | /v1/leaderboards/{game}?window=weekly&top=100 | none | 200 { period, updatedAt, entries: [{ rank, playerId, name, score }] } | Served from a cache of 1 to 2 seconds. top is capped (for example 1,000). Cursor for deeper pages. |
| GET | /v1/leaderboards/{game}/me?window=weekly | none | 200 { rank, score, percentile } | Needs the player's identity. Exact for the head, percentile for the tail if we use buckets. |
| GET | /v1/leaderboards/{game}/me/around?n=5 | none | 200 { entries: [ ...5 above, me, 5 below ] } | Rank, then a short range read. n is capped at 10. |
| Key (Redis) | Type and members | Notes |
|---|---|---|
| lb:{game}:alltime | Sorted set. Member = playerId, score = composite score | One for the whole game. No TTL. |
| lb:{game}:weekly:2026-W49 | Sorted set, same shape | One per week. TTL of about 5 weeks after the week ends. |
| lb:{game}:daily:2026-12-04 | Sorted set, same shape | One per day. TTL of about 35 days. |
| seen:{eventId} | A key with a TTL (SET NX) | Dedup marker so a repeated event is ignored. Kept for a day or two. |
| player:{playerId} | Hash or row: name, avatar, region | Profile data lives apart from the board. Fetched for the 100 rows shown. |
// Higher points win. On a tie, the player who reached it first wins.
// One number, so the sorted set needs no second sort key.
const TIME_BITS = 2 ** 20; // room for ~12 days of seconds in the low bits
function composite(points: number, secondsIntoPeriod: number) {
return points * TIME_BITS + (TIME_BITS - 1 - secondsIntoPeriod);
}
// 810 points at 100 s -> 810 * 1,048,576 + 1,048,475
// 810 points at 500 s -> 810 * 1,048,576 + 1,048,075 (smaller, so ranks lower)
// A double holds integers exactly up to 2^53 (about 9e15).
// points up to 2^33 (8.6 billion) * 2^20 = 2^53. Plenty of room.
// Decode: points = Math.floor(score / TIME_BITS)| Component | What it does |
|---|---|
| Score service | Checks the caller is a game server, validates the points, checks the event id has not been seen, and writes the event to the queue. |
| Queue (Kafka) | Durable, ordered per player, and the record we can replay. It absorbs spikes so Redis is never overwhelmed. |
| Updater workers | Read events and apply them to the daily, weekly and all-time sorted sets with an atomic increment. Scale by adding workers. |
| Redis sorted sets | The fast ordered view. Sharded by board or by player (see the deep dive). Each primary has a replica. |
| Read API and top-K cache | Serves the top list from a cache that lives 1 to 2 seconds. Calls Redis directly for my rank and for players around me. |
| Event store and profile store | The durable record of every score event, and the player names and avatars joined into the rows we show. |
| Rotation and rebuild jobs | Create the next period boards, save the final top list, and rebuild a board by replaying events if Redis loses it. |
The problem: We need three fast queries on 50 million players: the top 100, the rank of one player, and the players around them. The data changes thousands of times a second, so the order must be maintained as it goes, not rebuilt.
| Option | How it works | Good | Bad |
|---|---|---|---|
| SQL table with ORDER BY | Store (player, score) in a table with an index on score. Top K is ORDER BY score DESC LIMIT K. Rank is SELECT COUNT(*) WHERE score > mine. | Familiar, durable, no new system. | Rank is a count over a range, so it is slow at 50 million rows and gets worse as updates keep changing the index. Hot rows and index churn under 10,000 writes a second. |
| Heap (priority queue) | Keep a heap of size K. Each update compares against the smallest of the top K. | Very cheap top K. Tiny memory. | Cannot answer “what is the rank of player X” without scanning, and cannot list the players around me. |
| Sorted set (skip list + hash map) | A skip list keeps scores in order. A hash map finds a player’s entry. Each level of the skip list also remembers how many entries it skips, so rank is a sum of those spans. | O(log n) update and rank. O(log n + K) for a range. One structure answers all three queries. Atomic increment. | All in memory. One sorted set lives on one node unless we shard. |
| Order-statistic tree (balanced tree with subtree counts) | Each tree node stores how many nodes are below it, so rank is found while walking down. | Same big-O as a sorted set. Common in an LLD interview. | More code to build and tune than using a ready-made sorted set. |
A sorted set gives all three queries from one structure: ZINCRBY to add points, ZREVRANGE 0 99 for the top 100, ZREVRANK for my rank, and a short ZREVRANGE around that rank. Every one is about log n, which for 50 million entries is about 26 steps. The SQL count has to walk a large part of the index, which is the work we are trying to avoid.
Use a heap when you only need the top K and never a rank, for example a live feed of the 10 best scores in a stream. For “my rank” you need the structure to know how many entries sit above each point, which is what a skip list with spans or a counted tree provides.
| Question | Sorted set command | Cost | SQL equivalent |
|---|---|---|---|
| Add 25 points to Ava | ZINCRBY board 25 ava | O(log n) | UPDATE, then the index moves the row |
| Top 100 | ZREVRANGE board 0 99 WITHSCORES | O(log n + 100) | ORDER BY score DESC LIMIT 100 |
| My rank | ZREVRANK board ava | O(log n) | COUNT(*) WHERE score > mine, a range scan |
| Five above and below me | ZREVRANGE board (r−5) (r+5) | O(log n + 10) | OFFSET r−5 LIMIT 11, which is slow for large r |
ZREVRANK returns 0, shown as rank 1 (add one). Gus has 760 and six players above him: rank 7. If Gus gains 100 points he reaches 860, the same as Dee. Dee got there first, so with the composite score Dee stays ahead and Gus takes rank 5 (behind Ava, Ben, Cy and Dee). The order is the same on every read.The problem: One sorted set lives on one node. At 50 million players it is only about 5 GB, so memory is not the issue, but one key means one node handles all its reads and writes. At 10x scale, or with hundreds of millions of players, we need to split a single ordered thing across machines, and ordering does not split cleanly.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One node per board (do not shard a board) | Different boards (games, windows) go to different nodes. One board stays whole. | Exact, simple, atomic. Enough for one board of 50 million at 10,000 writes a second. | A very big or very hot single board hits one node’s limit. Read replicas help reads only. |
| Shard by player id (hash) | Each shard holds a share of the players. Top K asks every shard for its best K, then merges. Rank asks every shard how many players have a higher score, and adds them. | Writes spread evenly. Top K is cheap: N shards × K entries merged. | Exact rank needs a call to every shard, and the counts must be taken at the same moment to be consistent. |
| Shard by score range | Shard 1 holds scores 0 to 1,000, shard 2 holds 1,000 to 2,000, and so on. Rank is the count of players in higher shards plus the local rank. | Rank needs only the local rank plus a cached count per higher shard. Top K reads one shard. | Players move between shards as scores change. Hot ranges (many players near the same score) overload one shard. |
| Exact head, approximate tail | Keep an exact sorted set only for the top N (for example 10,000). For everyone else keep score buckets (a histogram) and report a percentile. | Very cheap. Answers “top 12%” instantly. Nobody checks whether they are rank 4,883,120 or 4,883,121. | Not an exact rank. Needs a clear product choice, and an exact fallback if someone asks. |
Start simple: a 5 GB board and about 30,000 writes a second across three boards fit on a few primaries, and one board per node keeps everything exact. When one board must be split, shard by player id: writes spread evenly, and the top K is easy because it is the best K of N lists, merged. The costly query is the exact rank of an arbitrary player, which needs a count from every shard.
The pragmatic answer is that most players do not need an exact rank. Nobody cares whether they are 4,883,120th or 4,883,121st. Keep exact ranks for the top few thousand and show a percentile (“top 12%”) from histogram buckets for the rest. Interviewers like this because it shows you question the requirement before paying for it.
| Query | Shard by player (3 shards) | Shard by score range |
|---|---|---|
| Update one score | 1 shard (hash of player) | 1 shard, or 2 if the player crosses a range |
| Top 100 | All 3 shards give their best 100, merge 300 entries | Only the top shard |
| My exact rank | All 3 shards: count players with a higher score, then add | Local rank plus the cached sizes of higher shards |
| Hot spot risk | Low: players spread evenly | High: many players share a popular score range |
(players in higher buckets) + (a share of their own bucket) above them. Cost: reading a few hundred counters, not 50 million entries. Refresh the counts every few seconds.The problem: Each window must start empty on time, never mix periods, and keep working while it rolls over. Resets must not need a slow mass delete, and the weekly board is not the sum of the dailies for every kind of score.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Delete or reset the key at the boundary | A cron job at midnight clears the daily board. | Simple to picture. | A gap or a race: updates just after midnight can hit a half-cleared board. A big delete blocks Redis. |
| A new key per period | The period is part of the key (weekly:2026-W49). Updates for a period write to that key. The new one is created by the first write. | No reset at all. Late events go to the right period. Old keys expire with a TTL. | Needs a rule for which period an event belongs to, and a job to save the final top list before the TTL. |
| Compute weekly from daily boards | Merge seven daily sorted sets into the weekly one (ZUNIONSTORE with SUM). | Always consistent with the dailies. | Only right for a running total. A “best score” board cannot be a sum. The merge is expensive on big sets. |
| Write to all windows on every update | Each event updates the daily, weekly and all-time boards. | Every board is live. Simple, with a fixed cost of 3 writes. | Three times the writes. Late events must write to the right old period. |
Put the period in the key and let the first write create it. Then rollover is not an event: at midnight the daily key for the new date simply starts to receive writes, and the old one expires on its TTL. Decide the period from the event time sent by the game server, not the time the worker saw it, so a late event lands in the right board.
Write to all three windows (3 writes per update, as we budgeted). Avoid building the weekly board by summing the dailies unless the score is a running total, because a “best score” board does not add up. Before a period's key expires, a job reads the final top 100 and saves it, so history survives.
| Case | What to do |
|---|---|
| Event arrives 3 minutes after midnight, stamped 23:58 | Use the event time: it goes to yesterday’s daily board. Allow a grace period (for example 1 hour) before closing a period. |
| Timezones | Pick one (usually UTC) for the period key, and say so. Regional “today” boards need their own key per region. |
| Season ends | Freeze the board (stop accepting events for that period), save the final top list, give rewards from the saved list. |
| Replay after a failure | Replay events in order and use the same period rule, so the rebuilt boards are identical. |
const t = new Date(event.ts); // event time, not arrival time const keys = [ "lb:" + game + ":alltime", "lb:" + game + ":weekly:" + isoWeek(t), // for example 2026-W49 "lb:" + game + ":daily:" + isoDay(t), // for example 2026-12-04 ]; for (const k of keys) redis.zincrby(k, composite(points, secs), event.playerId);
The problem: Redis is fast but lives in memory. A crash, a failover or a repeated message must not lose points, count them twice, or let one player fake a place at the top.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Redis only | Write scores straight to Redis. Rely on AOF or RDB for safety. | Simplest. Lowest latency. | A failover can lose the last second or more. No way to prove or rebuild a score. Retries can double count. |
| Queue then Redis, with a durable log | Events go to a log first. Workers apply them to Redis. Any board can be replayed from the log. | Rebuildable, auditable, absorbs spikes. Delivery can be at-least-once if updates are idempotent. | A small delay (milliseconds to a second). One more system. |
| Database first, cache the boards | Write each event to a database transaction, then update Redis. | Strong durability. | A database write on the hot path of 10,000 events a second, and two writes that can disagree if one fails. |
| Idempotent apply with a seen-set | Each event carries an id. A worker applies it only if the id was not seen (SET NX), or stores the last applied offset per partition. | At-least-once delivery becomes effectively exactly once. | Needs a dedup store with a TTL, and care that the check and the update happen together. |
Treat Redis as a fast view and the event log as the truth. The score service writes to the log first (Kafka, partitioned by player so a player's events stay in order). Workers apply events to Redis. If Redis is lost, create a fresh board and replay: about 5 GB a day of events replays far faster than a day takes.
For double counting, give every event an id and apply it once: a Lua script that does SET seen:id NX and ZINCRBY together, or a stored offset per partition so a worker restarting from an older offset skips what is already applied. For cheating, scores come only from trusted game servers, with limits (maximum points per match, per minute), and suspicious accounts are flagged and their points removed with a negative event so the log still tells the truth.
-- KEYS[1] = seen:{eventId} KEYS[2] = board key
-- ARGV[1] = composite score delta ARGV[2] = playerId
if redis.call('SET', KEYS[1], 1, 'NX', 'EX', 172800) then
return redis.call('ZINCRBY', KEYS[2], ARGV[1], ARGV[2]) -- first time: apply
end
return nil -- repeat: ignore| Failure | What happens | Recovery |
|---|---|---|
| Worker crashes after applying, before it commits its offset | The event is delivered again | The seen-key makes the repeat a no-op |
| Redis primary fails, replica promoted | The last second of writes may be missing | Replay from the last committed offset, idempotently |
| Whole board lost | Board is empty | Rebuild from the event log, then switch reads over |
| Cheater detected | Points were already counted | Write a compensating negative event, and ban the account |
ZMSCORE and sort in the service. No new structure is needed, and it is always fresh.A teaching model with fixed data (no random numbers). A step means one comparison or one item touched; real costs also depend on memory, network and the engine. A sorted set in Redis keeps a skip list plus a hash map, which gives about log n for update and rank. Bucket counts give a range, not an exact rank, and the range gets tighter with more buckets.
| Bottleneck | Fix |
|---|---|
| Redis commands (about 120,000 a second at peak) | About 5 primaries, with boards spread across them. Pipeline the three board writes. Use replicas for reads of my rank. |
| Everyone reads the same top 100 | Cache it for 1 to 2 seconds in the read API, and in a CDN or local memory. One Redis read per second per board, not per player. |
| One huge board on one node | Read replicas for reads. If writes are the limit, shard by player and merge the top K, and show percentile for the tail. |
| Update spikes (a tournament ends) | The queue absorbs the burst. Add workers. Redis sees a steady rate, and the board lags by a second or two. |
| Joining names and avatars for 100 rows | Cache profiles. Fetch the 100 rows in one batch call. Keep names off the sorted set. |
| Pushing every rank change to clients | Do not. Poll every few seconds, or push only the top 10 and a player's own change. Avoid a fan-out of millions per update. |
| Memory growth from many period boards | A TTL on each period key. Daily boards for 30 days, weekly for 8 weeks. Save only the final top 100 forever. |
| Failure | How the design copes |
|---|---|
| A Redis primary fails | A replica is promoted. The last second of writes may be missing, so replay from the last committed log offset, idempotently. |
| All of Redis is lost | Show a cached or stale board with a banner, create empty boards, and replay the event log. Switch reads back when caught up. |
| The queue is down | The score service buffers briefly, then returns an error so game servers retry. Reads keep working from Redis and the cache. |
| A worker crashes mid-event | The event is redelivered. The seen-key or stored offset makes the repeat a no-op. |
| Late or out-of-order events | Use event time for the period. Allow a grace window. Totals are order-independent, so order only matters for tie-breaks. |
| A bad score is applied (bug or cheat) | Write a compensating negative event, or rebuild that board from the log with the bad events filtered out. |
Game servers send trusted score events to a score service that validates and dedupes, then writes to a durable queue. Workers apply each event to daily, weekly and all-time sorted sets in Redis, using a composite score for stable ties. The read API serves the top 100 from a short cache, my rank with one ZREVRANK call, and players around me with a short range read. The event log can rebuild any board. For very large boards we shard by player and merge the top K, and show a percentile for the long tail.
| Decision | What we gain | What it costs |
|---|---|---|
| Redis sorted sets for the boards | Rank, range and increment in log time, in one structure. | Everything in memory, and a single board lives on one node. |
| A durable event log as the truth | Boards can be rebuilt, audited and replayed. Spikes are absorbed. | A small delay, and one more system to run. |
| Idempotent apply with event ids | At-least-once delivery behaves like exactly once. | A dedup store with a TTL, and care that check and update are atomic. |
| Composite score with time in the low bits | A stable order for ties with one number. | Limits on how big points can get (the 53-bit limit), and a decode step. |
| Cache the top list for 1 to 2 seconds | One Redis read per second instead of 46,000. | The top list can be a moment old. |
| Percentile instead of exact rank for the tail | No cross-shard count for millions of players. | Players beyond the head see a range, not an exact place. |
The heart of the question. Be ready to explain why a sorted set, and what each command costs.
Ordering does not split cleanly. Show that you know the cost of each way to split it.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| The score is the best single result, not a total | Use ZADD with GT instead of ZINCRBY. Weekly boards cannot be built by summing dailies. Each window is written directly. |
| A leaderboard of 1 billion players | Shard by player, keep an exact head and a bucketed tail, aggregate events in a stream before writing, and show percentiles. |
| Players should see their rank change live | Push own-rank changes and the top 10 over WebSockets. Poll the rest. Throttle pushes to one every second or two per player. |
| Per-country and per-friends boards | A board per country (a new key). Friends boards are read on demand with a pipelined ZMSCORE. No global recompute. |
| Lowest score wins (for example, fastest lap time) | Use ZRANGE ascending instead of ZREVRANGE, and ZADD with LT for best. Tie-break by earlier time still applies. |
| The score is the result of a long computation | Compute in a batch job, and write the final scores to a fresh board that is swapped in at once. Reads see the old board until the swap. |
| A paid tournament with prizes | Freeze the board at the end, save the final list, and verify it against the event log before paying. Add audit logs. |
| Leaderboard history over time (rank last week) | Save the top 100 at each period end, and store a rank-per-day sample for each player in a time-series store. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing a Redis box. Never asks about windows, ties or exact rank. | Asks about windows, total vs best score, top K size and freshness. | Questions whether exact rank is needed for everyone, and writes the tie-break and anti-cheat assumptions down. |
| Estimation | No numbers, or says memory is the constraint. | Updates per second, reads, and memory per board, with correct maths. | Sees that a board is small (5 GB) and throughput is the limit, and uses it to decide on shards, caching and the queue. |
| Data structure | Says use a database or a list and sort it. | Picks a sorted set and names the commands. | Explains the skip list with spans, compares heap, SQL and counted tree, and says why each fails or fits. |
| Scaling | Add more servers. | Shards by player and merges the top K. | Explains the cost of exact rank across shards, offers percentile for the tail, and compares score-range sharding. |
| Correctness and failures | Ignores duplicates, crashes and late events. | Uses a queue, idempotency and a durable log. | Explains atomic apply, event-time periods, replay, compensating events and how to detect silent loss. |
| Communication | Lists technologies without reasons. | Follows the steps, explains each choice. | Summarises each step, checks in, and states clearly what is approximate and what is exact. |
| Mistake | Do this instead |
|---|---|
| Using SQL ORDER BY and COUNT(*) for rank on 50 million rows | Use a sorted set. Say why rank is the expensive query and how a skip list with spans answers it. |
| Reading the score, adding in the app, writing it back | Use an atomic ZINCRBY (or ZADD GT). Name the lost update. |
| Treating Redis as the only copy of the data | Keep a durable event log, and be able to rebuild a board by replaying it. |
| Resetting boards with a midnight delete | Put the period in the key and let the new key start empty. Use event time, with a grace period. |
| No tie-break rule | Fold time into the score, so equal points order by who got there first and the list is stable. |
| Promising an exact rank for every player at huge scale | Ask if it is needed. Exact for the head, percentile from buckets for the tail. |
| Letting clients submit scores | Only trusted game servers post scores, with limits and idempotency keys. |
| Pushing every rank change to every client | Poll the top list, and push only the top 10 and a player’s own change. |
The structure inside a Redis sorted set, and how spans give rank.
Top K without rank, and when a heap is enough.
Redis, and what its data types give you.
Splitting one big board across nodes.
The short cache of the top list.
The durable log and the buffer in front of Redis.
What happens when one board takes all the traffic.
Approximate counts for the long tail at huge scale.