Ch.1: Leaderboard System Design Mock Interview, Senior Level

Outline

Transcript

0:00 Take a player right in the middle, with 25 million players above her. With your index, how much work does that count do? Right, the index tells me where her score sits, not how many scores are ahead of it. So the count still reads about 25 million entries for one request, and rank requests arrive thousands of times a second. That won't work, so let me cross that out. That was minute 22, the hardest moment of this interview. Now, back to minute 0. A system design interview is the round where you design a real system out loud, in about 45 minutes, while an experienced engineer watches how you think, and the stakes are high: it can decide the offer and even your level.

0:42 You're about to watch one, written and vetted by senior and staff Silicon Valley engineers who run these interviews at top tech companies. You'll see the six phases a strong candidate goes through, what the interviewer scores in each one, and how the bar, meaning what counts as good enough, rises from senior to staff, the level above. I'm the interviewer. I'll ask the questions, push back when something looks weak, and take notes for the scorecard. And I'm the candidate, so I'm the one designing, out loud, with the clock running.

1:14 When I step in, the screen dims, because the interview is paused. The strip across the top names those phases, with the scorecard after them: requirements, estimates, the API, meaning the calls into the system, then a high-level design that sketches the whole system, deep dives into the hard parts, and a wrap-up. The clock beside it counts interview time as it happens, and it stops whenever I talk. This whole interview is graded at senior level. Thanks for coming in. Let's design a leaderboard for a mobile game, and I'll be scoring at the senior level. Players finish matches, and the game shows who's on top.

1:52 Where would you like to start? Okay. My first instinct is to throw every score into an in-memory database like Redis and sort it. Actually, let me back up, I'm getting ahead of myself. Can I ask a few questions about what it has to do first? Please do. Is this one global leaderboard, or one per country, per friend group, per season, per game mode? One global board. Friends are out for today. Got it. And is it all time, or does it start over every week or every season? What would change if it started over?

2:29 A weekly board means everyone drops back to zero each Monday, so we'd keep a separate ranking per week and throw the old ones away. That's a different shape of problem. If all time is enough for now, I'd start there and keep weekly boards in mind. That's fine for now. Weekly boards can come later. And besides the top players, does someone also need to see their own position? Yes, both. The top 10 on the home screen, and your own rank with a few players just above and below you. How many is a few, two on each side or a whole screen?

3:08 Five above you and five below. That's what fits on a phone. And can a player scroll down the whole board, page after page, or is it just those two views? Only those two. Nobody scrolls through millions of names. Good, that keeps the reads small. Should the board update live while someone is looking at it? No. It refreshes when they open it, or when they pull down on the screen. And are the players in one country, or all over the world? Worldwide. But assume one data center for today. One location, then. Where do the scores come from, the phone or our own servers?

3:44 Why does that matter? Because if phones can submit scores, anyone can send themselves a billion points. I'd only accept scores from our own game servers when a match ends. Anti-cheat itself can be out of scope, but that boundary stays. Agreed. We'll leave cheating for another day. Can a player hide from the board, or is everyone on it? Everyone's on it. Privacy settings are another team's problem. And what if a match is abandoned halfway? The game decides that. An abandoned match never sends a score.

4:16 One more on the product side. Does a player's score add up across matches, or is it their best single match? Their best match. Your place on the board is your best score ever. What does a score look like? A whole number up to what? Whole numbers, from zero to about a million. Most players land in the thousands. Do we keep every match's score, like a match history, or only the best one? Match history lives in another system. You only need the best. That makes the data a lot smaller. Last one on this side. If the leaderboard is slow or down at the end of a match, does the match have to wait for it?

4:54 Never. A match ending can't hang on the leaderboard. So the game server hands the score off and moves on, and the leaderboard catches up. Okay, let me write those down. Submit a score after each match, from game servers only, without making the match wait. Rank players by best match, all time. Show the global top 10. Show my rank with five players on each side. Out of scope for now: friends boards, weekly boards, scrolling, match history, anti-cheat and separate game modes. Let's stop the tape for a second.

5:26 Two things just happened. The candidate reached for a tool in his first sentence, before he knew the problem, and then caught himself. And the interviewer gave a vague prompt on purpose. A prompt like that could mean a dozen different systems, so the first thing being scored is whether the candidate narrows it down before drawing anything. Naming what's left out protects the clock, too. What he wrote down are the functional requirements, meaning what users can do. Next come the non-functional ones, meaning how well it has to work. Now the quality side. How many players are we talking about?

6:01 What would you assume? For a popular mobile game, I'd say 50 million players in total, and maybe 10 million playing on a given day. That works. Use those. Then how quickly does a new score need to show up on the board? Within 5 seconds or so is fine. Nobody's timing it with a stopwatch. Take the player who just set it. She's the one most likely to open the board right away. Does that hold for her too? Same for her. Keep it simple. And reading the board should feel instant, so let's say under 200 milliseconds.

6:37 One more thing. If we ever have to choose, I'd rather keep every new best safe and let a rank lag briefly, than show a perfect rank and drop someone's best match. Does that match what you want? Yes. Losing someone's best score is what gets us angry reviews. A board that's down for a minute is annoying. A lost best is a support ticket. Noted, new bests first. And with a single location, a player on the far side of the world pays that trip on every read, so the 200 milliseconds has to cover it. I'll keep that in mind for the reads.

7:18 Assume it fits. Then ties. Lots of players will finish on the same round number, like 9,000. How should a tie rank? What would you suggest? There are two ways. Tied players can share a rank, so everyone at 9,000 is, for example, 101st. Or whoever got there first ranks higher, which means the order also depends on time. Sharing is simpler to explain, so I'd go with that unless the game wants first-come to win. First-come doesn't matter. They share the rank. Okay. 50 million players, 10 million a day.

7:55 New scores visible within about 5 seconds, for everyone. Fast reads. No new best ever gets lost, and ranks may lag. Ties are shared. What's scored here isn't the list itself. It's whether the later choices trace back to it. He finished just before minute six. The common time split we're using, shown at the start, gives this phase about 5 minutes. Two interview-prep sites, Hello Interview and ByteByteGo, publish step-by-step plans that budget the round in a similar way, and the links are in the description.

8:27 The candidate also asked what matters more when two goals pull against each other, and that one answer will decide a choice later in the design. Now, can I do some quick math, just on the numbers that would change the design? Go ahead. Keep it short. 10 million daily players. Let's say each one finishes about 10 matches a day. That's a hundred million new scores a day. A day has about 86,000 seconds, so that's roughly 1,200 writes a second on average. Traffic isn't flat, so I'll assume the busiest hour runs about five times the average, around 6,000 per second.

9:04 Why five times? Most people play in the evening, so traffic bunches up. Five is a safe guess for a game like this. Does every one of those change the board? No, only a new best changes anything, and most matches won't beat a player's best. But every score still has to be checked against the best. I'd size writes for the full 6,000. And what about reads? People check the board when they open the game and after matches, so call it twice per match, and reads at peak are about 12,000 a second. So reads lead, but not by a huge margin.

9:44 Do the reads have the same evening peak? Yes, I assumed the same five times, so the 12,000 already includes it. What about storage? That one decides whether the whole ranking can live on a single server. Each player is an ID and a best score. In memory, with the extra bookkeeping, call it roughly 100 bytes each. 50 million players at that size is about 5 gigabytes. That fits in the memory of one ordinary server, so I don't need to split the ranking across machines on day one. And players online at the same moment?

10:21 I don't think I need that one. The per-second rates already cover the load, and nothing in this design holds a connection open per player. What else grows with the reads? The names on each list. They'd come from wherever player profiles live, so at peak, at most 12,000 batched lookups each second, and fewer once names are kept nearby. That's worth telling the team that runs the profiles, but it doesn't change our design. Anything else you want to size? I could size the database on disk, but it holds those same 50 million rows, and no choice I can see depends on it.

11:05 So I'd stop here. Sounds good. Let's move on. Not every round has this phase. Some prep guides fold this math into the requirements, and some interviewers skip it entirely. So calculate only what changes a decision. Here, 5 gigabytes changed 1: the design can start simple. And asked whether there was more to size, he said why the next number wouldn't matter, and stopped. That took about 2.5 minutes of the clock. Before I draw boxes, let me pin down the API. Ordinary web requests are enough, since nothing here has to push live updates.

11:38 I see three. Submit score takes a player and a score, and only our game servers can call it. The second, get top, returns the 10 best players. And get my rank returns the caller's own rank plus the 10 players around them. Spell out what each one sends and gets back. Submit score sends a player ID, a match ID and the score. It returns the player's best and whether this was a new one. Get top takes no input and returns 10 entries. Get my rank takes none either, and returns her own entry plus those 10 neighbors.

12:18 Each entry holds a rank, a name and a score. Why is the player named in submit score, but not in get my rank? Because the caller is different. Submit score is called by game servers we run, which we trust to say which player finished the match. Get my rank is called by the app on a phone, which we don't trust at all. So the player comes from the login session the request already carries, and the app sends nothing it could fake. Let's say a player's new score is lower than her best. What does submit score do then?

12:57 Nothing changes, because we keep each player's best score. A lower score doesn't move them. Its new-best flag just comes back false, so the game skips the banner. And a result that arrives twice, say after a timeout? That's harmless too. Keeping the higher of two scores gives the same answer however many times you apply it, so a repeat changes nothing. It gets back the same best, but this time the flag says no new best, because the first try already saved it. At worst one banner doesn't show. The match ID still helps: we can log duplicates and spot a game server that keeps retrying.

13:37 That's fine. A few edge cases I want on the board. For example, a score below 0 or above a million can't come from a real match, so I'd reject it, and the error tells the game server not to retry. A timeout tells it the opposite: keep the result and try again, waiting a little longer each time, so no match ever hangs on us. A brand-new player has no best, so no rank yet, and the app says "finish a match to get ranked." And a player in 3rd place just gets the two who are there. Suppose a player deletes her account.

14:13 Then her row comes out, and everyone below her moves up one place on their next read. Nothing else has to change. Does the top 10 call need any paging? Not for the two views. Get top always returns 10, and the rank call always returns the same window around the player. If scrolling ever comes back, I'd page from the last score and player ID seen, not by position. Ranks shift while someone scrolls, so paging by position would show one player twice or skip another. Where do the names come from? They aren't ours.

14:50 They come from the profile service you mentioned the game already has, so I'd look them up in one batch per request. I'd also return the time each answer was computed, so the app can say how fresh it is. I didn't mention a profile service, but yes, assume there is one. Fair, I assumed it. Then the data. One table holds the official record: player ID, best score, and when it was set. Names stay in the profile service, so this table never has to keep up with someone changing their name. In the split we're using, the API gets around 5 minutes, and the test is whether the contract sets the rules before any box exists.

15:31 Writing "game servers only" into submit score turned an early requirement into a rule every box has to follow. He also raised his own edge cases instead of waiting to be asked. And when he claimed a service she never mentioned, she corrected him, and he owned the assumption in one line instead of arguing. Let me sketch the simplest version that does everything we listed, and then we can make it fast. There are two paths: the write path, how scores get in, and the read path, how they get out. For writes, a finished match on a game server sends its result to a score service.

16:08 The score service keeps the higher of the old and new score in the scores database. I'll put the game servers on the left, the score service in the middle, and the database underneath. Which database? An ordinary relational one. It's one table with small updates by player ID, and it saves each update to disk before it says yes, which is how we never lose a new best. There's one race I want to handle before going on. Go ahead. Two of her matches finishing at the same moment. If each update reads her best, compares, and writes back, the lower score can land last and wipe out the higher one.

16:47 So I'd do it in one statement: set the best to the new score, only where it's higher. The database runs that as one step on her row, so whichever lands last, her best survives. And the database reports whether it changed a row, which is exactly the new-best answer submit score returns. Why not lock her row in your code, read the best, compare, then write? That works too, but then the lock is held across a trip from the score service to the database and back. The single statement takes the same lock inside the database for one step, so two matches wait on each other for far less time.

17:29 Every match runs that statement, even the ones that set no best. Isn't that wasted work? Mostly, yes, but it's cheap. It's one lookup by her ID, and usually it changes nothing. Skipping it would mean keeping every player's best somewhere else and trusting that copy, which is exactly the kind of second record I don't want yet. At our peak rate, I'll pay for the check. Okay. 6,000 of those a second at peak. Would you put a queue in front of the database? Not on day one. 6,000 small updates a second, each one on a single row it finds by player ID, is a load one well-sized database server can take.

18:17 A queue would add a box to run and watch. Fresh scores get 5 seconds to show up, so I could add one later if bursts grow, but I don't need it yet. Alright, no queue. The game servers could write to the database themselves. Why the extra service? They could, but then every game server holds database credentials, and the score checks and the one-statement update live in every copy of the game server code. Changing a rule would mean redeploying all of them. One small service holds the rules in one place, and the game servers only know one call.

18:52 Fair. Then the score service. It remembers nothing between calls, so I'd run a few copies behind a load balancer, four to start. If one dies mid-request, the game server retries, and a repeat is harmless. Why four? 6,000 at peak over four is 1,500 each, and if one copy dies, the other three carry 2000 each. Now the failures on this side, quickly. Go on. Let's say the database is down for 10 minutes. Submit score fails, the game servers keep their results and retry, and no score is lost. The board is down until it's back, which is an annoyance, not lost data.

19:31 Imagine 10 minutes of results piling up on the game servers. What happens when the database comes back? They would all retry at once, so each one waits longer after every failure, plus a random bit, and the wave spreads out. And a game server that's been cut off from you for an hour? It writes each result to its own disk before calling us and sends it later, even after a restart. The order doesn't matter, because a maximum comes out the same in any order. And take a game server stuck resending one match in a loop: a per-server cap on scores keeps it from drowning the database.

20:09 Okay. Last, take a first-timer: if there's no row yet, it inserts one with this score as her first best. And I keep when each best was set, because that's the first thing support checks when a best goes missing. Take an ID the profile service has never heard of. Storing that sounds risky. It would be, from a phone. But scores only arrive from trusted game servers, so an unknown ID is usually an account too new for the profile service. I'd store it and flag it, and if the flags climb, that's a game-server bug.

20:46 Before I draw the reads, is this the level of detail you want, or should I move faster? This is fine. Keep going. A quick pause on that queue. The interviewer suggested a box, and the candidate turned it down, which can feel risky in an interview. He did it with his own peak number from the estimates and the freshness she agreed to, and he said when he'd change his mind. A suggestion from the interviewer isn't an order. It's a question about whether you know why your design looks the way it does. The failure walk after it is expected at senior, as long as each failure gets a sentence or two.

21:23 Now the other path, the reads. The player's app goes on the right, the leaderboard API between it and the same database. The app keeps its last answer, so it can show the board instantly while it asks for a fresh one. The leaderboard API checks the login first and pulls out the player. For the top 10, it asks the database for the highest scores, sorted. For my rank, it counts the players with a higher score than mine and adds one. That gives ties the shared rank, because an equal score isn't counted.

21:55 Mm-hm. And the players around me are just the five entries above mine and the five below, ordered by score, with the player ID breaking ties. Those two lookups are the same idea: walk up from my entry and take five, then walk down for the other five. The busiest read, though, is the top 10, by far. It's shown at every launch, and everyone gets the identical list, so a big share of the peak read traffic is the same question. I'll flag that now and come back to it. The score service already talks to the database.

22:29 Why a separate leaderboard API? Different callers and different trust. Game servers write, phones read, and only the first should ever reach the writes. They also scale separately: a crowd opening the app at once spikes reads without touching writes. And a flood of phones means more leaderboard copies, not more score service copies, though for now they still share one database. Your top-10 query sorts the entire table? As drawn, yes, unless something keeps the scores sorted. That's part of what I'd fix next.

23:01 For now it's correct, and it's on my list. Two more read-side cases while I'm here. Sure. Names first. The leaderboard API takes the player IDs and asks the profile service for all of their names in one call. 10 names for the leaders' list, and 11 for my view, counting me. Names barely change, so they're worth keeping a copy of later. If the profile service is down, I'd still show the ranks and scores with a placeholder for the names, instead of failing the screen. Names are nice to have. The ranks are the product.

23:35 And say you hold your thumb on refresh: I'd cap each player at a handful of rank calls a second. Imagine a handful a second from every player at once. That's still a lot. It is, so the cap is about one broken phone, not the total. The total is the peak load we already sized for, and a cap just stops one phone from taking more than its share. And if the database is slow on a read, not down? Then the leaderboard API gives up well inside the read budget, and the player keeps seeing what the app already had, with the time it was computed.

24:15 A slow database looks a little stale to the player, not broken. How does the app find out that her rank changed? It doesn't, until she opens the board again. That's the refresh on open you set at the start, and the time on each answer tells the app how old its copy is. Let's say a famous streamer sends a wave of players in, on top of the peak. Is that okay on one database? No, not as drawn. More leaderboard API copies help, since they keep nothing between requests, but they all land on the one database.

24:55 Sorting the whole table on every read won't hold, and the rank count runs every time someone opens the game. I think keeping every score in sorted order as it arrives fixes most of it, and that's the first thing I'd want to go deeper on. The far players I flagged make it tighter, because their trip eats into the budget before we do any work. I'd like the whole picture to work first, even slowly, so let me trace one match from start to finish. Okay. A player finishes a match with 9,000 points. Her game server calls submit score.

25:31 The score service sees that 9,000 beats her old best of 7,000, so it updates her row and reports a new best. Her phone shows the banner. Moments later she opens the app, the leaderboard API runs the count, and she sees her new rank in the middle of her neighbors. Take a weaker match, 5,000: the one-statement update matches nothing, because 5,000 isn't higher than 9,000. Submit score reports no new best, and nothing else happens. That's most matches. And someone else, a second later? He sees the same sorted top 10, and if her score is high enough, she's in it.

26:10 Let me check the list against the board. Scores come only through the score service, a match never waits, and only the best counts. Every view has a read, ties share a rank, and new scores show right away, so the freshness budget is spare time I can spend later. And a best is on disk before anyone hears yes. Every requirement has a path, even if some of those paths are slow. Before I speed anything up, are you happy with this as the starting point? Yes, I'm with you. What's the weakest part of this picture?

26:46 The count, and then the top-10 sort. Both are read problems, and both get worse as the board grows. This is the step a lot of candidates rush. He walked one real request through it before optimizing anything, and he checked that the interviewer was with him. A simple design that covers everything beats a clever one that's missing half the paths. The clock is near 22 minutes. The high-level design took about 10 of them, the low end of its budget, which leaves the deep dives room. Now, where would you go deeper?

27:20 My rank, because every app launch asks for it. I'd put an index on the score column, so the database keeps scores in order and the count is fast. Take a player right in the middle, with 25 million players above her. With your index, how much work does that count do? Right, the index tells me where her score sits, not how many scores are ahead of it. So the count still reads about 25 million entries for one request, and rank requests arrive thousands of times a second. That won't work, so let me cross that out.

27:56 So what replaces it? Let me first think about what the database alone could do. Take the simplest idea: work out all the ranks ahead of time, and store them. But ranks move every time anyone improves, so I'd have to redo all 50 million of them every few seconds. Every 5 seconds, that's 10 million row updates every second. That's no good. What else? Keep a count of players at each score value in a second table. Then a rank is the sum of the counts above that score. That's better, but scores run anywhere up to a million, so there can be nearly a million different values, and for a player low on the board the sum still touches most of them.

28:44 I could build a tree of running totals on top to make that fast, but then I'm writing my own ranking structure. So neither works. Not as they stand. That index still helps the leaders' read and her window, because those read only a handful of entries. It's the count that breaks. I need a structure that keeps players in score order and also knows positions, so it can answer a rank without counting. A sorted set does that. For years, Redis has built its sorted set on a skip list, which is like a linked list with express lanes.

29:22 I'd use Redis rather than write my own, because it's widely used and already has the exact commands I need. How does a player end up on a lane? It's random. When a player is added, a random draw decides whether she also gets a lane above, and then another one above that. In that skip list, about one in four entries reaches each next lane up. On average, that keeps the jumps evenly spread. Express lanes make finding her fast. But how do they give you her rank? Each jump on an express lane also stores how many places it moves you forward, and on the way down to her, the sorted set adds those up.

30:08 Let's say the leaderboard had just eight players. I'll sketch it. Go on. On her way down, the lanes move forward four places, then 2, then 1. That adds up to seven, so she's 7th. The number of steps grows with the logarithm of the player count: doubling the players adds only a step or two. For 50 million players, that's a few dozen steps instead of millions. Even at 10 times the players, it's only a few steps more. The step count never becomes the problem. And when her best goes up, what moves? Her old entry comes out and the new one goes in, each with 1 walk down the lanes.

30:50 The counts on the jumps she passes get adjusted as it goes. What about all the players between her old score and her new one? None of them are touched. Their positions shift, but nobody's rank is stored per player. A rank is added up from the lane counts on the way down, and only the counts along her path change. That's exactly what storing every rank couldn't do. How long does one of those take? That many steps in memory is well under a millisecond inside the server. So most of the 200 milliseconds goes to the network, not the ranking.

31:30 Couldn't a database index keep those counts too? Some databases can keep counts inside their index, but the common ones don't, so I'd rather not build on it. Redis gives me exactly this, and it's one of its best-known features. And your 100 bytes a player. Does that cover the express lanes? Roughly, yes. Redis keeps the skip list and also a lookup from each player to their score, and for short player IDs the two together land around that size. So the 5 gigabytes still holds, and ordinary servers come with tens of gigabytes of memory.

32:07 And if it does run out of memory? Depending on how it's set up, Redis either refuses new writes or throws whole keys away, and our whole ranking sits under one key. For a ranking, I'd set it to refuse. Quietly losing the board would be much worse than an error. Redis runs one command at a time. Does that worry you here? Not for these commands. Each one is short, so one at a time still adds up to many thousands a second. It would worry me if someone ran something slow on it, like asking for every entry at once, because everything else would wait behind it.

32:51 Our API never asks for more than 11 entries. The interviewer didn't say the index was wrong. She asked a question with a number in it, and let the candidate find the flaw himself. That's what pushback usually is: a test of whether you hold your design or fix it out loud. Here the flaw was real, so fixing it was right, and he crossed out the old idea where everyone could see it. And Redis came back. At the start it was a guess; here it solves a problem he can point to. The recovery counts, even though the index idea will still cost him.

33:29 Now ties. Your sorted set gives every player their own position. What happens to two players tied on the same score? Right, by position alone one of them would come out a place ahead of the other, and ties have to share a rank. For my rank, then, I'd ask the sorted set a different question: the number of scores strictly higher than hers. That count runs down the same express lanes, so it's just as fast, and I add one. Take 200,000 of them on that same score. Does that count slow down? No. It finds where their score starts and reads off how many come before it.

34:14 It never looks at the tied players one by one, so it costs the same as any rank. For example, with 100 players above that score and 200,000 sitting on it, every one of them gets rank 101. Redis orders equal scores by player ID, so the order is stable. That decides who appears in a window, but it never changes anyone's rank. Mm-hm. The position is still useful, for her neighbors. Once I know where she sits, I ask for the 5 positions before hers and the five after. That's a single trip down, then 10 short steps along the bottom row.

34:50 And if her neighbors are tied with her, they all show the same rank, which is the rule. First her score, then the count above it, then that window: I'd bundle them in one small script that runs on the Redis server, so it's one trip, and nothing can change between the steps. And what does a player wait for in total? The sorted set takes microseconds, and fetching names costs milliseconds, not microseconds. So the trip from the phone is most of it. Nearby players are well under the 200 milliseconds, and a player across the world is the tight case I flagged.

35:29 Each entry is just her ID and her best score. Names stay out, so a name change never reaches the ranking. Where does it sit in your design? Next to the database, in memory. Whenever a score comes in, the score service also updates the sorted set. I'd use its option that only ever raises a score, so an old update arriving late can't push anyone down. The leaderboard API now asks the sorted set for both answers, and reads stop touching the database. Even scores that aren't a new best? Every score, as one raise-only update.

36:05 When it isn't a new best, that changes nothing, so it costs almost nothing. Draw it for me. The sorted set goes to the right of the database. The score service gets a second arrow to it, for raising a best, and the leaderboard API's arrow moves from the database to the sorted set. Players with no matches yet aren't in it at all, so they don't count toward anyone's rank. It's one shared copy, so every score service agrees on her rank. And the score index can go now. With only writes by player ID left on the table, that score index would only slow every write down.

36:46 Why that order, the table first and the ranking second? If the ranking were written ahead of the table and that update failed, the board would show a best that was never saved, the one thing that can't happen. In this order, the worst case is a rank that's behind. And the score service answers the game server only after both, so the game server keeps retrying until both writes are done. And if that second update fails after the database write? Then her rank is behind for a moment, within the 5-second window.

37:22 I'd retry the update until it lands, and the retry is safe, because the update only raises a best. Same if one copy of the score service dies between the two writes. The game server's retry gets "no new best" back, because the table already has it, and the raise still repairs the ranking. A ranking update that waited for a new best would never catch up, which is why every score goes to the sorted set. Then why keep the database at all? Because we agreed we never lose a new best. The sorted set lives in memory, so I treat it as the fast copy, not the record.

38:01 The database stays the truth. Even though every read now skips it? Yes. Each new best still lands there first. Memory is what I'd plan to lose someday, and the table is what survives. Give me the whole thing in one breath. Counting in the database reads millions of rows, so the rank comes from the sorted set's express lanes instead. Ties use the count of strictly higher scores. The database is still the record, and it's written first. The sorted set is the quick copy, written second, raised by every score, and safe to retry.

38:38 When she asked why he kept the database at all, that was the other kind of pushback. It sounded like a hint that the database was wrong, and it wasn't. He held his ground with the requirement he'd written down in the first 5 minutes, just as he did with the queue. Two outcomes, one habit: check the choice against its reason. A sound choice, you defend with that reason; a real flaw, you fix out loud. Caving when your choice is sound costs as much as digging in when it's flawed. So every player lives in a single sorted set.

39:11 How sure are you that one server is enough at peak? Let me add it up. Peak is 12,000 board reads plus up to 6,000 scores each second. That totals under 20,000. A single Redis machine does around five times that, so we'd use about a 5th of it. Would you keep it that way, then? There's another option. Instead of exact positions, we could count the players in each score range, like a histogram. Let's say my score is between 8,000 and 9,000: my rank is everyone in the ranges above it, plus a guess inside my own range.

39:53 That's tiny, a short list of counters instead of 50 million entries, but players see roughly where they stand instead of an exact number. How rough is roughly? It's off by at most the number of players in my own range. Suppose we use 1,000 ranges, sized so each holds an equal share. 50 million over 1,000 is 50,000 players per range, so a rank could be off by up to 50,000 places. More ranges help: 10,000 counters still fit anywhere and add up in microseconds, and that cuts the error to 5,000 places.

40:31 And what does a new best cost there? Two counter changes. Take one off the range she left, add one to the range she entered, and none if she stays inside it. Unlike the sorted set, where raising a score twice does nothing, a change applied twice counts twice, so each one carries its match ID. And her five neighbors, in that version? That's a problem. The counters know the size of each range, not who's in it, so the ranges version can't show the five above and below her on its own. I'd have to bring back the index on scores I just dropped, only for her window.

41:13 Okay. So that's two designs. Right. Approximate ranks from the ranges: tiny, but rough by thousands of places, with the index back for her neighbors. Or exact ranks in the sorted set: one big thing in memory, every rank and neighbor exact. Which one would you build? Exact ranks. 5 gigabytes fits on one machine, and 6,000 writes per second is a small fraction of what one in-memory server handles, which is on the order of 100,000 simple operations a second. It also gives the five neighbors from the same structure.

41:46 The approximate version would buy us scale we don't need yet. The cost is that one machine holds the entire ranking. If we grow 10 times, we'd be at or past that server's limit, and the score ranges become the plan. What would tell you it's time to switch? Two numbers. The memory on that machine filling up, or the writes and rank reads together getting near that server's ceiling. And at the switch, players far down the board see their exact number turn into a rounded one. That changes what we promised them, so it's a product call before we switch.

42:24 Now, anything else on reads? Yes, the top 10. Every player sees the same 10 names, and they change slowly. So I'd keep a cached copy of the top 10, names included, in each leaderboard API server, and refresh it about once a second. That's at most a second old, well inside the 5 seconds we agreed on. Why on a timer, and not whenever the top 10 changes? Because I don't control how often the leaders change, and every server would refill at the same moment each time. A timer gives a fixed, small load.

43:03 If a refresh fails, the server keeps serving the old copy and tries again on the next tick. How much load does that take off the sorted set? Let's say 20 API servers at peak, each taking about 600 requests a second. With 20, the sorted set answers 20 top-10 reads a second instead of thousands. What's left is the score writes and the my-rank calls, still far under its limit. My rank I wouldn't cache: each rank is personal, and it's answered in well under a millisecond anyway. Nice, that holds together.

43:39 And if we ever do switch to score ranges, the range sizes matter. You'd want each range to hold an even share of players, so I'd size them from a sample of real scores. Every best is already in the scores table, so I'd read a random slice of it, maybe one row in 500, sort them, and cut the sorted list into 1,000 equal pieces. Okay. We're at about 37 minutes. Right, quickly. I'd resize them every week, because scores keep climbing as players improve, and evenly spaced ranges would pile most players into a few crowded ranges near the bottom, where most players sit.

44:19 Resizing means recounting every range, so I'd build the new counters beside the current ones and swap them in, sending each change to both until the new set takes over. Do you need to resize them at all, if you're not using them? Probably not right away, but if we ever switch, I'd want it ready. Ties at the range edges get tricky. Say you have 1,000 players sitting exactly on an edge score: they all have to land in the same range, or the tie splits across two. Let me stop you there. You chose exact ranks a while ago, and I want to save the end for your questions, so we've got about 2 minutes to wrap up.

45:03 Two lessons in that stretch. First, listing options is half an answer. Take a candidate who names three databases and never picks 1: the interviewer hears a survey, not a decision. This candidate laid out exact and approximate ranks clearly, but he only chose when the interviewer asked. Choosing out loud, and naming the cost of the tradeoff, is what interviewers mean by judgment. Second, look at the clock. He went back to the design he'd just turned down, even after she told him the time, and those minutes came out of the wrap-up.

45:37 So, to wrap up, and quickly: what breaks first? That in-memory ranking is what I'd worry about. If that machine crashes, the ranking is gone, so we'd have to rebuild it somehow. Until then, rank calls would fail. How long would that take? I'm not sure. A while, with 50 million players. Imagine that crash at the evening peak. What would players see? Scores would still be saved, because the database takes them first. Matches keep working. The board itself would be missing, or stuck, until the ranking is back, and the first to notice would be whoever checks the board next.

46:21 And what would you watch in production? How long the rank calls take, mostly. If those climb toward the 200 milliseconds, players feel it first. Anything else? That's the one I'd start with. What breaks second? Probably the profile service at peak, if name lookups pile up. Caching the leaders' names helps with part of it. Sorry, I know that's quick. And the database at peak? 6,000 checks a second is fine today. I'd want a load test to know how much room is left. Last one. What if the game gets 10 times bigger?

47:03 Then it's five hundred million players, and 60,000 writes every second with all the rank reads on top. That's past the limit of one Redis machine, so that's when the ranges come in. Can one database take that? That's a lot for one database, so I'd split the table across several databases by player ID. Each player's row lives in exactly one of them, so the update itself doesn't change at all. Both services just get more copies, as they do today. And honestly, with more time I'd talk about spreading the ranking over more machines. Okay, let's stop there.

47:44 Thanks, this was a good conversation. Now, what questions do you have for me? The recording ends there; the last 5 minutes of the slot belong to his questions. "Rebuild it somehow" is a hope, not a plan. This phase checks reliability: what breaks, how it recovers, and what you'd watch. The split we're using saves 5 minutes for it, and he got 2: the deep dives ran their full 15, and the drift past her time check came out of this one. The interviewer writes a scorecard the candidate never hears, and the people who make the decision read it alongside the other interviews. Here, she reads it to us.

48:19 Now the scorecard I'd write after that interview. Each row grades a skill across the whole interview, even where it shares a phase's name. Requirements and scope: strong. After one false start, he pinned down the features, the scale and the freshness, and he asked which goal comes first. High-level design: strong. Simple, complete, and he walked one match through it. Depth on the hard parts: mixed. He picked the right problem, but his first fix, the index, still counted millions of entries. He needed my question to see it.

48:52 Both strong rows were earned before the deep dives even started. Trade-offs and judgment: mixed. He explained exact versus approximate ranks well, named the cost and when he'd switch, and the top-10 cache was a good call, but the choice came only after I asked. Mixed, not weak: once asked, he chose and said what it would cost. Scale, reliability and operations: weak. He covered growth, the database outage and the failed second write. But the ranking machine is a single point of failure, meaning one crash takes the rankings down, and nothing takes over while it's gone.

49:28 With no rebuild plan either, that outweighs what he covered. Asked what he'd watch, he named how long rank calls take, not the memory and load signals he'd used earlier. Communication and collaboration: mixed. Clear, and he adapted under pushback, but he kept going after I gave him the time, and I had to call it. Decision: lean hire, at senior. That's a yes, but a weak one. So two more sentences would have moved that decision. Imagine the wrap-up with these two. Rebuild the ranking from the scores table.

50:03 And keep serving the cached top 10 while it rebuilds. That likely lifts the row to mixed and the decision to a plain hire; a standby copy that takes over would likely make it strong. At staff, a candidate would also have raised recovery unprompted, questioned whether the player in 40-millionth place needs an exact rank at all, and planned how to spread the ranking over several machines, for example giving each machine its own band of scores while every rank stays exact, before anyone asked about growth.

50:33 From my side of the table, one thing. I can only score what you say out loud. For example, if you thought about recovery but never said it, it isn't in my notes. And for a mid-level role, this same interview would likely pass as a hire, because there I'd expect to lead more of the later questions myself. And from mine: watch the clock yourself. I knew the ranking could be rebuilt from the table. With 2 minutes left I rushed, and it never came out, because I'd gone deeper than I needed to earlier.

51:07 So here's the framework, one habit per phase. Requirements: write the numbers down and rank the goals. Estimates: only the math that moves a decision. The API: agree on the calls before the boxes. The high-level design: simple, complete, one request traced. Deep dives: pick the hard part, choose out loud, say the cost. The wrap-up: save time for what breaks. At senior you drive every phase and choose without being asked; at staff you also question the requirements and plan for growth before anyone asks.

51:42 If you're preparing for these interviews, we recommend Alex Xu's System Design Interview books, volumes 1 and 2. We've read both, and volume 2 has a whole chapter on this same leaderboard problem. The links are in the description, and we earn a small commission if you buy through them. Thanks for listening to Learning Podcasts.