SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Leaderboard

Rank millions of players in real time: top-K, a player's own rank and time windows.

⏱ 28 min readMedium case studyIntermediate22 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a real-time leaderboard for a game.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy 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 structureThe 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 thingOrdering does not split across machines easily. Top-K, and my rank, are the hard queries once one node is not enough.
Time windows and correctnessDaily and weekly boards must reset cleanly, ignore duplicates, and survive a crash without double counting.
Trade-offs and honestyExact rank for 50 million players is expensive. Saying “top 12%” is a legitimate answer, and knowing when to offer it shows judgement.

TL;DRThe whole design in 60 seconds

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.

  • Scale: 5M daily players making 20 updates each is 100M updates a day, about 1,200 a second on average and about 10,000 at peak. Reads are about 5 times that. One all-time board of 50M players is about 5 GB.
  • Structure: a sorted set (a skip list plus a hash map) gives O(log n) update and rank, and O(log n + K) for the top K. SQL with ORDER BY or COUNT(*) does a lot more work per query.
  • Write path: game server, score service (validate, dedupe), queue, updater workers, Redis. The queue is also the durable record.
  • Read path: top 100 is cached for a second or two. My rank is one ZREVRANK call. Players around me is rank plus a short range read.
  • Time windows: one sorted set per period (for example weekly:2026-W49), with a TTL. Resetting is just starting a new key, no mass delete.
  • Beyond one node: shard by player and merge each shard's top K. For exact rank of everyone that is costly, so show an approximate rank (top 12%) outside the top few thousand.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Which boards and windows, what a score is, ties, exact vs approximate rank, how fresh.
2. Estimate3Updates per second, reads per second, memory per board, number of boards.
3. API and data5Submit score, top K, my rank, around me. The sorted set layout and tie-break trick.
4. High-level design8Score service, queue, updaters, Redis, durable store, read API with a cache.
5. Deep dives15Why a sorted set, then scaling past one node, then time windows, then durability and double counting.
6. Scale and failures7Hot board, Redis loss, late events, cheating, monitoring.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about what a score means, how long a board lasts, who needs an exact rank, and how fresh the data must be.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Add points to a player (idempotent, from a trusted server)
  • •Show the top K players for a board and window
  • •Show a player their own rank and score
  • •Show the players just above and below me
  • •Daily, weekly and all-time boards that reset on schedule
Non-functional (how well)
  • •Own rank visible within 1 second of an update
  • •Top list read in under 50 ms at p99
  • •Handle 10,000 score updates a second at peak and about 5 times that in reads
  • •No double counting, even if a message is delivered twice
  • •Available: reads keep working if the update path is behind
  • •Stable order: equal scores never swap between reads
Out of scope (say it)
  • •Matchmaking and rating systems such as Elo
  • •Anti-cheat detection models (we only keep the hooks)
  • •Rewards and prizes at the end of a season
  • •Chat and social features around the board
🎤
Say it out loud
“Let me confirm the scope. We have a global board per game mode, plus friends boards, with daily, weekly and all-time windows. A score is a running total of points, set by our game servers and never by the client. Ties go to whoever got there first. The top 100 must be exact, and for everyone else a rank within the top few percent is fine. A player should see their own change within a second. I will plan for 5 million active players and about 10 thousand updates a second at peak, in one region. I will leave rating systems, anti-cheat models and prizes out. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: updates per second, reads per second, how big is one board in memory, and how many boards are alive at once? Which is the real constraint: memory or throughput?

Assumptions (say them first)

AssumptionValue
Registered players50 million
Daily active players5 million
Score updates per active player per day20
Peak to average ratio8
Leaderboard views per active player per day100
Memory per sorted-set entry (id, score, structure overhead)about 100 bytes
One Redis node, simple operationsabout 25,000 per second used for this job (50% of a typical 50,000, leaving headroom)
Size of one update event in the logabout 50 bytes

The arithmetic, line by line

WhatMathsResult
Score updates per day5,000,000 × 20100 million
Updates per second (average)100,000,000 ÷ 86,400about 1,160 per second
Updates per second (peak)1,160 × 8about 9,300, call it 10,000
Board writes per update (daily, weekly, all-time)10,000 × 330,000 sorted-set writes per second at peak
Leaderboard views per second (peak)5,000,000 × 100 ÷ 86,400 × 8about 46,000 per second
Commands per view (top list from cache, plus my rank and around me)about 2 Redis commandsabout 92,000 commands per second at peak
Memory, all-time board50,000,000 × 100 bytes5 GB
Memory, daily boards (only active players, 30 days kept)5,000,000 × 100 bytes × 3015 GB
Memory, weekly boards (about 15M players, 8 weeks kept)15,000,000 × 100 bytes × 812 GB
Memory in total, with a replica(5 + 15 + 12) GB × 2about 64 GB
Redis commands per second at peak, all boards30,000 writes + 92,000 reads = 122,000about 5 primaries at 25,000 each
Durable log per day100,000,000 × 50 bytes5 GB a day, about 150 GB for 30 days
What the numbers tell us about the design
  • •Memory is small: a few tens of GB for everything. One 50M board is only 5 GB, so a single sorted set fits on one machine.
  • •Throughput, not memory, forces a second node: about 120,000 commands a second at peak is about 5 primaries. And one big board is still one key on one node.
  • •Reads are about 5 times the writes (46,000 views vs 9,300 updates), so cache the top list. It is the same 100 entries for everyone.
  • •The durable log is the real storage: 150 GB for 30 days is trivial for a log, so keeping every event to rebuild boards is cheap.
  • •Three boards per update triples the writes, so period boards must be cheap to write and cheap to drop.
🎤
Say it out loud
“Let me do the maths. Five million players with 20 updates each is a hundred million updates a day, about twelve hundred a second, and about ten thousand at peak. Each update touches three boards, so thirty thousand writes a second. Views are about five times that. An entry in a sorted set is about a hundred bytes, so the all-time board of fifty million players is five gigabytes. That fits on one machine, so memory is not the problem. Throughput is: about a hundred and twenty thousand commands a second means about five primaries. And I would cache the top hundred, because every player sees the same list.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the call a game server makes to add points, and the three calls a client makes: top K, my rank, and players around me. What do you store per player in the sorted set, and how do you break ties?

Endpoints

MethodPathRequestResponseNotes
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=100none200 { 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=weeklynone200 { 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=5none200 { entries: [ ...5 above, me, 5 below ] }Rank, then a short range read. n is capped at 10.

Data model

Key (Redis)Type and membersNotes
lb:{game}:alltimeSorted set. Member = playerId, score = composite scoreOne for the whole game. No TTL.
lb:{game}:weekly:2026-W49Sorted set, same shapeOne per week. TTL of about 5 weeks after the week ends.
lb:{game}:daily:2026-12-04Sorted set, same shapeOne 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, regionProfile data lives apart from the board. Fetched for the 100 rows shown.
Composite score for a stable tie-break (sketch)
// 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)
📝Total, best or latest?
For a running total use ZINCRBY (atomic add). For best-score use ZADD with the GT flag, which only updates if the new score is higher. For latest, a plain ZADD replaces it. Say which one you picked and why.
📝Which store, and why
The boards are an ordered set that must update and rank in logarithmic time and be read by position, so an in-memory sorted set (Redis ZSET) is the natural fit: it is a skip list plus a hash map, and it supports rank, range and atomic increment. It is not the source of truth. A durable log of score events (Kafka, or a database table) is, so a lost board can be rebuilt. Profiles live in a normal key-value store or database, and are joined in for the few rows we show.
🎤
Say it out loud
“A game server sends points with an event id as the idempotency key, and gets back 202 because the board updates a moment later. Clients have three reads: the top K, my rank, and the players around me. Each board is a Redis sorted set keyed by game, window and period, with the player id as the member. For a stable tie-break I fold time into the score, so one number gives both the points and who got there first. The sorted set is a fast view, and a durable event log is the real record.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the boxes for one score update and one rank read. Where does the queue sit? Where do you cache? What can you rebuild if Redis loses everything?
Leaderboard: high-level design
🎮Game serverstrusted score source
→↓points
✅Score servicevalidate, dedupe, rate limit
→↓
📨Queue (Kafka)durable event log
→↓
⚙️Updater workersZINCRBY on 3 boards
Boards (sharded)
⚡Redis sorted setsall-time, weekly, daily
📋Replicasfailover copy
Reads
🌍Read APItop K, my rank, around me
🧊Top-K cache1 to 2 s TTL
Durable and jobs
🗄️Event store / DBsource of truth, profiles
🔁Rotation + rebuild jobsnew periods, replays
📱Playersview the board
→↓reads
🌍Read API
Updates flow through a queue into sorted sets. Reads hit a short cache for the top list and Redis for my rank. The event log can rebuild any board.
ComponentWhat it does
Score serviceChecks 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 workersRead events and apply them to the daily, weekly and all-time sorted sets with an atomic increment. Scale by adding workers.
Redis sorted setsThe fast ordered view. Sharded by board or by player (see the deep dive). Each primary has a replica.
Read API and top-K cacheServes 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 storeThe durable record of every score event, and the player names and avatars joined into the rows we show.
Rotation and rebuild jobsCreate the next period boards, save the final top list, and rebuild a board by replaying events if Redis loses it.
Write path (follow one request)
  1. A game server finishes a match and calls POST /v1/scores with an event id, the player and the points.
  2. The score service authenticates the caller, validates the points against a sane range, and rate limits per player.
  3. It checks the event id (SET NX in Redis, or a database unique key). A repeat is acknowledged but ignored.
  4. It appends the event to the queue, partitioned by player id so one player’s events stay in order, and returns 202.
  5. An updater worker reads the event and runs ZINCRBY on the daily, weekly and all-time boards, using the composite score.
  6. The same event is also written to the durable event store, so any board can be rebuilt later.
Read path (follow one request)
  1. A player opens the leaderboard. The read API gets the request with the game and window.
  2. For the top 100 it checks the cache. On a miss it runs ZREVRANGE on the board, joins in names from the profile store, and caches the result for 1 to 2 seconds.
  3. For my rank it runs ZREVRANK and ZSCORE on the board (both O(log n)).
  4. For players around me it takes that rank and runs ZREVRANGE from rank − n to rank + n.
  5. If the player is far outside the head and we use buckets, it returns a percentile instead of an exact rank.
  6. The response includes the period and an updatedAt time, so the client can show how fresh it is.
🎤
Say it out loud
“Here is the picture. Game servers send points to a score service that validates and dedupes, then writes to a queue, which is also the durable record. Updater workers apply each event to three sorted sets in Redis: daily, weekly and all-time. Reads go through a small API: the top hundred comes from a cache that lives a second or two, my rank is one ZREVRANK, and players around me is the rank plus a short range. If Redis loses a board, I replay the event log to rebuild it. Boards are a fast view, and the log is the truth.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Keeping millions of scores in order: why a sorted set

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.

OptionHow it worksGoodBad
SQL table with ORDER BYStore (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.
Pick
A Redis sorted set per board and window

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.

QuestionSorted set commandCostSQL equivalent
Add 25 points to AvaZINCRBY board 25 avaO(log n)UPDATE, then the index moves the row
Top 100ZREVRANGE board 0 99 WITHSCORESO(log n + 100)ORDER BY score DESC LIMIT 100
My rankZREVRANK board avaO(log n)COUNT(*) WHERE score > mine, a range scan
Five above and below meZREVRANGE board (r−5) (r+5)O(log n + 10)OFFSET r−5 LIMIT 11, which is slow for large r
📝Worked example
Ava has 940. Players with more: 0. So 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.
🎤
Say it out loud
“The core need is three fast queries on millions of players: top K, my rank, and around me, while scores change constantly. SQL with ORDER BY and COUNT works at small scale, but the rank query is a range count and it gets slow. A heap gives the top K but not a rank. A sorted set, which is a skip list plus a hash map, does all three in about log n, and Redis gives it to me with an atomic increment. So I would keep one sorted set per board and window.”
5.2

Scaling past one node: sharding and approximate rank

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.

OptionHow it worksGoodBad
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 rangeShard 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 tailKeep 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.
Pick
One sorted set per board while it fits, then shard by player with a merged top K, and show a percentile for the long tail

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.

QueryShard by player (3 shards)Shard by score range
Update one score1 shard (hash of player)1 shard, or 2 if the player crosses a range
Top 100All 3 shards give their best 100, merge 300 entriesOnly the top shard
My exact rankAll 3 shards: count players with a higher score, then addLocal rank plus the cached sizes of higher shards
Hot spot riskLow: players spread evenlyHigh: many players share a popular score range
💡Approximate rank in one line
Keep a count of players per score bucket (for example every 100 points). A player with score s has about (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.
📝Try it
The visualizer below shows how many steps and shards each query touches for a plain table, one sorted set, and three shards, and compares an exact rank to a bucket range.
🎤
Say it out loud
“A sorted set lives on one node, so I would first ask whether I need to split it at all: a fifty million player board is about five gigabytes and fits. If I must shard, I would shard by player id: writes spread evenly and the top K is the best K from each shard, merged. The costly query is exact rank for an arbitrary player, because it needs a count from every shard. So I would keep exact ranks for the top ten thousand and show a percentile like top twelve percent for everyone else, from score buckets. That is a requirement question as much as a technical one.”
5.3

Daily, weekly and all-time: time windows and resets

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.

OptionHow it worksGoodBad
Delete or reset the key at the boundaryA 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 periodThe 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 boardsMerge 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 updateEach 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.
Pick
A key per period, and write each event to all three windows

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.

CaseWhat to do
Event arrives 3 minutes after midnight, stamped 23:58Use the event time: it goes to yesterday’s daily board. Allow a grace period (for example 1 hour) before closing a period.
TimezonesPick one (usually UTC) for the period key, and say so. Regional “today” boards need their own key per region.
Season endsFreeze the board (stop accepting events for that period), save the final top list, give rewards from the saved list.
Replay after a failureReplay events in order and use the same period rule, so the rebuilt boards are identical.
Which board does an event write to? (sketch)
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);
🎤
Say it out loud
“I would put the period in the key, so daily and weekly boards are separate sorted sets and a reset is not an event: the new key just starts to fill and the old one expires on a TTL. I decide the period from the event time, not the arrival time, with a short grace period, so late events land in the right board. Each event writes to the daily, weekly and all-time boards. I would not build the weekly board by adding up the dailies unless the score is a running total. Before a key expires, a job saves its final top hundred.”
5.4

Durability, double counting and cheating

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.

OptionHow it worksGoodBad
Redis onlyWrite 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 logEvents 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 boardsWrite 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-setEach 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.
Pick
A durable event log, idempotent updaters, and boards that are always rebuildable

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.

Apply an event once (Lua sketch, runs atomically in Redis)
-- 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
FailureWhat happensRecovery
Worker crashes after applying, before it commits its offsetThe event is delivered againThe seen-key makes the repeat a no-op
Redis primary fails, replica promotedThe last second of writes may be missingReplay from the last committed offset, idempotently
Whole board lostBoard is emptyRebuild from the event log, then switch reads over
Cheater detectedPoints were already countedWrite a compensating negative event, and ban the account
💡Friends leaderboard
A friend list is small (hundreds). Read each friend's score from the board with a pipelined ZMSCORE and sort in the service. No new structure is needed, and it is always fresh.
🎤
Say it out loud
“Redis is a fast view and the truth is a durable event log. The score service writes to the log first, partitioned by player so a player's events keep their order, and workers apply each event to Redis. If Redis loses a board, I rebuild it by replaying the log. To avoid double counting, every event has an id and the apply step is idempotent: a small script marks the id as seen and increments in one atomic step, so a redelivered message does nothing. Scores come only from trusted game servers with limits, and a cheat is removed with a negative event so the log stays honest.”
VisualizerPlain table vs sorted set vs shards: what each query costsPick a player and change their score. Switch between a plain table, one sorted set and three shards, and raise the number of players. Watch the step counts. Then compare the exact rank with the bucket range.
How is the leaderboard stored?
Pretend the board has this many players (the list below always shows 16)
Ranked list. Equal scores: the player who got there first ranks higher. Green = top 5, cyan = your player.
1Ava940
2Ben910
3Cy870
4Dee860
5Eli820
6Fay820
7Gus760
8Hal700
9Ivy650
10Jo610
11Kai540
12Lia480
13Max420
14Nia300
15Oz220
16Pat90
Update a score
40
steps
Top 5
25
steps
Rank of Gus
21
steps (rank 7)
Shards touched
1
per query
A sorted set keeps order as it goes, so an update, a top-5 and a rank each cost about 40, 25 and 21 steps, instead of 1,000,000. That is the whole reason leaderboards use one. Walk down the express lanes (about log2 n), then read K in order. Rank comes from counts kept on each lane.
Approximate rank from bucket counts
Keep only how many players sit in each score range of 200. Then Gus (score 760) is somewhere in a rank range, with no per-player lookup.
1
0
2
200
3
400
4
600
6
800+
Exact rank: 7 (needs the sorted set)
From buckets: 7 to 10 (top 63%)

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.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
If traffic grows 10 times, what breaks first? If Redis loses a board, what do players see? If one game launches and everyone opens the board at once, what gets hit?

What breaks first, and the fix

BottleneckFix
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 100Cache 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 nodeRead 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 rowsCache profiles. Fetch the 100 rows in one batch call. Keep names off the sorted set.
Pushing every rank change to clientsDo 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 boardsA TTL on each period key. Daily boards for 30 days, weekly for 8 weeks. Save only the final top 100 forever.

What if a part fails?

FailureHow the design copes
A Redis primary failsA replica is promoted. The last second of writes may be missing, so replay from the last committed log offset, idempotently.
All of Redis is lostShow 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 downThe score service buffers briefly, then returns an error so game servers retry. Reads keep working from Redis and the cache.
A worker crashes mid-eventThe event is redelivered. The seen-key or stored offset makes the repeat a no-op.
Late or out-of-order eventsUse 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.
What to monitor
  • •Update lag: time between a score event and its appearance on the board (target under 1 second)
  • •Redis commands per second and latency per node, and memory per board
  • •Queue consumer lag per partition, and the number of redelivered events
  • •Cache hit rate of the top list, and p99 latency of the read API
  • •Score outliers: players gaining far more than the normal rate, to catch cheating early
Security and abuse
  • •Only authenticated game servers can post scores. Clients never send points.
  • •Limit points per event and per player per minute, and reject impossible values.
  • •Idempotency keys on every event, so a replay attack cannot add points twice.
  • •Flag and review unusual gains, and remove cheaters with a compensating event so history stays true.
  • •Hide private data: show a display name, not an email or real name, on public boards.

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
Redis sorted sets for the boardsRank, 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 truthBoards can be rebuilt, audited and replayed. Spikes are absorbed.A small delay, and one more system to run.
Idempotent apply with event idsAt-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 bitsA 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 secondsOne Redis read per second instead of 46,000.The top list can be a moment old.
Percentile instead of exact rank for the tailNo cross-shard count for millions of players.Players beyond the head see a range, not an exact place.
If we had more time, we would…
  • •Friends and region boards, with a pipelined ZMSCORE for friends.
  • •Multi-region: a board per region, and a periodic merged global board, accepting a little delay.
  • •Real-time push of rank changes for the top 10 only, over WebSockets.
  • •Anti-cheat scoring and a review queue for suspicious gains.
  • •Season archives, with the final top list and rewards driven from the saved list.
🎤
Say it out loud
“To recap: trusted game servers send score events to a service that validates and dedupes and writes to a durable queue. Workers apply them to daily, weekly and all-time sorted sets in Redis with a composite score so ties are stable. Reads use a short cache for the top hundred, one ZREVRANK for my rank, and a range read for around me. The log can rebuild any board. The trade-offs are that everything is in memory, ties and period keys need care, and for huge boards I would show a percentile instead of an exact rank. With more time I would add friends boards, multi-region and anti-cheat.”

Q&ACross-questions (22)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Data structure and queries

The heart of the question. Be ready to explain why a sorted set, and what each command costs.

Scale and sharding

Ordering does not split cleanly. Show that you know the cost of each way to split it.

Time windows, consistency and failures

Features, cheating and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
The score is the best single result, not a totalUse ZADD with GT instead of ZINCRBY. Weekly boards cannot be built by summing dailies. Each window is written directly.
A leaderboard of 1 billion playersShard 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 livePush 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 boardsA 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 computationCompute 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 prizesFreeze 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.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts 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.
EstimationNo 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 structureSays 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.
ScalingAdd 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 failuresIgnores 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.
CommunicationLists technologies without reasons.Follows the steps, explains each choice.Summarises each step, checks in, and states clearly what is approximate and what is exact.

AvoidCommon mistakes on this question

MistakeDo this instead
Using SQL ORDER BY and COUNT(*) for rank on 50 million rowsUse 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 backUse an atomic ZINCRBY (or ZADD GT). Name the lost update.
Treating Redis as the only copy of the dataKeep a durable event log, and be able to rebuild a board by replaying it.
Resetting boards with a midnight deletePut the period in the key and let the new key start empty. Use event time, with a grace period.
No tie-break ruleFold 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 scaleAsk if it is needed. Exact for the head, percentile from buckets for the tail.
Letting clients submit scoresOnly trusted game servers post scores, with limits and idempotency keys.
Pushing every rank change to every clientPoll the top list, and push only the top 10 and a player’s own change.

Revise60-second revision sheet

  • ✔Scale: 100M updates a day is about 1,200 a second, about 10,000 at peak, times 3 boards. Views are about 5 times that.
  • ✔Memory: about 100 bytes an entry, so 50M players is about 5 GB. Memory is small. Throughput forces about 5 primaries.
  • ✔Structure: Redis sorted set (skip list plus hash map). ZINCRBY, ZREVRANGE, ZREVRANK are all about log n.
  • ✔Why not SQL: top K is fine, but rank is a COUNT over a range. A heap gives top K but no rank.
  • ✔Ties: fold time into the score (points × 2^20 + remaining seconds). A double is exact up to 2^53.
  • ✔Write path: game server, score service (validate, dedupe), queue (the durable log), workers, Redis. 202 Accepted.
  • ✔Read path: cache the top 100 for 1 to 2 seconds. My rank is one ZREVRANK. Around me is rank plus a short range.
  • ✔Windows: period in the key, TTL on old keys, event time decides the period. No midnight delete.
  • ✔Sharding: by player, merge each shard's top K. Exact rank needs a count from every shard, so use a percentile for the tail.
  • ✔Safety: idempotent apply with an event id, replay from the log, trusted servers only, compensating events for cheats.

Read these topics next

Skip Lists→

The structure inside a Redis sorted set, and how spans give rank.

Heap and Priority Queue→

Top K without rank, and when a heap is enough.

Key-Value Databases→

Redis, and what its data types give you.

Sharding→

Splitting one big board across nodes.

Caching Strategies→

The short cache of the top list.

Message Queues→

The durable log and the buffer in front of Redis.

Hot Keys→

What happens when one board takes all the traffic.

Count-Min Sketch→

Approximate counts for the long tail at huge scale.

← Previous
Design a Distributed Cache
Next →
Design a Job Scheduler