Lesson 3 · Minutes 20-30

Real-Time Leaderboard: Scaling It

Problem

By minute twenty the interviewer has your count and your 2 seconds, and the next ten minutes press on the design in four places. Here is what they press on, in order.

  • The count runs thousands of times a second at peak, and each run walks half an index.
  • Whatever replaces the count holds its answers in one process, and processes restart.
  • The game launches worldwide, and one node may no longer be enough for one board.
  • Two players finish level, and the fix for the count has taken away their shared rank.

The Rank Count

"Two seconds a rank and nine thousand ranks a second. How does that work?" It does not, and read replicas will not rescue it, because they divide the requests and not the work inside each one. So keep the table as the truth and add a sorted set in memory, which holds entries in score order. An in-memory store such as Redis has one, and the design needs only the promise. Each link in the structure carries how many entries it skips, so walking down adds up a rank.

Forty million entries is about 25 steps. At 100 nanoseconds a step, that is about 2.5 microseconds, nearly a million times less than 2 seconds. How a skip list or a balanced tree stays balanced belongs to Computer Science Deep Dive; the counts on the links are the one thing added here. The room needs the logarithm, and the fact that a rank is computed and never stored.

Now size it. At peak the set takes 3,000 updates, 9,000 ranks and 9,000 top-ten reads, which is 21,000 operations a second. Assume a sorted-set operation costs about what a simple one does. One node does about 100,000 of those, so the board takes a fifth of one node. The price is a second system, two writes per result with a gap between them, and an answer that now lives in memory. That last item is the next thing the interviewer reaches for.

The Restart

"Your set's process just died. What's gone, and what's on a player's screen right now?" Nothing that matters is gone, because the set is derived data. Chapter 2's Caching at Scale draws the line: what cannot be rebuilt from the store is a second database, and this set can be rebuilt from the scores table.

A replica in another zone takes over within seconds, so what a player sees is a short pause. It is asynchronous, so it may lack the last writes, which is the loss Chapter 4's Leaders, Followers and Everyone describes. So the rows changed in the last minute are re-applied from the table: 3,000 a second for 60 seconds is 180,000 rows.

If both copies are lost, rebuild. Pipelining sends many commands in one round trip, so assume one node takes about 1 million pipelined inserts a second, and 40 million take about 40 seconds. Meanwhile the table still answers the top ten from its index, and a rank says "updating" rather than showing a wrong number.

Snapshots are rejected for now, because a 40-second rebuild does not justify one more thing to run. The trigger is a rebuild longer than the product tolerates, and the deep dive prices that at the next probe's size. This answer costs twice the memory, 8 GB, and it keeps the gap between the table write and the set write. A crash in that gap leaves one player behind until the game server's retry, which hits the unique key and then writes the set from the table, or until their next match.

Fifteen Times the Players

"Every market now, 600 million players. Is one node still your answer, and if not, what do you cut a ranking by?" Start from what does not decide. At about 100 bytes a player, that is 60 GB, and a large node holds it, so memory gives you no reason to split. The rate does. Fifteen times 21,000 is 315,000 operations a second, and one node does about 100,000.

Take the easy half off first. The top ten is one answer for everyone, read 135,000 times a second, so each application server keeps a copy for one second, the local tier from Chapter 2's When the Cache Hurts. Assume 100 servers: the set sees 100 reads a second. The cost is a top ten up to a second old, in copies nothing can reach to correct, and the second agreed in Scope covers that. That leaves 45,000 updates and 135,000 ranks, 180,000 a second. Replicas of the one set do not get there. Each replica applies all 45,000 updates, so at half of one node's limit, 50,000 a second, it has 5,000 left for ranks, and 135,000 ranks would need 27 replicas.

Then split by score into bands, range partitions where each band holds one slice of the score order. Assume each band runs at half of one node's limit, 50,000 a second. So 180,000 a second takes four bands.

Hash shards are the reflex here, and they fail on arithmetic. With players hashed across shards, a rank has to ask every shard how many outrank this player, so every shard sees all 135,000 rank reads however many shards there are. With bands, a rank asks one band for the player's place inside it, and adds the players in higher bands from a small map of four counts, refreshed each second. Say the reason in one breath: "Bands, not hash shards: with a hash, every shard sees every rank read, so adding shards never helps the one read that is the problem."

Four bands averaging 150 million players are about 15 GB each, and with a replica for each that is eight nodes. The scores table splits by a hash of the player, and the results table splits the same way, so a result row and its score stay in one partition and one transaction. Each of the 45,000 results is two row writes, and 90,000 writes at 1,000 a partition need 90 partitions. A rank first looks up the player's score to pick the band, and those 135,000 lookups at 3,000 a partition need 45, which the 90 already cover. Double that for half load and you have 180. By the same rule, today's 3,000 results already want twelve.

Three costs arrive with the bands. A rank far down is off by whatever crossed a band in the last second, which Scope allowed when it agreed on a percent. A player crossing a band is two writes. And bands need recutting as scores climb, which you put off in so many words: "Take the band boundaries as given; they get their turn in the deep dive."

The Tie

"Level on points, one place left in the top ten. Who's in?" This is the tie you parked in the first design, and it has changed. The first design gave ties one rank for free. The set took that away, because it must put equal scores in some order, and left alone it falls back on something like the player ID, which nobody chose. So get the rule from the interviewer before you touch anything.

If the earlier player ranks higher, fold that into the score: high bits for points, low bits for the time left in the season, so an earlier finish sorts above a later one. Ninety days is 90 times 86,400 seconds, about 7.8 million, which fits in 23 bits. Assume the score holds 53 exact bits. That leaves 30 for points, about a billion. If ties should share a rank instead, skip the bits and ask the set how many entries sit above that score, the same logarithmic walk and not the old count. Add one for the rank. The top ten can then run past ten rows.

The bits have a price: a score decoded on every read and rewritten whole on every result, since a plain increment cannot replace the low bits, a season length capped by the bits, and an order only as good as the game servers' clocks, the problem Chapter 5's Clocks and Ordering takes apart. If a prize hangs on one second, one owner stamps the finals.

The Board at Minute Thirty

A rank now runs from the load balancer to an application server that holds the one-second top ten and the band counts. The server looks up the player's score in the scores table, asks one of four bands for the place inside it, and adds the counts above. Each band has a replica. The scores and results tables, partitioned by a hash of the player, sit beside them as the truth. A result writes those tables in one transaction, then the band.

The full design, with changes marked new
Rank path Result path Phonetop ten, own rank Load balancerany server Game serverreports each match Score bands4, each with a replicaNEW App serverstop-ten copy, countsNEW Scores, resultshash of the playerNEW first: result second rank score readwriteNEWsince the first design
Interview Pitfalls
  • Reaching for hash shards by habit, and finding the scatter-gather, one read asked of every shard, only when asked how a rank is computed.
  • Calling the in-memory set the database, then having no answer to the restart.
  • Sizing by memory at 600 million: 60 GB fits, so you propose a bigger node, the wrong fix.
  • Letting player ID settle a prize, because the set's default order was never questioned.
What Interviewers Listen For
  • Each change arriving with its number: 2 seconds, 40 seconds, 180,000 a second.
  • The deciding signal named before the split: the rate, not the memory.
  • The error a band's stale count allows, tied back to what Scope agreed.

Knowledge Check

What does one rank read ask of the ranking nodes, first with four score bands, then with four hash shards?

  • Bands: all four and a map of counts. Hash: one shard alone.
  • Bands: one band and a map of counts. Hash: all four shards.
  • Bands: one band and a map of counts. Hash: one shard alone.
  • Bands: all four, one by one. Hash: all four, all at once.

Both copies of the sorted set are lost at 40 million players. What does that cost, and why?

  • Every score since the last snapshot, because results were never saved
  • The season's scores, because the set was the only full copy of them
  • About 40 seconds of rebuild, because the table holds every score
  • About 10 minutes of rebuild, because the table must be sorted first

Each application server keeps the top ten for one second. What does that copy trade away?

  • A second network hop to the bands on every one of the rank reads
  • Exact ranks far down the board, because ranks now read from the copy
  • A top ten up to a second old, in copies nothing can reach to correct
  • Memory for about 150 million entries of one band on each server

A 90-day season, ties going to the earlier player, by the second. How many low bits does the time need?

  • 32 bits, a standard timestamp, leaving 21 of the 53 for points
  • 17 bits, one day in seconds, leaving 36 of the 53 for points
  • 25 bits, a year in seconds, leaving 28 of the 53 for points
  • 23 bits, about 7.8 million seconds, leaving 30 of the 53 for points

You got correct