System Design

Problem Breakdowns

Design a Leaderboard / Ranking Service

A Redis sorted set answers who is on top and where you stand in one command each, right up until a board outgrows one key. The way through is to notice that a rank is only a count of the players ahead of you, and counts add up across machines, can be shared, and can be rounded where nobody can check them.

"Design a leaderboard" sounds like a question with a one-line answer. Put every player in a Redis sorted set, ZADD each new score, read the top 100 with ZRANGE … REV and a player's place with ZREVRANK. For a few million players that is close to the whole design, and a good candidate says so early.

The follow-ups are where it gets harder. What rank am I, for a player 20 million places down? What happens when one board takes more writes than one Redis process can apply? Where do the scores live, and what happens when Redis loses some of them?

A leaderboard serves two reads, and they cost different things. "Who is on top?" needs a short list: 100 names in order, the same for everyone. "Where am I?" needs a count: how many players have a better score. A database index answers the first by reading 100 entries. It answers the second by walking every entry above you. AWS measured its own rank query, a count nested inside a select, at an average of 35 seconds on a table of 50 million rows, even with indexes.

A player's rank is a count of the players ahead of them, and only the rows on screen ever need to be a list. Counts add up across machines. They can be computed once and shared by everyone who asks. And they can be rounded where nobody can check them.

Most of this design follows from that. The sorted set wins because it keeps counts inside its links. A board split across 8 machines adds up 8 counts. The player who just submitted gets their rank from a count, before the board even holds their score. And the top 100 is one list for everyone, so the edge serves it.

Two reads, two costs
The bar is one board, best score at the top. The top 100, in green, is the same short list for every player (1). Player P sits 2,400,000 places down, and their rank is the count of everyone above them plus one, the orange bracket (2). The players around P are a second short list, five above and five below (3).The bar is one board, best score at the top. The top 100, in green, is the same short list for every player (1). Player P sits 2,400,000 places down, and their rank is the count of everyone above them plus one, the orange bracket (2). The players around P are a second short list, five above and five below (3).
The top 100 and the neighbours are short lists; the rank is a count. The bar is one board, best score at the top. The top 100, in green, is the same short list for every player (1). Player P sits 2,400,000 places down, and their rank is the count of everyone above them plus one, the orange bracket (2). The players around P are a second short list, five above and five below (3).

Understanding the problem

The general method for this part of the interview is in The First Five Minutes: Requirements.

A leaderboard ranks players by a score. Here it belongs to a mobile game with tens of millions of players. Every match ends with a score sent by the game server, and players look at boards for today, this week and all time, for the world, for their region and for their friends. Weekend events run boards of their own, which open empty and close at a set time.

Five different systems go by this name. Split them before drawing anything.

  1. A live game leaderboard. Every player's rank moves within seconds of each match. This is the one we're designing.
  2. Final standings. The exact order of a contest or a season after it closes, which decides prizes. It's computed once, offline, from the record of scores. This design produces it when each period closes.
  3. Top K by count. The most searched terms, for example. There the score is a count of events that the system has to compute first, often approximately, as search autocomplete does.
  4. Skill ratings. Elo or a matchmaking rating, computed from results. The game computes them, and a rating can fall, which this design's boards don't allow (section 3).
  5. Ranking content. Ordering posts by votes and age, as Reddit's front page does. That's a scoring problem more than a ranking one.

Functional requirements

Core:

  1. Show the top of a board. The top 100, for the world or for one region.
  2. Show a player's rank and the players around them, five above and five below.
  3. Record a score when a match ends, exactly once, and return the player's new rank in the same response.
  4. Daily, weekly and all-time boards, plus seasons and timed events that start empty. When two players have the same score, the one who reached it first ranks higher.
  5. Friends boards. The same ranking, among a player's friends.

Out of scope, deliberately:

  • Computing points and skill ratings. The game server does that.
  • Catching cheats beyond the checks at the door. A separate team reviews suspicious scores and can remove them.
  • Paying out rewards, which reads the final standings.
  • The friends graph itself, which a social service keeps.

Non-functional requirements

  1. Scale. 50 million players hold an all-time score, and 20 million play on a given day, about 10 matches each. An event takes up to 10 million entrants. These are assumptions, sized for a large mobile game.
  2. Latency. A top-100 read or a rank read answers in under 50 ms at p99, the latency that 99 percent of requests beat, measured at the server.
  3. Freshness. The player who submitted sees their new rank in the response. A rank read in the player's own region sees a new score within 2 seconds. The cached top 100 and other regions may take a few seconds more.
  4. Exact where someone can check. The top 10,000 of every board, and every final standing, are exact. Further down, a live rank may be off by up to 2,000 places.
  5. No accepted score is lost. Once the game server is told a score was recorded, it survives any one machine failing, and every board can be rebuilt from the record.

Requirement 4 carries the design, so write it in those words. If it says "every rank exact, live", rank reads in the last 10 minutes of one event need 15 to 27 Redis processes' worth of work instead of about 3 (deep dive 2).

Back of envelopeWrites on one board
The question is how many writes a single board takes,
on a normal day and at the end of an event.

Normal day
  scores a day      20M players × 10 matches     =   200M
  average           200M / 100,000 s             =  2,000/s
  peak, 5x                                       = 10,000/s
  boards one score can change: day, week and all-time,
    for the world and for the player's region    =      6
  sorted-set writes at peak, at most
                    10,000 × 6                   = 60,000/s
  the busiest single board                       = 10,000/s

The last 10 minutes of an event
  entrants still playing                            10M
  one match a minute each   10M / 60             ≈ 167,000/s
  the event board keeps totals, so every match
  writes it, all into one board
  ─────────────────────────────────────────────────────────
A normal board takes at most 10,000 writes a second. An
event board takes 17 times that, on one key.

The set up

Core entities

  • Player. An id, a home region and a display name.
  • Match result. One finished match: a match id chosen by the game server, the player, the points and the time the match ended. Written once and never changed.
  • Board. A ranking rule. It says which game mode it covers, whether it keeps each player's best score or their total, whether high or low scores win, its scope (world, region or friends), and when it resets.
  • Board entry. One player's standing on one board for one period: their score, and when they reached it. The board entry is the entity that matters. Rewards are paid from these rows, and every sorted set in this design is an index built from them.
  • Period. A day, a week, a season or an event. A board keeps one set of entries for each period.

System interface

GAME SERVER → SCORE SERVICE

POST /v1/matches/9c2e41d7-0b3f-4e5a-a1c8-6f2d90b7e413
{ "player_id": 81723, "mode": "classic", "points": 48210,
  "ended_at": "2026-11-09T23:59:50.412Z", "sig": "…" }

→ 200 { "boards": [
    { "board": "classic:world:day:2026-11-09",
      "score": 48210, "rank": 1843, "new_best": true },
    { "board": "classic:world:all",
      "score": 61900, "rank": 220517, "new_best": false } ] }

CLIENT → BOARD SERVICE

GET /v1/boards/classic:world:day:2026-11-09/top?limit=100
→ 200 { "as_of": "…", "entries": [ { "rank": 1, "player": …, "score": … }, … ] }
  Cache-Control: public, max-age=1, stale-while-revalidate=5, stale-if-error=1800

GET /v1/boards/classic:world:week:2026-W46/players/81723?around=5
→ 200 { "rank": 98204, "score": 57300, "above": […], "below": […] }

GET /v1/boards/classic:friends:week:2026-W46/players/81723
→ 200 { "rank": 4, "of": 37, "entries": […] }

Four things to note.

The game server submits the score, never the client. A score the client sends can be anything the client wants. Steam's leaderboards have a Trusted setting for this: with it on, clients can't set scores at all. Here the game server signs each result, and the score service checks the signature.

The match id is the idempotency key. The game server picks it before sending, and sends the same id on every retry. The record keeps it, so a retry gets the first answer back instead of counting the match twice.

ended_at picks the period, not the time of arrival. A match that ended at 23:59:50 counts for that day, even if it arrives after midnight (deep dive 4).

The top is public and the player read is private. The top-100 response is the same for every player and carries a cache header. The rank read is different for each player and carries none. Because the two are separate, the edge can serve most reads (deep dive 6).

All of that is the data plane. The control plane holds the board definitions and runs the scheduler that closes periods, freezes them and sets their expiry, the kind of timed job a distributed job scheduler runs. A key's name comes from the board's reset rule and the match's ended_at, so no service has to open a period. If the control plane is down, closing waits, and scores and reads carry on.


High-level design

1. The top of a board

The top 100 is a short list read from one end of an ordered structure. A database with an index on (board, period, score) answers ORDER BY score DESC LIMIT 100 by reading 100 index entries. A sorted set answers ZRANGE key 0 99 REV by walking 100 members from the high end. Both cost about the same, so this requirement doesn't choose the data store.

It also returns the same list to every player. A board's top 100 changes a few times a second at most, and nobody can tell a list one second old from a live one. So the response is cached at the edge for one second, and the data store behind it sees about one read a second per board, however many players open the screen. Deep dive 6 counts that.

The next requirement chooses the data store.

2. A player's rank, and the players around them

A rank is one plus the number of players with a better score. The players around them are two short lists, five entries on each side of their score. The lists cost the same as the top 100. The count is the hard part.

Which data store, and what actually forces it

Naive

One table, with an index on the score

Every score already lives in a database, so rank there. One row per player per board per period, an index on (board_id, period, score), and this query:

SELECT count(*) + 1 FROM board_entries
WHERE board_id = ? AND period = ? AND score > ?;

It's tempting because it's one data store, it keeps every score safely, and the top 100 and the neighbours are cheap reads from the same index.

The count is not cheap. The index keeps entries in score order, but it doesn't know how many sit above any point, so the database walks them and counts. A player in the middle of 50 million walks 25 million entries. Strava found the same in MySQL: the count is fast near the top of a board, and near the bottom it has to count most of the rows.

Strava chose MySQL for its new challenge boards and cached the score at about every 1,000th rank, so a count walks about 1,000 rows. The problem is the writes. A score that lifts a player from rank 2.4 million to 1 million moves about 1,400 of those checkpoints by one place each. Strava applies the changes in batches, which suits a monthly running challenge. At 10,000 new scores a second, the checkpoints would be rewritten all day.

Senior

A Redis sorted set

Redis keeps each sorted set in two structures that share every member: a hash table from member to score, and a skip list in score order. A skip list is a linked list with layers of shortcut links on top. Each node joins the layer above with probability 1/4, so each layer skips about four times as far as the one below it. A search starts in the top layer and drops down whenever the next link would overshoot.

Redis adds one thing to the textbook skip list: every link stores its span, how many places forward it goes.

How a skip list counts
Each link carries its span, how many places forward it goes. To find dee's rank, the search starts in the top layer and takes the link that spans 4 (1). The next top link would pass dee, so it drops a layer and takes a link that spans 2 (2), then drops again and takes one that spans 1 (3). The sum of the spans is dee's rank, found without visiting the members in between, in grey.Each link carries its span, how many places forward it goes. To find dee's rank, the search starts in the top layer and takes the link that spans 4 (1). The next top link would pass dee, so it drops a layer and takes a link that spans 2 (2), then drops again and takes one that spans 1 (3). The sum of the spans is dee's rank, found without visiting the members in between, in grey.
A rank is the sum of the spans on the path down, not a walk along the bottom. Each link carries its span, how many places forward it goes. To find dee's rank, the search starts in the top layer and takes the link that spans 4 (1). The next top link would pass dee, so it drops a layer and takes a link that spans 2 (2), then drops again and takes one that spans 1 (3). The sum of the spans is dee's rank, found without visiting the members in between, in grey.

So ZREVRANK never counts members one by one. It walks down to the member and adds up the spans of the links it took. That costs O(log N), where N is the number of members, and so do ZCOUNT and ZADD. The neighbours are a ZRANGE … REV around that rank.

This is the standard answer. Redis's documentation names leaderboards as a use for sorted sets, and AWS's guide to leaderboards on ElastiCache is built on one. It costs about 100 bytes of memory per member (deep dive 1), so 5 GB for the all-time board.

The other cost is that Redis keeps the data in memory and replicates it asynchronously. The Redis Cluster specification says there are usually small windows in which acknowledged writes can be lost when a primary fails. If Redis is the only copy, those scores are gone for good, and nothing is left to rebuild a board or pay a prize from.

Staff

Keep the record in a database, and rank in sorted sets built from it

Question the premise that one data store has to both keep the scores and rank them. The two jobs want different things. The record needs every match kept, exact history for prizes, and a write that is never lost. The ranking needs counts in O(log N), which means memory and one structure per board.

So the board entries live in a key-value store partitioned by player, DynamoDB here. Key-value store designs the single-key core of such a data store. The sorted sets are an index built from those rows, the way a search index is built from a table. Any of them can be thrown away and rebuilt. Redis then needs replicas to stay up, but not disks to stay correct.

The write rate rules out a single relational database. Each match writes a match row and up to six entries, so 10,000 matches a second at peak are up to 70,000 row writes, and an event's end needs 334,000 more. The course's working figure for one Postgres primary is 5,000 to 15,000 writes a second.

Every write in the path belongs to one player, so partitioning by player spreads them evenly. No player writes more than about once a minute, so the record has no hot key, even at an event's end.

The trade, sized. A full rebuild of every current board takes about 25 minutes (deep dive 5). A sorted set trails the record by the time a change takes to reach it, and section 3 hides that from the player who submitted.

What you give up. Two data stores, and a pipeline between them to run. Redis can also briefly disagree with the record, so prizes are paid from final standings computed from the record, never read from Redis.

Back of envelopeWhat one rank read costs
The question is whether rank reads can come from the
database, or need a structure that counts. The all-time
board holds 50M players, and every match asks for a rank.

Database, count(*) over the index entries above a score
  a player at the median     50M / 2           =   25M walked
  AWS's nested rank query, 50M rows, indexed    ≈   35 s each
  rank reads at peak                           = 10,000/s

Redis sorted set, ZREVRANK or ZCOUNT
  skip list layers, each kept with p = 1/4
                             log base 4 of 50M ≈   13
  links followed: a few per layer              ≈ a few dozen
  ─────────────────────────────────────────────────────────
The database walks 25 million entries to rank a median
player. The skip list follows a few dozen links for any
player, at the top of the board or the bottom.
data storewhat goes in itwhat forces it
DynamoDB, partitioned by playermatch results and board entries70,000 row writes a second at peak, 334,000 at an event's end, each for one player
Redis sorted sets, one key per board and periodeach player's score, packed with a tie-breaka rank is a count, and the skip list answers it in O(log N)
object storage, such as S3final standingsprizes are paid from an exact ranking that never changes

The tables

-- DynamoDB. Both tables are partitioned by player.
matches (
  player_id     bigint,      -- partition key
  match_id      uuid,        -- sort key; chosen by the game server
  mode          text,
  points        bigint,
  ended_at      timestamp,   -- picks the period
  primary key (player_id, match_id)
)

board_entries (
  player_id     bigint,      -- partition key
  board_period  text,        -- sort key: 'classic:eu:week#2026-W46'
  score         bigint,      -- best or total, by the board's kind
  reached_at    timestamp,   -- when this score was first reached
  primary key (player_id, board_period)
)

-- Config, read through a cache by every service
boards (
  board_id      text primary key,  -- 'classic:eu:week'
  kind          text,              -- BEST or TOTAL; scores only rise in both
  low_wins      boolean,           -- race times: stored negated, so the score still rises
  reset         text,              -- DAY, WEEK, SEASON, EVENT, NEVER
  reset_zone    text,              -- one zone per board; 'UTC' for the world
  grace         interval           -- writes accepted after close: 10 minutes
)

-- Redis. One sorted set per board and period.
lb:classic:world:day:2026-11-09    member player_id, score composite
lb:classic:world:week:2026-W46
lb:classic:world:all
lb:classic:eu:day:2026-11-09       and the same for every region
lb:event:42:s0 … lb:event:42:s7    an event board, split by player

Three things to note.

Both tables are keyed by player, and nothing is keyed by board. No query on the live path asks the record for every entry on a board. The sorted sets answer every live question about a board. Only the standings job reads a whole period from the record, once, after it closes.

reached_at changes only when the score does. It's the time the player first reached their current score, so matching that score again later doesn't move them behind anyone. Deep dive 3 packs it into the sorted set's score, which makes that score a composite of points and time.

The period is part of the key, in both data stores. A new day is a new key, so nothing is ever reset in place (deep dive 4).

The operations that carry the product

-- 1. Record a match, in the score service
Query board_entries where player_id = p     -- current entries, one partition
TransactWriteItems
  Put    matches(p, match_id, …)            if match_id doesn't exist
  Update board_entries(p, board_period)     one per entry this match improves
         set score, reached_at              if score = the value just read

-- 2. The rank the response returns, on a replica, for new composite c
ZCOUNT lb:classic:world:day:2026-11-09 (c +inf     -- rank = count + 1

-- 3. The updater, for each batch of change records
ZADD lb:classic:world:day:2026-11-09 GT c1 p1 c2 p2 …
ZREM lb:classic:world:day:2026-11-09 p              -- for a REMOVE record

-- 4. A rank and its neighbours, on a normal board
ZREVRANK lb:… p                                    -- r, counted from 0
ZRANGE   lb:… max(r-5, 0) r+5 REV WITHSCORES

-- 5. The top 100
ZRANGE lb:… 0 99 REV WITHSCORES

Operation 2 runs most often: once per board shown, on every match. Operation 1 is the one an interviewer pushes on, usually by asking what happens when the response is lost. The game server retries with the same match id. The Put fails its condition, and the service returns the scores it stored with the first attempt.

The service reads the entries first and puts only the ones this match improves into the transaction, because a DynamoDB transaction fails as a whole when any condition fails. Each update is conditional on the score it just read. A failed match id check means a retry. A failed score check means the player's own previous match landed in between, so the service reads again and tries once more.

3. Recording a score, exactly once

Before anything is written, the score service checks the result at the door. The signature must come from a game server. The points must sit inside the mode's limits: Google Play Games Services lets a game set lower and upper limits on each board to discard scores that are clearly fraudulent. And a player can't finish matches faster than the shortest match allows. Anything subtler goes to the review team, which can remove a player's scores later.

The record is then one transaction, as above. The question is how a change reaches the sorted sets, and how the player sees their new rank without waiting for it.

Naive

The game server sends ZINCRBY straight to Redis

One command per board, and the board updates within a millisecond. It's the shortest path there is.

A timeout after the increment applied looks the same as a timeout before it, so the game server retries, and the match counts twice. Nothing records the match, so there's nothing to check a board against, nothing to rebuild from and nothing to pay prizes from. And a primary failover drops the last few acknowledged increments, with nobody told.

Senior

Commit the record, then update Redis in the same request

The service commits the transaction, then writes each board it changed, with the new absolute score, and reads the rank back. A retry finds the match id already recorded and writes the same absolute scores again, which changes nothing, because setting a value is already idempotent. Most teams build this.

It's a dual write: two data stores updated one after the other, with nothing tying them together. A retry that lands after the player's next match writes an older absolute score over the newer one. If the service dies between the commit and the Redis writes, the board misses that score until the player beats it, because nothing else will write it. The scores a failover loses are missed the same way.

Every request also writes six sorted sets, so at an event's end the request path itself carries the hot key.

Staff

Feed the boards from the record's change stream, and rank by count

Question the premise that the board has to hold the new score before the player can see their rank. A rank is a count of the players ahead. The service knows the new score the moment the transaction commits, so it asks each board how many players are ahead of that score: ZCOUNT key (c +inf, plus one. The player's own entry still holds their old, lower score, so it isn't counted. The count is exact against the replica it runs on, which is milliseconds behind its primary, though the board doesn't hold the new score yet.

The rank before the board has the score
Time runs left to right. The transaction commits P's new best, 48,210, and c is that score packed with its time (1). Two milliseconds later the service counts the members of today's board above c on a replica, and returns P's rank (2). The board still holds P's old score, in grey. About a second later the updater writes c to the board (3), in green, and other players see the new score from then on.Time runs left to right. The transaction commits P's new best, 48,210, and c is that score packed with its time (1). Two milliseconds later the service counts the members of today's board above c on a replica, and returns P's rank (2). The board still holds P's old score, in grey. About a second later the updater writes c to the board (3), in green, and other players see the new score from then on.
The response counts the players ahead of the new score, so it doesn't wait for the board. Time runs left to right. The transaction commits P's new best, 48,210, and c is that score packed with its time (1). Two milliseconds later the service counts the members of today's board above c on a replica, and returns P's rank (2). The board still holds P's old score, in grey. About a second later the updater writes c to the board (3), in green, and other players see the new score from then on.

Then one path feeds the boards. DynamoDB Streams emits a record for every changed entry, in order for each item, and a deleted entry arrives as a REMOVE record. A small fleet of republishers reads the stream and copies every record into a Kafka topic, keyed by player id.

Each stream shard has one reader at a time, and if it dies another republisher takes the shard over, which the DynamoDB Streams Kinesis adapter coordinates. The republishers read a parent shard before its children, as the Streams documentation requires, and write with Kafka's idempotent producer, which writes one copy of each record and keeps their order through retries. Kafka keeps order within a partition, as change data capture notes, so one player's records stay in order.

The extra hop has two reasons. DynamoDB's documentation says no more than two processes should read a stream shard at once, and every region, replay and rebuild needs to read. And the stream keeps records for 24 hours, while the topic keeps them as long as replays need. A topic is a log the updater can read again from an earlier offset, which message queues vs event streams explains.

Updaters read the topic. Each record becomes a ZADD with the GT flag, which only ever raises a member's score, or a ZREM for a REMOVE record. The updater batches each key's records and keeps them in stream order.

Absolute scores with GT make every write safe to repeat and safe to reorder, as long as a board's scores never fall. A record delivered twice changes nothing the second time, and an older record that arrives after a newer one is refused. That covers every board here: best-score boards, and total boards whose matches never take points away, the event board included. A low-wins board, such as race times, stores the time negated, so a better time is still a higher score. A ratings board, whose scores fall, would need a version with every write instead. Order still matters across a REMOVE, which is why the updater keeps each player's records in stream order.

So on these boards a replay after a failover, or an updater that restarts, needs no coordination (deep dive 5). It's the rule from change data capture: a copy applies state, not differences.

The trade, sized. The submitter gets their rank in the response: one ZCOUNT per normal board shown, or the event snapshot on an event board (deep dive 2). Other players see the score once the stream and the topic deliver it, which DynamoDB's documentation calls near real time, and requirement 3 gives that 2 seconds. The request path does no Redis writes at all. The app keeps the response's rank on screen until a board read shows the new score, so the submitter never sees their old one again.

What you give up. A second log, Kafka, to run between the record and the boards. And GT only raises, so taking a score away needs a path of its own.

4. Daily, weekly and all-time boards

Each board keeps one sorted set per period, and the period is in the key: lb:classic:world:day:2026-11-09, lb:classic:world:week:2026-W46, lb:classic:world:all. The updater computes the key from the board's reset rule and the match's ended_at. A match can change today's, this week's and the all-time key, for the world and for the player's region.

A new period is a new key that starts empty, so there is no reset to run. Old keys expire once nobody reads them. A new season is a new season number, and a timed event gets keys of its own, created when it opens.

Ties follow one rule in every period: the earlier player wins. Deep dive 3 puts that into the score, and deep dive 4 covers when a day ends.

5. Friends boards

A player has a few dozen friends, and their friends board is the same ranking limited to them. There are two ways to build it.

Keep a sorted set per player. Each score change is copied into the set of every friend.

Build it when asked. Read the friend list from the social service, which the board service caches, and fetch every friend's score in one command: ZMSCORE key f1 f2 … f50. Sort the 50 scores in the board service. The player's rank among friends is one plus the number of friends with a higher score.

Back of envelopeCopy every change, or read 50 scores
The question is whether to keep a sorted set per player
for their friends, or build it on each read. 50 friends
each, on average, assumed.

Copy each change into every friend's set
  score changes at peak, day, week and all-time
                       10,000 × 3            =    30,000/s
  copies               30,000 × 50           = 1,500,000/s
  memory: 50-entry sets fit Redis's compact listpack
  form, about 25 B an entry, assumed
                       20M players × 3 periods
                       × 50 entries × 25 B   ≈     75 GB

Build on read, one ZMSCORE of the friend list
  friends-board opens  20M × 2 a day / 100,000 s
                       × 5 peak              =     2,000/s
  scores looked up     2,000 × 50            =   100,000/s
  ─────────────────────────────────────────────────────────
Copying costs 1.5 million writes a second and 75 GB of
memory, to save one command that looks up 50 scores.

So friends boards are built on read. ZMSCORE costs O(F), where F is the number of friends asked for, so the friend list is capped, at 500 here. A player with more sees the 500 friends they played with most recently.


Deep dives

Deep dives 1, 2 and 3 come up in most versions of this interview.

1. How big is one board, and what limits it?

Section 2 chose sorted sets. Now check whether each board fits in one key, by memory and by writes.

Back of envelopeMemory and writes, per key
The question is whether every board fits in one Redis
key, by memory and by writes.

Memory per member
  skip list node and links, member string and hash
  entry, from Redis 7.4's source                ≈  100 B
Boards held in memory
  all-time          50M × 100 B                  =    5 GB
  this week         35M × 100 B, assumed         =  3.5 GB
  today             20M × 100 B                  =    2 GB
  regional copies of all three                   × 2
  yesterday and last week, kept for display      +   11 GB
                                                 ≈   32 GB
  an event board    10M × 100 B                  =    1 GB

Writes on one key at peak
  budget: a Redis process at 50% of 100,000
  operations/s, counting each member a batched
  ZADD writes as one operation                   = 50,000/s
  the busiest normal board                       = 10,000/s
  an event's last 10 minutes                     = 167,000/s
  ─────────────────────────────────────────────────────────
Memory fits on a few nodes, and a normal board uses a
fifth of one process. The event board needs more than
three processes' worth of writes on a single key.

The 100,000 operations a second is the course's working figure for one Redis process, from back-of-envelope estimation. Running it 50 percent busy at peak is the low end of the 50 to 70 percent that page recommends. A batched ZADD saves network round trips, but each member it writes is still a skip list insert, so the budget counts members.

So the normal boards go into a Redis Cluster of three primaries, about 11 GB and 20,000 writes a second each. Each primary has one replica, which applies those same writes and serves the rank reads. Memory and writes both grow only as players do, so this fleet is planned ahead rather than autoscaled.

The event board doesn't fit. Redis Cluster places each key in one hash slot on one primary. It spreads keys across machines and never splits one. Consistent hashing works through what one key that outgrows its node does to a cluster. Replicas don't help either, because each replica applies every write its primary takes.

So the event board is split into 8 keys by a hash of the player id, on 8 primaries of its own, about 21,000 writes a second each. Four primaries would carry the writes, at 42,000 each. But each replica applies every write its primary takes, so 42,000 applied writes would leave each replica little room for the event's reads, which deep dive 2 counts.

The services around Redis hold no data. The score service and the board service scale on requests behind a load balancer, and the updaters scale with the topic's partitions.

The record and the event's Redis are the tiers with a peak to plan for. An event's end writes 334,000 rows a second to the record, and its board needs 16 Redis processes, 8 primaries and their replicas, in each region: 48 across the three regions of deep dive 7. Both are added before the event opens. Its start time is known weeks ahead, so that capacity is planned from the event's forecast, as capacity planning recommends for any tier that holds data.

2. Ranks on a board split across machines

Deep dive 1 split the event board into 8 sorted sets, lb:event:42:s0 to s7, each holding the players whose id hashes to it. Writes are solved. But every submission still wants a rank, 167,000 a second at the end, and the players ahead of any score are now spread over 8 keys.

Naive

Keep one key, and add replicas

Replicas serve reads, and an event's end is mostly read traffic, so more replicas look like the fix.

They don't fix the writes. Each replica applies every write its primary takes, so each one is as far past the budget as the primary: 167,000 writes a second against 50,000. Replicas add read capacity to one key and never add write capacity.

Senior

Split by player, and add up a count from every shard

Counts add, so a rank on a split board is the sum of 8 counts. ZCOUNT (c +inf on each shard gives the players ahead in that shard, and their sum plus one is the exact rank.

The lists merge. The top 100 is the merge of each shard's own top 100, because any member of the global top 100 is in the top 100 of its own shard. A search engine merges its shards' top hits the same way, as inverted indexes describes. The neighbours are each shard's five members on either side of the score, merged, keeping the closest five on each side.

Every answer is exact, and this is what most teams build. The cost is that every rank read asks every shard. 167,000 rank reads a second become 1.3 million ZCOUNT calls, about 27 processes' worth of budget for rank reads alone, and every neighbours read takes 16 calls. Each read also waits for the slowest of 8 shards, the fan-out cost that partitioning and sharding works out.

Staff

Count once a second at fixed scores, and share the counts

Question the premise that each rank read needs its own count. 167,000 players a second ask the same question about different scores: how many players are above this score? So answer it once a second for a fixed set of scores, and let every read use the answer.

A snapshot job runs ZCOUNT (b +inf on each shard for 20,000 boundary scores every second, and adds up the 8 counts for each boundary. It also merges the shards' top 100. Then it publishes the counts and the top 100 to every score service and board service.

The boundaries are cut so each bucket between two of them holds about 500 players. A rank read is then a search in memory. A score below the top 10,000 gets the count above its bucket's upper boundary, plus an estimate of its place inside the bucket. The estimate assumes the bucket's players are spread evenly across its range of scores.

A rank read from the shared counts
The ruler is the event board's scores, with two of the 20,000 boundaries marked. 2,399,412 players score above the upper boundary, summed from 8 shards a second ago (1). P's score sits a third of the way down the bucket, in orange, so P is placed about a third of the way into its players (2). P's true place is somewhere in the green bucket, give or take the players who passed P's score since the counts were taken (3).The ruler is the event board's scores, with two of the 20,000 boundaries marked. 2,399,412 players score above the upper boundary, summed from 8 shards a second ago (1). P's score sits a third of the way down the bucket, in orange, so P is placed about a third of the way into its players (2). P's true place is somewhere in the green bucket, give or take the players who passed P's score since the counts were taken (3).
The count above the bucket is exact as of a second ago; only the place inside it is estimated. The ruler is the event board's scores, with two of the 20,000 boundaries marked. 2,399,412 players score above the upper boundary, summed from 8 shards a second ago (1). P's score sits a third of the way down the bucket, in orange, so P is placed about a third of the way into its players (2). P's true place is somewhere in the green bucket, give or take the players who passed P's score since the counts were taken (3).

A score above the boundary where the counts pass 10,000 gets the senior answer instead, a live sum of 8 counts, so the ranks people check stay exact. Only about 167 of those players submit a second.

The trade, sized. Rank reads cost about 161,000 calls a second instead of 1.3 million, and no Redis call at all for most reads. A rank below the top 10,000 is off by its bucket plus the players who passed that score since the counts were taken. With the churn assumed below, that's about 2,000 places at most, which requirement 4 allows. The churn is an average, so a burst past one score can push a rank further for a second.

The boundaries are only arguments to a query. As scores rise during the event, the job splits any bucket that passes about 800 players and merges small neighbours, so it keeps about 20,000 boundaries, using the counts it just took. No data moves. A service holding a snapshot older than 2 seconds treats it as stale and leaves the rank out, as it does when Redis is down.

What you give up. Ranks below 10,000 are estimates, a second old. The final standings come from the record after the event closes.

Back of envelopeRank reads at an event's end
The question is what 167,000 rank reads a second cost
with the board split into 8 keys, at 50,000 operations
a second per Redis process.

Add up a count from every shard, per read
  ZCOUNT calls       167,000 × 8            ≈   1.3M/s
  processes          1.3M / 50,000          ≈      27

Count once a second at fixed scores
  boundaries                                =  20,000
  ZCOUNT calls       20,000 × 8             = 160,000/s
  live counts for scores in the top 10,000
                     10,000 / 60 s × 8      ≈   1,300/s
  processes          161,300 / 50,000       ≈     3.2

Error below the top 10,000
  players per bucket 10M / 20,000           =     500, on average
  split past 800, so with a second's growth
  a bucket holds at most about              =   1,000
  players passing a score in the second the counts
  are old: one match lifts a total past about
  0.6% of the board, assumed
                     167,000 × 0.6%         ≈   1,000
  error at that churn
                     1,000 + 1,000          ≈   2,000
  ─────────────────────────────────────────────────────────
Counting per read needs about 27 Redis processes' worth
of work in an event's last 10 minutes. Counting once a
second needs about 3, and a rank below the top 10,000
lands within about 2,000 places at the assumed churn.

The neighbours come from the player's own shard: the five members just above and just below P's score there, two range reads. The shard holds one entrant in 8, so these are players near P rather than P's exact neighbours. The app refreshes this half of the screen once a minute while the board is open. With 1 million boards open at the end, assumed, that's about 17,000 views and 33,000 calls a second.

A player in the top 10,000 gets an exact rank from 8 live counts and exact neighbours merged from all 8 shards. If all 10,000 of them keep the board open, that's about 167 views a second, 1,300 calls for ranks and 2,700 for neighbours.

Each event primary's replica carries an eighth of all this. It applies its primary's 21,000 writes a second, runs 20,000 of the snapshot's counts and about 5,000 reads for ranks and neighbours, and stays under the 50,000 budget.

Splitting by score range instead of by player makes exact ranks cheaper, but not cheap. Each shard holds one range of scores, and an exact rank is a live ZCARD of every shard above yours plus one ZCOUNT in your own. That's 4.5 calls on average with 8 shards, about 750,000 calls a second, or 15 processes. And a score that crosses a range boundary moves between two keys, two writes that aren't atomic. So exact ranks for everyone cost 15 to 27 processes' worth of work, against about 3.

3. Ties, and what a double can hold

Requirement 4 says the earlier player wins a tie. Redis orders members with equal scores by their bytes, so with plain points as the score, the player id would decide every tie. So the time goes into the score.

The score becomes a composite. Points take the high bits, and the low 23 bits hold 2^23 − 1 − t, where t is the seconds since the season began. One point is worth more than any time difference, so more points always rank higher. Among equal points, the smaller t gives the larger composite, so the earlier player ranks higher. Points come back out as the composite divided by 2^23, rounded down.

The limit is the score's type. A Redis score is a 64-bit IEEE 754 double, and Redis's documentation says it holds integers exactly only between −2^53 and 2^53. Past 2^53 the gap between neighbouring doubles is 2, and past 2^54 it's 4.

Back of envelopeBits for points, bits for the tie-break
The question is how large a score the composite can
hold before the tie-break is rounded away.

Exact integers in a double                     up to 2^53
Tie-break: seconds since the season began, 90 days
  90 × 86,400                               =  7,776,000
  bits needed                               =  23  (2^23 = 8,388,608)
Points get the rest
  53 − 23                                   =  30 bits
  largest score       2^30 − 1              =  1,073,741,823

Milliseconds instead of seconds
  90 × 86,400 × 1,000                       ≈  7.8B, 33 bits
  points left         53 − 33               =  20 bits, 1,048,575

Past the limit: 1.5B points, 23 bits of seconds
  1.5B × 2^23                               ≈  1.26 × 10^16
  that's above 2^53, so the gap is 2. Players who reached
  it at seconds 102, 103 and 104 all get the same score.
  ─────────────────────────────────────────────────────────
Seconds leave 30 bits of points, about a billion.
Milliseconds leave 20 bits, about a million. Past 2^53 the
tie-break is rounded away, and nothing reports an error.
Points and the tie-break share 53 bits
A double has a sign, 11 exponent bits and a 53-bit significand, 52 bits stored plus one implied (1). The composite uses the significand as an integer: 30 bits of points, then 23 bits of inverted seconds, in orange (2). Above 2^53 the gap between doubles is 2, so three composites one second apart round to the same value, in red (3).A double has a sign, 11 exponent bits and a 53-bit significand, 52 bits stored plus one implied (1). The composite uses the significand as an integer: 30 bits of points, then 23 bits of inverted seconds, in orange (2). Above 2^53 the gap between doubles is 2, so three composites one second apart round to the same value, in red (3).
A double holds 53 exact bits, and the composite has to fit inside them. A double has a sign, 11 exponent bits and a 53-bit significand, 52 bits stored plus one implied (1). The composite uses the significand as an integer: 30 bits of points, then 23 bits of inverted seconds, in orange (2). Above 2^53 the gap between doubles is 2, so three composites one second apart round to the same value, in red (3).

So the mode's largest possible score picks the time unit, and the bounds check at the door enforces it. An all-time board can't count seconds since launch in 23 bits, because 2^23 seconds is only 97 days. It counts minutes, which last almost 16 years.

4. When does a day end?

A daily board needs one answer to "which day is it?" There are three clocks to choose from: each player's local midnight, one fixed time for everyone, or a midnight chosen for each region.

Local midnight breaks a world board. A player in Tokyo would start a new day while a player in London was still on the old one, so "today's board" would mean one window for each UTC offset in use. So a world board resets at one fixed time for everyone. Google Play Games Services resets daily boards at UTC−7 all year, and weekly boards at midnight between Saturday and Sunday in the same zone. PlayFab resets at 00:00 UTC, and weekly boards on Monday.

A regional board resets at one midnight chosen for its region, stored as the board's reset_zone. A region can span several time zones, so for some of its players that reset falls at another hour.

ended_at puts each match in a period, which is the event time rule from the ad click aggregator. A match from 23:59:50 whose result arrives at 00:01:30, after a retry, still counts for the old day. A closed period keeps accepting matches for a grace window. PlayFab accepts writes to a reset statistic's old version for up to 10 minutes, then locks it, and this design uses the same 10 minutes.

A day's board around midnight
A match ends at 23:59:50 and its result arrives at 00:01:30 (1). Its ended_at belongs to the 9th, so it goes into the 9th's key, the top lane, while new matches go into the 10th's (2). At 00:10 the grace window ends and the 9th is frozen (3). The standings job sorts the 9th's entries from the record and writes final standings to S3 (4). The key expires 2 days later.A match ends at 23:59:50 and its result arrives at 00:01:30 (1). Its ended_at belongs to the 9th, so it goes into the 9th's key, the top lane, while new matches go into the 10th's (2). At 00:10 the grace window ends and the 9th is frozen (3). The standings job sorts the 9th's entries from the record and writes final standings to S3 (4). The key expires 2 days later.
The match's end time picks the key, and the old key stays open for 10 minutes. A match ends at 23:59:50 and its result arrives at 00:01:30 (1). Its ended_at belongs to the 9th, so it goes into the 9th's key, the top lane, while new matches go into the 10th's (2). At 00:10 the grace window ends and the 9th is frozen (3). The standings job sorts the 9th's entries from the record and writes final standings to S3 (4). The key expires 2 days later.

After the grace window, the scheduler marks the period closed and the score service refuses matches for it. Then the standings job exports the period's entries from the record, sorts them, writes final standings to S3, and compares its top 10,000 with the sorted set's. Any difference is a bug somewhere in the stream path, found before prizes go out.

Daily keys expire 2 days after they close, so players can still see yesterday's board. Weekly keys last 2 weeks. An event's keys go once its results are published. The all-time key never expires.

A reset itself adds little load, because the new key starts empty and each player's first match of the day is one insert. The product can add load. A push notification to every player saying the new daily board is open brings them all back in the same minute. Spread that push over the first hour.

5. What happens when Redis loses scores?

Redis loses scores in two ways. A failover drops the last writes a primary acknowledged before its replica caught up. A larger failure, or a change to how scores are packed, means rebuilding boards from nothing.

A failover. Redis Cluster promotes a replica after its node timeout, as distributed cache describes, and the writes the old primary hadn't sent are gone. The updater watches for promotions. When one happens, it replays the topic from a few minutes before the failover.

The replay applies each player's records again, in order. A score the new primary already has is refused by GT, and a lost one is written again. Before it starts, the updater reads the window once for REMOVE records, and drops any earlier record for a player removed later in the window, so a banned player never reappears on the live board. The updater skips records for periods whose keys have expired, so a replay can't bring one back. A record from a period inside its grace window, or just closed, is still applied.

A replay across a ban
In both rows, P reached 9,000 and was then banned, and the updater replays the topic from before both changes. In the top row the ban was a lower score, 0. The replay writes 9,000 with GT (1), then GT refuses 0 because it's lower (2), so P is back at 9,000, in red. In the bottom row the ban deleted P's entry. The replay skips the 9,000, in grey, because a REMOVE for P comes later in the window, and runs ZREM (3), so P stays off the board, in green.In both rows, P reached 9,000 and was then banned, and the updater replays the topic from before both changes. In the top row the ban was a lower score, 0. The replay writes 9,000 with GT (1), then GT refuses 0 because it's lower (2), so P is back at 9,000, in red. In the bottom row the ban deleted P's entry. The replay skips the 9,000, in grey, because a REMOVE for P comes later in the window, and runs ZREM (3), so P stays off the board, in green.
A ban written as a lower score is undone by a replay; a ban written as a REMOVE record holds. In both rows, P reached 9,000 and was then banned, and the updater replays the topic from before both changes. In the top row the ban was a lower score, 0. The replay writes 9,000 with GT (1), then GT refuses 0 because it's lower (2), so P is back at 9,000, in red. In the bottom row the ban deleted P's entry. The replay skips the 9,000, in grey, because a REMOVE for P comes later in the window, and runs ZREM (3), so P stays off the board, in green.

A rebuild. A rebuild writes into new keys while the old ones keep serving, if they still exist. It takes four steps.

  1. Note the topic's current offset.
  2. Scan the current periods from the record with ConsistentRead, so the scan includes every write completed before it began, and load them into the new keys with batched ZADD. A consistent scan costs twice the read capacity.
  3. Replay the topic from the noted offset into the new keys, so every change made during the scan is applied again after it, in order.
  4. When the replay has caught up, switch the board service to the new keys.

A record replayed from before the scan can set a member back for a moment, the time travel change data capture describes. A later record fixes it, and nobody reads the new keys until the replay has caught up. Entries for closed days and weeks are deleted from the record once their final standings are in S3, so the scan reads little besides the current periods.

Back of envelopeHow long a rebuild takes
The question is how long boards are missing after Redis
loses everything, and so whether Redis needs disks.
The scan rate is an assumption.

Rows in the current periods
  all-time 50M + week 35M + day 20M, × 2 for regions
                                                ≈   210M
Scanning the record, 200,000 rows/s
  210M / 200,000                                ≈ 1,050 s, 18 min
Loading Redis at the budget, 50,000 members/s
per primary, 3 primaries
  210M / 150,000                                ≈ 1,400 s, 23 min
Scan and load run side by side. Then replay the
changes made meanwhile, at average traffic,
2,000 matches/s × 6 boards
  12,000/s × 1,400 s                            ≈    17M
  17M / (150,000 − 12,000)                      ≈   120 s
Replay after one failover: 5 minutes of one
primary's 20,000 writes/s, while new ones arrive
  20,000 × 300 s                                =     6M
  6M / (50,000 − 20,000)                        =   200 s
  ─────────────────────────────────────────────────────────
A full rebuild takes about 25 minutes, and Redis's write
budget sets that, not the scan. A replay after one
failover takes about 3 minutes.

So Redis keeps a replica for each primary, which turns a failed machine into seconds. It keeps periodic snapshots to make a restart shorter. It doesn't need to write every command to disk, because the record already holds every score. Strava's older boards were rebuilt from other data stores too, and its write-up says the rebuild time grew from about an hour under 100,000 athletes to possibly more than a day past a million. Know that number before you need it.

While a board is down or rebuilding, the design degrades in a set order. Matches are still recorded, so no score is lost. The response leaves out the rank and says it's updating. The board service answers 503 while it can't read the board, and the top 100 keeps coming from the edge, up to 30 minutes stale, longer than a full rebuild. Friends boards say they're unavailable.

6. Caching the top 100 at the edge

The top-100 response is the same for every player, so the CDN, a content delivery network, caches it in its points of presence (PoPs). Each PoP keeps it for one second and refreshes it in the background while serving the old copy, with stale-while-revalidate. If the board service answers with an error such as 503, stale-if-error lets the PoP keep serving the old copy for up to 30 minutes. RFC 5861's rule covers only 500, 502, 503 and 504 responses, so the board service returns 503 rather than timing out.

Nothing invalidates the cached copy. The lifetime is so short that expiry alone keeps it fresh enough, the first of the three options in caching strategies. CDNs and edge compute makes the general case for a one-second lifetime on a shared response. Behind a shield tier, one upper cache that the PoPs fill from, the board service sees about one read a second per board, whatever the traffic.

That matters most at an event's end. Say 1 million players keep the event board open, as deep dive 2 assumed, and their app refreshes the top 100 every 5 seconds. That's 200,000 requests a second for one response, the hot key on the read side, and the edge turns it into about one request a second.

The personal half of the screen stays uncached: the player's rank and the players either side. On an event board it refreshes once a minute, which deep dive 2 priced.

7. Multi-region

Three regions serve the game: the Americas, Europe and Asia. Each player has a home region, where their account lives.

The record is partitioned by home region. A player's matches and board entries are written in their home region, so a submit commits in a few milliseconds. Each region's record is copied asynchronously to one other region for disaster recovery, as multi-region and disaster recovery describes for data with one write region per key.

The boards are replicated in full. Each region's republishers copy its DynamoDB stream into that region's Kafka topic, so each stream shard still has one reader. Every region's updaters read all three topics, two of them across regions, and build every board, world boards included. Every rank read and every top-100 read is then local.

The cost is three copies of every board, about 96 GB of Redis for the normal boards instead of 32, and 48 processes for the event board instead of 16. Each region also pulls the other regions' changes. At peak, 60,000 changes a second across three regions, at a few hundred bytes each, is a few megabytes a second per link.

A score from Europe reaches the Asian copy of a world board a second or two after it reaches Europe's. Requirement 3 allows that for other regions.

Counts add, so there's an alternative that saves memory. Each region could hold only its own players, and a world rank would be the sum of three regional counts. That saves two thirds of the memory, and costs two cross-region calls on every rank read, around 150 ms each. Memory is the cheap resource here, so every region holds the full board.

If a region fails, its players move to the region holding their record's copy, losing the last seconds of changes that hadn't been copied yet. Every region's boards keep serving, without the failed region's last few seconds of scores.

8. How do you know it is working?

During an incident you need four answers quickly: are scores reaching the boards, is any key near its limit, do the boards agree with the record, and are submissions being refused.

  • Lag from the record to the boards, in seconds. That's the republishers' place in each DynamoDB stream, and each updater's place in the topics. The age of the event snapshot belongs here too, and it should stay under 2 seconds. Requirement 3 allows 2. A lag that keeps growing means a reader has stopped or a key is saturated.
  • Operations a second per Redis primary, and per event shard. The event shards run closest to the 50,000 budget, and the cluster's total hides them.
  • Board against record. Each minute, a checker picks 1,000 random players, reads their entries from the record and their scores from Redis with ZMSCORE, and counts the differences older than the lag. That count should be zero. At every close, the standings job compares its top 10,000 with the sorted set's.
  • Refused submissions, by reason. A rise in duplicate match ids means game servers are retrying. A rise in out-of-bounds scores means a cheat or a client bug.

Don't label metrics by player. Each label value is its own time series, and 50 million of them would sink the metrics backend.


Final design

The final design, with the path of one match
Blue is the game servers and clients, purple the score and board services, orange the record, the stream, the Kafka log and Redis, teal the republishers, the updaters and the snapshot and standings jobs, yellow the control plane, and grey the CDN and telemetry. The normal boards sit on three Redis primaries, and the event board on 8 primaries of its own. The badges follow the eight steps below.Blue is the game servers and clients, purple the score and board services, orange the record, the stream, the Kafka log and Redis, teal the republishers, the updaters and the snapshot and standings jobs, yellow the control plane, and grey the CDN and telemetry. The normal boards sit on three Redis primaries, and the event board on 8 primaries of its own. The badges follow the eight steps below.
The record takes every match once, and every board is an index built from it. Blue is the game servers and clients, purple the score and board services, orange the record, the stream, the Kafka log and Redis, teal the republishers, the updaters and the snapshot and standings jobs, yellow the control plane, and grey the CDN and telemetry. The normal boards sit on three Redis primaries, and the event board on 8 primaries of its own. The badges follow the eight steps below.

One match, end to end:

  1. The game server sends the signed result with its match id. The score service checks the signature, the mode's limits and the player's match rate.
  2. The score service reads the player's current entries and writes the match and every improved entry in one DynamoDB transaction. A match id already recorded returns the stored result.
  3. For each board in the response, the score service returns a rank. On a normal board it counts the members above the new composite score on a Redis replica. On the event board it reads the snapshot in memory, or sums 8 live counts for a score in the top 10,000.
  4. DynamoDB Streams emits each changed entry, and a republisher copies it into a Kafka topic keyed by player. Updaters in every region write batched ZADD GT for new scores and ZREM for REMOVE records, and skip periods whose keys have expired.
  5. A client asks for the top 100. The CDN answers from a copy about a second old. On a miss the board service reads ZRANGE … REV from a replica, or the snapshot's merged top 100 for the event board.
  6. A client asks for its rank and neighbours. On a normal board the board service reads ZREVRANK and ZRANGE … REV. On the event board it uses the snapshot and the player's own shard, or 8 live counts and the 8 shards' neighbours for a player in the top 10,000. It builds friends boards from one ZMSCORE.
  7. On the event board, a snapshot job counts the 8 shards at 20,000 fixed scores every second, merges their top 100, and publishes both to the score and board services.
  8. When a period's grace window ends, the scheduler freezes it. The standings job sorts its entries from the record into final standings in S3, and the key expires later, freed in the background.

The numbers behind the shape: a member costs about 100 bytes, so the normal boards fit in about 32 GB on three primaries. A normal board takes at most 10,000 writes a second, a fifth of one process. An event's end takes 167,000, so its board is split into 8 keys on 8 primaries of its own. Counting once a second keeps its rank reads to about 161,000 Redis calls a second instead of 1.3 million. A full rebuild takes about 25 minutes.


What is expected at each level

How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.

Mid-level

Breadth matters more than depth at this level, and it's fine to be led.

You should reach a sorted set, and use ZADD, ZRANGE and ZREVRANK correctly. You should keep one key per board and period, and say why count(*) over a large table is slow for a rank.

You aren't expected to raise change streams, tie-break bits or a split board without being asked. You are expected to answer sensibly when asked "the game server retries a submit, what happens?" A good answer says the match must count once, and names the id that makes that possible.

Senior

You drive the structure, and three things should come up without prompting.

A rank is a count. Say why the database's count walks every entry above the player, and why the skip list doesn't.

A record and an index. Keep every match in a durable data store, with the match id as the idempotency key, and treat the sorted sets as something you can rebuild. Write absolute scores, never increments.

Periods by event time. One fixed reset time for a world board, the match's end time to pick the period, and a grace window before it freezes.

Two things are disqualifying: incrementing scores in Redis straight from the game server with no record and no deduplication, and proposing count(*) over 50 million rows as the rank query.

Staff+

A correct design is still the bar. A staff+ answer also decides what not to build.

Say early that a rank is a count, and use it. It sums across shards, it answers the submitter before the board has their score, and it gives a friends rank from 50 numbers.

Price exactness. Exact for the top 10,000 and the final standings, within about 2,000 places below. The alternative costs 15 to 27 Redis processes' worth of rank reads in one event's last 10 minutes, against about 3.

Make every write to Redis repeatable. Absolute scores with GT, on boards whose scores only rise, and bans as REMOVE records, all fed through a log, so a replay ends where the record is.

Fit the tie-break inside 53 bits, and size the points and the time unit against 2^53.

Be able to say what you would not build. No sorted set per player for friends boards. No exact live rank for every event entrant. No Redis persistence on every write as the plan for keeping scores. No reset at each player's local midnight for a world board. No resharding of a live event board, whose shard count is fixed from its forecast before it opens. No ranking service of your own when a skip list with spans already exists. A team could spend a quarter on any one of these.


Sources

These are the sources behind every claim about a real system on this page, all read for it. The traffic, the sizes and the rates in the worksheets are assumptions, marked where they're used.

  • Redis documentation: sorted sets, ZADD, ZRANGE, ZREVRANK, ZMSCORE and UNLINK. The skip list and hash table, leaderboards as a use case, and the O(log N) commands. ZRANGE with REV in place of ZREVRANGE, the GT flag, integers exact up to 2^53, equal scores ordered by bytes, and freeing memory in a background thread.
  • Redis 7.4 source: t_zset.c, server.h, dict.c and redis.conf. The span on each link and how rank sums them, the 1/4 promotion chance, and the node and hash entry layouts behind the 100 bytes. The compact listpack form for small sets, and the warning about deleting values with millions of elements.
  • Redis, Redis Cluster specification. One hash slot per key, asynchronous replication, and the small windows in which acknowledged writes can be lost.
  • Jan Michael Go Tan, Building a real-time gaming leaderboard with Amazon ElastiCache for Redis, AWS Database Blog, 2019. Its nested rank query, and 35 seconds on average against 50 million rows with indexes.
  • Mike Kasberg, Scaling Challenge Leaderboards for Millions of Athletes, Strava Engineering, 2024. Older boards on Redis sorted sets, and a rank as a count of rows ahead. The move to MySQL with a cached score at about every 1,000th rank, and rebuild times growing from an hour to more than a day.
  • Google, Play Games Services leaderboards. Resets at UTC−7, and score limits against fraud.
  • Microsoft, Using resettable statistics and leaderboards, PlayFab. Resets at 00:00 UTC, and writes to the old version accepted for 10 minutes.
  • Valve, Steamworks leaderboards. The Trusted setting that stops clients setting scores.
  • Amazon DynamoDB documentation: DynamoDB Streams, for change records in order for each item, near real time, a 24-hour lifetime and no more than two readers per shard. The stream record reference, for REMOVE records, and transactions, for all-or-nothing writes that fail as a whole when any condition fails. Scan, for ConsistentRead and its doubled cost, and the Kinesis adapter, for spreading shards across workers and reading parent shards first.
  • Apache Kafka, producer configuration, version 3.8. The idempotent producer, on by default, which writes one copy of each message and keeps order through retries.
  • Mark Nottingham, RFC 5861, HTTP Cache-Control Extensions for Stale Content, an Independent Submission. What stale-while-revalidate and stale-if-error let a cache do, and the error statuses the second covers.
  • Wikipedia, Double-precision floating-point format. The 53-bit significand, and the gap of 2 between doubles above 2^53.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.