Ch.78: System Design: Build a Top-K Video Ranking Service
Outline
- 0:00 Find the videos people are watching now
- 0:37 The complete route to the answer
- 1:09 Decide which views belong
- 2:39 Make the small service work first
- 3:46 The winner lost between two servers
- 4:46 Add the pieces before picking winners
- 6:08 A video can win without another view
- 7:21 Batch a hot video without counting it twice
- 9:32 Agree on which minute has finished
- 11:23 Publish one result readers can keep
- 13:57 Exact ranking costs more than a small list
- 15:26 Follow the winner through the complete service
Transcript
0:00 A Top-K service lists a video app's most-watched videos; K says how many. Counts split between servers can hide the real winner. We'll build the path from accepted views to that list for the latest hour. And a small list can hide a large mistake. On screen, each of two servers sends its first-place video. Yet the video watched most across both servers disappears. X has five views on each server. That's 10 altogether, ahead of either local winner. I want our service to find X, then keep the answer correct as those views age out.
0:37 That missing winner leads to three jobs in this architecture: save accepted views, combine the pieces for each video, and publish a result the app can read quickly. Where do X's two pieces finally meet? Follow the middle of the diagram. Parallel workers send partial counts to the server responsible for each video. That server combines the pieces before choosing winners. The right side merges those winners into one saved snapshot. Queries read that prepared answer. We'll revisit this same map after sorting out what its counts actually mean.
1:08 Before filling in that map, our functional requirements are to count qualified views, return up to 100 videos, and refresh once per minute. Highest count wins; ties use video ID order. Qualified means another service has already decided that a view should count. We're trusting its filtering and deduplication. Our ranking service doesn't decide whether a person really watched. Right. It counts accepted records. For the time window, choose the latest 60 complete minutes of accepted reports. At noon, the timeline includes 11 o'clock and excludes noon itself.
1:40 For instance, a phone reports something watched at 11:30, but the report reaches us at 12:01. Which hour gets that view? The hour containing its durable acceptance minute. We don't use the phone's old timestamp to rewrite a closed minute. This product measures recently accepted viewing reports. Okay, my mental model was when people physically watched. Using acceptance time is a deliberate tradeoff; delayed reporting can make that a different ranking. It can. For non-functional requirements, accepted records must survive failures, each answer must describe one complete window, and 99 of 100 reads should finish within 100 milliseconds.
2:18 That's our target, pending a benchmark. We'll design for a hypothetical 100,000 accepted events a second, 10 million active videos per hour, and 50 count owners. Freshness has its own clock. Imagine Ava opens the app during an outage and gets last night's ranking. Low latency alone hasn't given her the recent popularity she asked for. Before distributing those counts, one server can maintain every active video's total and an ordered index. Update a video's count, then move its entry to the right position.
2:48 So the full store still has the videos below first place. The little result card containing X is a copy of the answer, not our entire state. Exactly. A scheduled job prepares that small answer, and the query API serves it. Apache Flink's Top-N docs describe a changing ranked result; our design saves a complete snapshot each minute. The links are in the description. That's the tempting memory saving here. Could we throw away the other rows once we've chosen 100? I'd keep them. Time can promote a video even when it gets no new view.
3:22 We'll test that in a moment; the current winners alone won't tell us who replaces them. Fair. A 100-entry heap keeps the smallest current winner handy while we choose the list. It doesn't become the database. Right. We can maintain the ordering after each update, or scan every active count when the minute closes. I'd benchmark that tradeoff. Queries read the prepared answer either way. Now take a small split across two servers. The first table has A with six and X with five. On the second, B leads with 6; X has another five.
3:56 Each server is correct about its own events. But these are partial counts for X. If both send only their first-place entry, neither sends X. The merger gets A and B, both with six, but no evidence that X exists. It can't add a count it never received. So every server can be healthy and every event delivered, and our own shortcut still loses the winner. We threw away its evidence. Yes. For this example, sending two entries would rescue X. That repair doesn't prove a generally exact result when one video's views are spread across servers. Sure, suppose I put another local competitor ahead of X on every server.
4:36 Collecting more candidates reduces the risk, but I still need a reason the true winner survives. How would you change what each server owns so its count is actually complete? Next, fix the split by giving each video one count owner. Every worker routes that video's partial minute counts there, using a stable partitioning rule over video IDs. Both arrows labeled X now meet at one owner. 5 plus 5 becomes 10 there. The owner can rank a complete value instead of guessing from a partial one. Each owner sends its best 100.
5:09 With 50 owners, that's at most 5,000 candidate rows. The merger selects the global 100 from those rows. I buy that for X. Consider a video below 100th place on its owner. Could it still belong among the global winners? No. If 100 complete videos beat it on that owner, those same 100 beat it globally. Adding other owners can't remove those competitors. Ah, that settles it. The proof comes from complete counts and disjoint ownership. It never applied to the event shards, where X's two halves were competing separately.
5:41 And all lists need the same window and tie rule. Otherwise equal-count videos could be cut differently, or we'd compare counts for different hours. So the little heap wasn't the broken part. We were asking it to rank numbers that hadn't finished being added. Right. Selection becomes safe after aggregation. We still have to keep those complete numbers correct when the left edge of the hour moves. Now test that moving edge. Let's say A has 10 views and B has nine. Nine of A's views are about to expire.
6:15 B's nine are newer. Advance the window 1 minute. A loses nine and drops to one. B loses nothing, so B becomes first without receiving a single new view. There it is. B did nothing, but it won anyway. I think keeping those losing rows is worth it; we can actually name the replacement when time changes the winner. That's why the winner list can't be the whole database. Retain all active totals, along with the minute contributions we'll subtract as they expire. If we store only A because it won last time, then after subtracting its nine...
6:51 ...we know A fell, but we've forgotten who should replace it. Keeping B's count is what makes that next answer possible. And each minute moves exactly once out of the active interval. Add the newly completed bucket, subtract the expired bucket, then update the ranking entries that changed. Would a cache expiry on each video's counter save us from managing those buckets? No. Expiring the whole counter at once drops recent and old views together. Our window needs 1 minute's contribution removed while the other 59 remain. That complete ownership raises a scaling problem: one popular video sends all its count changes to one owner.
7:28 Batch events on the intake workers to reduce that traffic. A worker sends one subtotal for X in a particular minute, instead of forwarding every view separately. Every subtotal still reaches X's owner before winner selection. That lowers the owner's message rate. The first layer still absorbs the event rate, and the owner still needs capacity for its incoming subtotals. Suppose the sender reports five, misses the acknowledgment, and sends it again. Does the count owner now store 10? It shouldn't. Give each source shard, video and minute one versioned subtotal.
8:02 Version 7 writes five on that card. Receiving the same card twice doesn't add another five. When version 8 says six, replace five with six. The total increases by one. An older version arriving afterward mustn't take it back to five. And save that version, subtotal and adjusted total in one atomic update. Acknowledge only after it's durable, so recovery can't restore a new version beside an old total. Take a worker that crashes just after sending six. The owner's acknowledgment hasn't reached it.
8:32 What does its replacement actually send? Look at the saved restart card. Before sending, the worker checkpointed its state, meaning it saved a consistent place to restart. The card ties what it has counted to where it stopped reading and what it still owes the owner. The pending message is still version 8, count six, for that same source, X and original minute. It sends that card again. The owner already has it, so this source still contributes six. Yes. Then the worker continues after its saved input position.
9:04 We haven't invented a new subtotal identity or moved the old view into a new minute. That restart card is doing more work than the retry itself. One limit, though. If upstream appends the same human viewing twice at two fresh log positions, this processor counts two accepted records. Right. Remembering input offsets prevents processing replay from inventing views. Recognizing duplicate human activity belongs to the qualification service we assumed at the start. Those batches raise a timing question: how can an owner know that all the required subtotals for the hour have arrived?
9:39 Each intake partition keeps an ordered durable lane. After it has appended every acceptance assigned to a minute, it appends a seal saying that minute is closed. A seal is a promise about that partition's data, not just a clock reading. Producers can't append another acceptance behind it. Later accepted records use the next open minute. A request reached the API before noon but waited to be written. Has it missed that minute? Yes. Acceptance happens at durable append. The ordered intake assigns the open minute then.
10:12 Waiting at the API doesn't let a request sneak behind a committed seal. Okay, return to our opening tables: five from each source. Its first five has arrived. The second is still on its way. Seeing a seal upstream doesn't make that second five appear here. Right. The completion marker leaves a worker only after all its prior subtotal writes are durably acknowledged. The owner waits for every required source. Only then can it select X with 10. A quiet queue can look awfully reassuring here. But if its connection died, treating silence as zero would erase the views we're waiting for. Exactly.
10:50 An empty minute still needs an explicit seal. Every owner list names the same cut: the saved stopping position for each required source. It also names one complete assignment of videos to owners. So the merger waits for all required owners at that cut. It doesn't combine one owner's new hour with another owner's older hour, or mix two ownership assignments. And if a source or owner stalls, the app's as-of time stops advancing. We've chosen an exact answer for a complete interval; freshness has to wait for the evidence.
11:23 Once those owner lists agree, the merger writes one immutable snapshot with the winners, window, source stopping positions and ownership version. Then it atomically moves a small current pointer to that file. Prepare first, publish last. A failed merge can leave an unused file, but the pointer still names an earlier complete answer. Exactly. The API reads that pointer once per response. Its cache key includes the snapshot ID, and the response carries the snapshot's own time and window. Two people might briefly receive different completed snapshots; neither gets mixed rows.
11:57 For example, Ava's app shows X at 10 when its owner fails. Keep her result card on screen. Does X vanish while we rebuild? No. Ava keeps the published result with its age, labelled stale as it ages. Once it's too old for the product's agreed policy, return unavailable. A fast response mustn't disguise an old ranking. For recovery, choose a deliberately simple policy: pause counting and rebuild the whole ownership assignment. Intake keeps saving new arrivals. Ava's answer is waiting, even though the log is growing.
12:28 Start from matching checkpoints and replay the retained log to the last complete cut, those recorded positions. Restore counts, minute contributions and subtotal versions together. On screen, the replacement has recovered X's two fives. X is 10 again, but the replacement still says prepared. Having the data and being allowed to publish are separate things. Yes. Once that whole assignment is complete, activate its new generation, the ownership version. Count stores reject old-generation writes. The transaction that advances the current pointer also checks that generation.
13:00 There, the old owner comes back with its old list. That same-transaction check rejects it, even if it started publishing before the switch. X belongs to exactly one active owner. Right. Resume after that cut under the new assignment. Later arrivals are safe in the log and can now catch up. Ava gets a newer complete answer when publication advances again. We paid for this simple restart with a pause in freshness. Our exercise retains the accepted log for 24 hours, so the missing positions might be gone.
13:33 What if the saved state needs input we've already deleted? Then rebuild a fresh complete hour or stay unavailable. We can't reconstruct expired input by reassuring ourselves that the cache still has a list. That stale card is a useful debugging clue too. Expose publication lag, missing seals, owner backlog and recovery gaps, so we can find what's holding up its next answer. That recovery state raises the memory bill. The slide compares our tiny result list with 10 million active videos: 160 megabytes for IDs and totals, plus 4.8 gigabytes for 60 dense minute counts, before overhead.
14:12 And the raw input alone would be 11.52 gigabytes for an hour at our hypothetical peak. The formulas and assumptions are on screen. A sparse layout can save empty bucket slots, but we still need the contributions that will expire. A bounded heavy-hitter summary can avoid retaining every exact count. It tracks likely frequent items using limited space. That's an approximate product choice. Look at these overlapping count ranges. X could lead under one set of actual values and trail under another. The estimate doesn't settle their order.
14:48 Apache DataSketches exposes estimates and count bounds; Redis Top-K is probabilistic. We'd need the chosen structure's actual merge and expiry guarantees. Neither description alone proves this exact sliding-window service. We could recount the candidates it kept. But that leaves the question from our opening: could an omitted video beat them? Yes, unless the summary's guarantee rules that out. Exact numbers for the shortlist don't prove that the shortlist contains every winner. So for this build we keep exact active counts and accept their storage and coordination cost. Approximation remains an option if the product can expose and tolerate that uncertainty.
15:26 Finally, return to the full architecture. X's two partial fives meet at its count owner before selection. The active minute state removes old contributions; every owner uses the same completed window. There it is. The merger publishes that complete answer as one snapshot, and X reaches the app with 10, its window and its age. As views expire, retained counts let a different video take the lead. Thanks for listening to Learning Podcasts.