Ch.44: Leaderboard System Design: Freeze the Right Winner
Outline
- 0:00 The close race starts before the board catches up
- 0:34 What callers must get
- 1:48 Capacity, latency and failure requirements
- 2:44 The complete architecture
- 4:09 One receipt ID, one decision
- 4:29 Commit the best score and its handoff together
- 5:22 Make the checkpoint honest
- 6:35 Prove close before trusting rank
- 8:25 Deterministic ties
- 9:28 Apply one log record atomically
- 11:47 Accepted and exact are separate states
- 12:42 Rank and neighbors in one snapshot
- 13:55 One bounded friends snapshot
- 14:36 The hot-board capacity obligation
- 16:19 Return to the same architecture
Transcript
0:00 Final second. Priya's scorer receipt, `R7`, arrives three times. API records 10,000; `R7` has no saved log position. Global ranks her 9th, around-me centers eleventh, friends shows 9,000. All claim one board version. The leaderboard is wrong. Global, around-me, and friends share one label. That's one impossible board. What makes close safe? Three proofs connect: saved receipt decision, each winner's log position, and a gap-free rank index. This mechanism rejects largest-seen and empty-queue shortcuts.
0:31 That leaves one rule: missing link, no close. That contradiction leads to a concrete case. Priya's 10,000-point scorer result arrives, then `R7` repeats twice. What is the API allowed to change, and what must it return? Those are the functional requirements: what callers get. The repeats cannot change `R7`'s immutable result. Deduplicate the receipt ID, retain every receipt, and rank only Priya's best. Reads still owe top N, exact rank with five above and below, and friends under the same ordering rule.
1:03 Her best can be accepted while the board still trails. So the rank call must return 10,000, `rank pending`, and the last complete version instead of inventing a place. What makes that version complete? Picture the shelf. Its last filled slot is 8,103. Next comes a blank at 8,104. A complete board version is the latest contiguous log position reflected in the ranking view. Until the rank projector, the worker copying winners into the live board, catches up, the caller gets that accepted score plus `rank pending`, alongside the shelf's complete version.
1:37 The projector recovers safely; close freezes one version. Priya can wait on that rank request or on her accepted winner reaching the board. Two clocks, then. How fast may each be? That two-clock question opens with Priya's live rank-and-window read. 99 of 100 must finish within a quarter second; that's the read p99. If it misses, the client retries or gets a labeled previous complete board, never a guessed rank. Her accepted best runs on the projection clock: p99 2 seconds from best-score change to visible winner.
2:10 If projection misses, 10,000 stays accepted while rank is pending on the latest complete board. Those are the non-functional requirements: how well the functional promise holds under pressure. A read miss delays the answer; a projection miss delays her new best. Now suppose Priya and Omar are tied on one version-labeled board. Points are equal; what breaks the tie? Score, then earlier achievement, then stable player identifier. Tie order is stable inside each version. That sets up the projection problem: Priya's accepted best still has not appeared in current standings.
2:44 With those limits set, start in the middle of the map. Priya's freeze is stuck. What exactly is missing? Imagine a shelf whose unbroken run reaches bag 8,103. Slot 8,104 is empty, and bag 8,105 waits behind it. A contiguous prefix is that unbroken run, so the projection can't claim anything beyond 8,103. Oh, good. The visible hole finally makes “complete” concrete: the later bag can wait while the certified prefix still stops at 8,103. Trace Priya's missing bag from the left. What is already durable?
3:17 `R7` has one saved decision, and `PlayerBest` holds the winning total, 10,000. The same transaction saves a durable publish instruction: an outbox row that survives a crash for the relay. It must become the missing numbered bag; Redis hasn't seen it yet. The relay gives Priya's instruction a permanent log slot. The projector writes rank state and checkpoint to Redis atomically. The control plane issues the numbered writer badge, or epoch, and later appends the close marker. That ordered finish record still has to be applied by the projector before freeze.
3:48 Priya's accepted winner stays absent until her rank update is applied and the checkpoint moves. Source links are in the description. That retry path has one sharp boundary: one initial `R7` delivery plus two identical retries should resolve to one decision. But if a request reuses `R7` with different points, is that a correction or a collision? A collision. The receipt ID returns its saved outcome. Reuse it with changed points, board, player, or achievement time, and the API rejects that collision for investigation.
4:19 Otherwise, honestly, a network retry becomes a scoring rule. Excellent retry policy. Catastrophic scoring policy. One decision still doesn't settle which score becomes Priya's best. Now make two scorer results race: Priya is at 9,000 when 10,000 and 9,500 both read her old best. Which survives? One transaction rechecks `PlayerBest` by points, then achievement time. 10,000 wins; the late 9,500 stays auditable but cannot replace it. Priya's per-player best counter advances from version 41 to 42. Why keep an outbox instruction at all?
4:54 Why not commit `PlayerBest`, then publish straight to the board log? Because a crash between those calls leaves an accepted winner with no durable handoff. Saving the winning best and its publish instruction in one transaction closes that gap; the relay can retry the append. Yeah, without the outbox, the API says accepted but recovery has no saved relay instruction. With it, 10,000 is accepted while Priya's rank stays pending. Next: its permanent log position. With Priya's winner authoritative, the relay appends her instruction to the board log under a stable identity. The log assigns permanent position 8,104.
5:31 If acknowledgement is lost, a deduplicated retry returns 8,104 again. Omar's next winner receives 8,105. Take the hole on the map. Record 8,105 reaches the projector while 8,104 remains missing. May it write Omar or advance the checkpoint because 8,105 is the largest number seen? No. A checkpoint is the highest gap-free offset applied. The projector rejects that future-gap record before any write; it leaves checkpoint 8,103 unchanged. Once Priya's 8,104 arrives and fills the prefix, Omar's 8,105 may apply.
6:07 The largest observed record can't really certify a missing position. The log now defines replay order and board version. Oh, man. So even receiving the later record doesn't prove completeness: largest seen is not complete. 42 says Priya's authoritative best is newer. Her assigned position proves only log placement; a checkpoint reaching it proves the projection includes every winner through her record. Exactly. Now we can prove whether tournament close may pass that gap. Now take this close failure on the same shelf.
6:38 The projector dies at checkpoint 8,103; `R7` lacks its saved offset acknowledgement. A replacement starts, and the old owner wakes. My instinct, honestly, treats promotion as readiness. Why is that unsafe? Promotion changes who may write. A higher-numbered badge authorizes the replacement. Our application-owned Redis Function, a server-side script that runs atomically, rejects every lower-epoch stale-projector write before any state changes. Readiness is different: exact reads require the gap-free shelf to catch up.
7:10 Here the shelf reaches 8,103. Its next slot is empty, so the board is not ready. The badge proves authority; the shelf still ends at 8,103. Walk me through the proof that lets us close. First, stop admitting receipts and durably save the last accepted cutoff. Then save a decision for every receipt through it. Priya's late 9,500 loses, so it is settled without a log slot. The cutoff fixes who counts, and all admitted receipts have saved answers. Winners still need durable placement. What proof must the relay save?
7:42 Every winner gets a permanent board-log offset; the relay saves the returned acknowledgement. Only after every decision and every winner acknowledgement are durable may the control plane append the close marker. I have Priya's saved 8,104 acknowledgement. We're still waiting on Omar before that marker, right? Right. Omar gets slot 8,105, and its acknowledgement must be saved before the control plane adds marker 8,106. Then the higher-epoch projector applies 8,104 through 8,106 without gaps and freezes when its checkpoint reaches the marker.
8:15 Hold on, I'm seeing the missing proof: the shelf is filled. That gives us every winner, but replay could still swap tied players. Which comparator keeps their order? Same points are not enough. Replay must rebuild their exact order. How does Redis carry the tie? Both use numeric score minus 10,000, so higher points sort first. When scores tie, Redis compares the member string. Its first field is achievement time; its second is stable player ID, matching the product's tie order. Priya reached 10,000 at time 12 with ID one.
8:47 Omar reached it at time 13 with ID nine. Earlier time keeps Priya ahead. Right. Redis sees equal scores, then 12 sorts before 13; if the times match, one sorts before nine. But why fixed-width timestamps? Because plain text puts 12 before two. Write two as zero-two, and time order matches text order. Production keeps that field order everywhere: fixed-width timestamp, separator, then fixed-width stable ID. The ID text is chosen so byte order matches ID order. Okay, I like that: a tiny encoding choice actually decides which tied player wins.
9:23 Replay is where it gets weird. Walk me through Priya's atomic update. Before the numbers, my first thought was to keep only her sorted-set member. But that member changes, so put a current-member lookup beside it; Priya's ID finds the old value without a scan. Right, the lookup moves with the rank entry. Together where? And does putting them together stop a read from seeing the half-update? Those are separate guarantees. Colocation says where one call can find the records: one Redis server, or one Redis Cluster hash slot owned by one shard.
9:57 Isolation says whether another command can cut in. Picture record 8,104 on one workbench. Colocation puts the records within reach. A bounded Redis Function keeps other commands waiting through its checks and writes. No read catches Priya between removal and replacement. That's exactly it. Use that bench: Redis checkpoint sits at 8,103, with Priya stored at version 41. The active projector brings record 8,104 with version 42. Before writing, Redis checks three things: this projector owns the current badge, 8,104 immediately follows checkpoint 8,103, and incoming 42 is newer than Priya's stored 41. All three pass.
10:37 One operation replaces her old rank member with the new one at numeric score minus 10,000, updates her lookup, stores version 42, and advances the checkpoint to 8,104. The checked epoch stays unchanged. These are unit tests outside the live tournament. Let's say the applied checkpoint starts at 8,103, while Priya's board entry shows 10,000 points under player version 42. An incoming exact-next record carries delayed 9,000, version 41; current owner, no gap. What changes? Redis advances only the checkpoint to mark that record processed.
11:13 Priya keeps her logical 10,000. Nothing else moves: encoded member, lookup, stored player version 42, or checked owner epoch. Take an independent reset: checkpoint 8,103, Priya projected at 10,000, version 42. Exact-next input matches: 10,000-point score, player version 42. Current owner, no gap. Same result? Yes. Checkpoint alone advances. Redis score stays minus 10,000; lookup, player version 42, encoded member, and checked owner epoch stay fixed. Priya keeps 10,000 logical points. Clients need checkpoint progress plus projected player version.
11:47 Now test the tempting shortcut. Priya has a stamped receipt showing 10,000 plus player-state version 42, while public standings reach only 8,103. If her accepted update already has assigned position 8,104, why not call the rank exact and let Redis catch up behind the label? Because assigned is not applied. Return: “Accepted: 10,000. Player state: 42. Rank: pending. Last complete board: 8,103.” Accepted means the ledger stored Priya's score; exact means the rank index incorporated it. Oh, right. Accepted is the stamped receipt; exact is the posted board.
12:23 The label cannot get ahead of the board. From that receipt-board split, exact rank needs two checks: the board checkpoint must reach the log position assigned to that accepted winner, 8,104, and Priya's projected player-state version must be at least accepted version 42. The response may name 8,104 or a later checkpoint. Which means exact rank can still be paired with the wrong neighborhood when a separate window races Omar onto another board version. Now take this race. Priya's rank call sees 9th at 8,104.
12:55 Omar's update at 8,105 moves above her, so Priya becomes 10th. A separate around-me call then reads the five-above, five-below window centered on 10th. What did the UI assemble? A board that never existed: rank nine attached to a rank-10 neighborhood. One atomic query function takes the photograph: it resolves Priya's member, reads her numeric rank and surrounding range, and returns the checkpoint before a write can interleave. That's a nasty bug: the finish table would publish a rank and neighborhood no complete board ever produced.
13:26 So every response names the version it read. Separately requested live screens may honestly return different versions; only matching labels may be compared as one board. Yes. The checkpoint belongs in the response because it is part of the answer's meaning, not merely an operations metric. Right. That leaves the friends screen exposed to the same race: it can read those two players on opposite sides of an update. How do we keep one request bounded and coherent? That race leads to one bounded read: Priya plus at most 49 server-supplied IDs, 50 total. Here the fixed set is Priya, Omar, Lina, and Chen.
14:05 Right. One Redis Function atomically returns their points, tie fields, and checkpoint; then the query service sorts that fixed set with the global comparator. At complete version 8,104, the global API returns Priya 9th and the friends API first; both show her score as 10,000. Nice. Same score, different ordinal, and both screens can prove why. At matching version 8,105, Omar moves Priya to global 10th and friends second. Both reads still rely on one ordered writer, so capacity is next. Now put that owner under load while Priya waits for the finish marker.
14:40 Imagine platform lead Dana voicing what teams assume: “We added Redis nodes. Why is this board still pinned to one owner?” Right. That's the scale-out reflex we all have: add nodes, expect the bottleneck to split. Redis Cluster partitions whole keys. Separate divisions can use other shards; the global board stays one key with 1 ordered owner. Hold on. If the key stays whole, what would hashing players across shards and adding local ranks buy us? A local rank can't count players on other shards, so it can't produce Priya's worldwide position. API replicas route requests.
15:16 Read replicas may return older standings labeled with their board version. Neither adds an ordered write lane. More API replicas add doors, not checkout lanes. One cashier owns six million ranked members. More doors, same cashier: 200,000 rank reads each second, plus winners toward Priya's marker. At the buzzer, 30,000 trusted receipts each second join. Suppose every receipt improves a player. What must the owner do before Priya's board can freeze? Apply 30,000 winners and reach the marker while serving reads: roughly seven reads per receipt.
15:49 Has that peak actually been benchmarked? No. Those are targets, not results. And we've all watched a target come back later dressed as a benchmark. Yeah. By the second planning meeting, nobody remembers which column was measured. So test reads and projection together. If one global competition is optional, split into divisions with separate boards and winners. Otherwise Priya's safe close depends on an unmeasured owner, which means the last crash must prove recovery preserves her finish. With capacity still an open test, return to the exact same architecture image for the last failure walk.
16:25 Suppose the worker crashes after record 8,104 updates the rank store but before the later close marker is appended; its process memory is lost. What can the replacement prove? Redis still holds Priya's member, player-version metadata, member map, and checkpoint 8,104. That proves her update survived, but the later close marker does not exist yet. And when the recovered old projector wakes up? The replacement owns a newer epoch, so Redis rejects stale-worker writes before they change state. The replacement may replay immediately.
16:56 Exact reads wait until its checkpoint covers the required durable log prefix with no gaps; frozen results wait for marker 8,106. Redis has already applied `R7` and checkpointed through position 8,104. Its replay writes nothing: the checkpoint, Priya's ranking entry, and player version stay unchanged. Priya's projected state is already right; what's uncertain is whether the relay saved the returned log-position acknowledgement. If `R7`'s offset acknowledgement remains unsaved, the relay retries the deduplicated append and persists the same position, 8,104. It also persists Omar's acknowledged position, 8,105.
17:32 Good. The winner acknowledgements are durable. What makes the board frozen rather than merely caught up? The cutoff is saved, every receipt through it has a durable decision, and every winner's offset acknowledgement is saved. Those facts authorize the control plane to append marker 8,106. The replacement applies Omar at 8,105, then that marker; reaching 8,106 freezes the board. `R7`'s safest replay is zero writes, so it preserves Priya's finish instead of rewriting it. At frozen version 8,106, every response shows Priya's score of 10,000, global rank 10, around-me centered on 10, and friends rank two in the same four-person set.
18:12 Omar is above her; the other two are below. I love that: the worker changed; Priya's finish did not. Thanks for listening to Learning Podcasts.