GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Top K System (Spotify, YouTube)

Count five billion plays a day, keep one song’s midnight release from stalling the count, merge 64 machines’ lists without losing the real winner, move the last hour, day and 30 days every minute, and survive a crash without counting a play twice. Built one step at a time, with experiments you can run.

A top K system counts events, such as plays of a song or views of a video, and keeps a ranked list of the K items with the most of them over a recent window. Phones send each play to an API that appends it to a Kafka log. Flink counts in two stages: pre-counters spread the plays evenly by play ID and sum each second, then counting tasks keyed by song hold each song’s complete count. Each task keeps a running total per window, adds the minute that arrives and subtracts the minute that leaves, read back from Cassandra, then walks its counts with a size-K heap. A merger combines the 64 lists into one chart per window in Redis, labelled with the minute it is as of. Checkpoints save counts with their read position, so a crash never counts a play twice.

Difficulty: Medium. Reported in interviews at Meta, Microsoft, Amazon, Uber, Monzo. Also asked as Design top K YouTube videos, Design top K songs for Spotify, Design trending hashtags, Design top K heavy hitters.

Practise one part of it on a canvas that tests your design: Build a Trending Top K.

How do you design a top K system?

A top K system counts events, such as plays of a song or views of a video. It keeps a ranked list of the K items with the most of them over a recent window. “Top 50 songs of the last hour” and “most viewed videos this month” are top K lists. Every music and video app has one. Ranking ten songs on a laptop takes a hash map and a sort. Ranking five billion plays a day, every minute, over the last hour, day and month, is harder. The counts are spread over many machines, one song can bring a sixth of all traffic, and old plays must leave the window on time.

  1. Played: Lena plays Glasshouse. Phones send 5 billion plays a day. A weak signal sends some twice. Each counts once.
  2. Counted: Glasshouse: 30,000/s. At midnight one new song brings a sixth of all plays to whoever counts it.
  3. Ranked: Top 1,000 of 20 million. The counts live on 64 machines. Merging them must not lose the real winner.
  4. Windowed: Hour, day, 30 days. Plays from 61 minutes ago must leave the hour chart, even for a song nobody plays now.
  5. Shown: Top 50, as of 14:05. Every reader sees one list, at most a minute old, that says which minute it is.
One play, start to finish. The system does this about 58,000 times a second on average.

Picture Lena, who uses a music app. At 14:05 she opens “Top 50: last hour” and expects a list about the hour before 14:05, not about this morning. Last night at midnight a famous band released a single, Glasshouse, and for a few minutes it was played 30,000 times a second. Somewhere else in the catalogue is a song that is never first on any one machine’s count and still has more plays than any other. The chart has to get all of it right.

Interviewers like this problem because the first answer fits in two lines: count the plays in a hash map, then sort. The rest of the round is about what those two lines cannot do. The plays arrive faster than one database can record them, the counts live on many machines, and the window keeps moving.

Here is the design in brief. Phones send each play to a play API, which appends it to a Kafka log and replies. A stream processor, Flink, counts in two stages. The first stage spreads plays evenly and adds them up a second at a time. The second gathers every partial count for one song in one place. Each counting task keeps a running total per song for the last hour, day and 30 days, and every minute picks its own top 1,000. A merger combines those lists into one chart per window, stored in Redis, where the chart API reads it.

The rest of this page is about the moments that design has to survive.

The first is a release. A design that keeps each song’s count in a database row adds one to the row per play. One row takes about 1,000 updates a second, and Glasshouse brings 30,000. Within a minute, 1,740,000 updates are waiting, and the chart is a minute behind and falling further behind.

The second is a merge. Three machines each count part of the plays, and each sends its top two. A song that is third on all three, with more plays in total than anything else, is on no list. The chart leaves it out, and no merge can find a song that nobody sent.

What is the interviewer testing?

Most candidates reach a working answer in ten minutes: count plays in a stream, keep a heap of the top K, serve the result from a cache. That answer is right, and a mid-level answer often stops there.

The interviewer then pushes on each piece. One song gets a sixth of all plays. The counts sit on 64 machines. Old plays must leave the window. A counter crashes. Memory runs short. A senior answer keys the counts by song before ranking, and says why a shortlist from each machine can miss the winner. It keeps the last hour, day and month moving without 43,200 counters a song. A staff answer also splits a hot song across two stages, saves each count with the position it was read up to, and knows when an approximate count is worth its error.

Spend most of the deep-dive time on the merge and on the windows. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

Most played, or trending?
Most played ranks songs by their count. Trending ranks them by growth against a baseline: a song going from 20 plays to 60 is trending and nowhere near the top. Assume most played; trending is a short section at the end.
Which windows, and how fresh?
Assume the last hour, the last 24 hours, the last 30 days and all time, each at most a minute behind. A window ends at the last full minute, and the chart says so: “as of 14:05”.
How large is K?
A chart of 50 is typical. Assume K is at most 1,000, so one stored list of 1,000 answers every smaller K.
Exact counts, or close enough?
Charts are quoted, and labels are sometimes paid by them. Assume exact counts over the plays accepted. Approximation gets a deep dive of its own.

Functional requirements

On the board: Functional requirements
1. Record every play of every song
2. Top K songs, K ≤ 1,000, with play counts
3. Last hour, 24 hours, 30 days, all time
out: trending, per country, what is a play

Say it, don’t write it: The ranking itself is a few lines of code. The hard part is keeping it exact while the counts are spread over machines and the window moves.

The users are two groups. Listeners read the charts: songs in order, each with its number of plays. Editors and record labels quote those numbers, so a plausible number that is wrong still does harm.

  1. Record every play of every song, sent by the app once a play qualifies.
  2. Return the top K songs, for any K up to 1,000, with each song’s play count.
  3. Over four windows: the last hour, the last 24 hours, the last 30 days, and all time.

Out of scope

  • Deciding what counts as a play, such as 30 seconds of listening, which the app does before it sends one
  • Trending, meaning fastest growing, which a short section at the end covers
  • Charts per country or per genre, beyond a paragraph at the end
  • Recommendations and personal charts

Non-functional requirements

On the board: Non-functional requirements
• 5B plays/day ≈ 58k/s; peak 174k/s
• One song can take 30k/s at a release
• Each chart ≤ 1 min behind, “as of” shown
• Exact counts; each play counted once
• Chart reads < 100 ms p99, precomputed

Say it, don’t write it: The average is easy. The peak and one hot song decide how the counting is split.

  • About 5 billion plays a day: about 58,000 a second on average, and 174,000 at peak.
  • One song can bring 30,000 plays a second when a famous artist releases it.
  • Each chart is at most a minute behind, and says which minute it is as of.
  • Counts are exact over the plays accepted, and each play is counted once, even after a crash.
  • Reading a chart takes under 100 ms at the 99th percentile (p99).

Two numbers are worth working out now, because each decides a piece of the design. The first is the write rate. 5,000,000,000 plays ÷ 86,400 seconds is about 57,870, so about 58,000 a second. A big album released at midnight can triple that, to about 174,000. A database write per play would mean 174,000 writes a second before a single chart is read. So plays are counted in memory, in a stream, and only the counts are written.

The second is the read. A chart is 1,000 songs with a count each, about 50 KB. It changes once a minute and is read by everyone who opens it. So charts are computed once a minute and stored ready to serve, and a read never counts anything.

The other numbers appear in the deep dive that needs them. They are illustrative interview targets, not measurements of any particular app.

Core entities

On the board: Core entities
Play(play ID, song, listener, played at)
MinuteCount(key group, minute → song: n)
WindowTotal(song → hour, day, 30 days)
AllTime(song → total)
Chart(window, as of, top 1,000 + counts)

Say it, don’t write it: A play is the fact. Everything else is a count derived from plays, and can be rebuilt from them.

Follow one of Lena’s plays through the records. At 14:04:31 her phone finishes 30 seconds of Glasshouse and sends a play. It carries a random play ID the phone made, the song, her user ID and the time it was played. The play goes into the log, and a counter adds one to Glasshouse’s count for the minute 14:04.

At 14:05 that minute closes. The counter writes the minute’s counts to disk as one row, and adds them to Glasshouse’s three running totals and its all-time total. The merger then writes four charts, each labelled “as of 14:05”.

RecordWhat it holdsWhy it is separate
PlayPlay ID, song, listener, when it was playedThe only fact; everything else is derived from plays
Minute countFor one key group and one minute: each song’s playsSubtracted when that minute leaves a window
Window totalPer song: plays in the last hour, 24 hours and 30 daysThree numbers a song, kept in memory
All-time totalPer song: every play everOnly goes up, so it needs no subtraction
ChartOne window, the minute it is as of, 1,000 songs with countsComputed once a minute, read by everyone

The one distinction that matters: a play must never be lost, but every count can be rebuilt. If a counter’s memory is wiped, the plays in the log and the archive can produce the same numbers again. That is why counts can live in memory at all.

API

On the board: API
POST /plays  [{play_id, song_id, played_at}]
  → 202
GET /charts/:window?k=50
  → {as_of, songs: [{id, plays}]}
window: hour | day | month | all

Say it, don’t write it: The chart is built once a minute and read many times. A read never counts anything.

Phones call one endpoint to record plays, and every reader calls one to get a chart.

CallReturnsWhy it looks like this
POST /plays with a batch of up to 50 plays202 once the plays are in the logA phone sends plays in batches, which cuts the number of requests
Each play: play_id, song_id, played_atNothing moreThe listener comes from the signed-in session, not the body
GET /charts/{window}?k=50The top K songs with counts, and as_ofAny K up to 1,000 is the start of one stored list
window: hour, day, month or allThe chart for that windowFour fixed windows, each computed ahead of time

Two fields exist for a reason. The play_id is made by the phone, so a play the phone sends twice after a lost reply carries the same ID twice, and can be recognised. And played_at is when the song was played, not when the play arrived. A phone that was offline on a plane sends hours of plays at once, and each belongs to the minute it happened.

The response carries as_of, because a chart is always about a window that ended at some minute. A reader who sees “as of 14:05” at 14:05:40 knows the chart is current. A reader who sees “as of 13:52” knows something is behind.

Step 1: record every play in a log

Start with the plays. A phone calls POST /plays with a batch. The play API checks the session and the fields, then appends each play to a Kafka topic called plays. It replies 202 once Kafka has written the plays to at least two of their three replicas (acks=all with min.insync.replicas=2). The API holds no counts and no state, so any instance can take any request.

Kafka only adds to the end of a log, which is what makes it fast. The topic is split into partitions across brokers, and together they take hundreds of thousands of appends a second. Kafka keeps the plays for 7 days, long enough to replay anything the counters lose.

The interactive version of this example is available when JavaScript loads.

Nothing is counted yet. The log is the record of what happened, in the order it arrived.

Step 2: count by song, and rank the last hour every minute

A Flink job reads the log. Plays are keyed by song ID, so every play of one song goes to the same one of 64 counting tasks. A task adds each play to its song’s count for the current minute, in memory. It also keeps the last 60 minute counts per song and a running total for the hour.

Each minute the task closes the minute. It adds the new minute to each song’s hour total and subtracts the minute from 60 minutes ago. Then it picks its own top 1,000 songs and sends them to a merger. The merger takes the 64 lists, 64,000 candidates, keeps the best 1,000, and writes them to Redis under one key per window and minute, such as chart:hour:2026-09-27T14:05. Last, it points chart:hour:current at that key. It waits for all 64 lists for a minute before it merges, which is where the busiest task sets the pace. A reader follows the pointer, so it always gets one whole chart, never half of one minute and half of the next.

The interactive version of this example is available when JavaScript loads.

The chart API is a thin reader. It reads the pointer, reads the chart it points at, and returns the first K songs. Redis answers in well under a millisecond, which leaves the 100 ms budget almost untouched.

Step 3: the last 24 hours, the last 30 days and all time

The hour chart keeps its 60 minute counts in memory. The same trick for 30 days would keep 43,200 counts per song, which the windows deep dive shows is terabytes. So each closed minute is also written to Cassandra, as one row per group of songs and minute. The counting task keeps three running totals per song. Each minute it adds the new minute to all three, then reads back the rows for the minutes leaving each window and subtracts them. The subtraction reads at QUORUM, since a subtraction that reads half a row leaves the total wrong for good.

All time is simpler. A song’s all-time count only goes up, so the task adds each minute to it and never subtracts. The merger now writes four charts each minute, one per window.

The interactive version of this example is available when JavaScript loads.

The windows deep dive shows why this beats keeping more counts in memory, and what it costs.

Step 4: keep every play, so any count can be rebuilt

Kafka keeps plays for 7 days. A connector also copies every play into files in object storage (S3), one folder per hour, kept for a year. Two jobs read them. A nightly batch job recounts yesterday from the files and compares each minute row with its own count. A bug in the stream then shows up as a difference the next morning. And after a bug fix, the same files rebuild every count from scratch.

This is the part of the design that makes the counts trustworthy. The stream is fast. The archive is what lets anyone check it.

The interactive version of this example is available when JavaScript loads.

With a quiet catalogue this is already a working top K system. The deep dives take it through a release at midnight, a merge that loses the winner, windows that must forget, a crash, and a tight memory budget.

A new single gets 30,000 plays a second. Why does its counter fall behind?

At midnight a famous band releases Glasshouse. Fans are waiting, and from the first second it is played 30,000 times a second, about a sixth of everything the app is playing. Lena is one of those listeners. At 00:01 she opens “Top 50: last hour” to see whether it has reached number one.

The first design most people draw keeps a play count in the songs table. Each play adds one: UPDATE songs SET plays = plays + 1 WHERE id = 'glasshouse'. Every play of Glasshouse updates the same row. A database lets one transaction change a row at a time, and each holds the row’s lock until it commits. If a commit takes about a millisecond, that row takes about 1,000 updates a second.

Glasshouse needs 30,000. Each second, 30,000 − 1,000 = 29,000 more updates join the queue. After a minute, 29,000 × 60 = 1,740,000 are waiting. The count Lena sees is already a minute old, and it gets older every second.

Splitting the table across more database servers does not help. Every Glasshouse update is for one row, and one row lives on one server. Meanwhile the rest of the app still sends 144,000 plays a second, each one a write.

The fix is to stop writing each play. Plays go to the Kafka log instead, and Flink counts them in memory. Plays are keyed by song ID, so every play of one song reaches the same one of 64 counting tasks. That task adds one to a number in memory, which takes nanoseconds instead of a millisecond. It writes a count once a minute. The database now sees one write per song per minute instead of one per play.

That creates a new problem, and the arithmetic shows it. At peak, the other songs bring 174,000 − 30,000 = 144,000 plays a second. Spread over 64 tasks, that is 2,250 each. The task that owns Glasshouse gets its 2,250 plus all 30,000 of Glasshouse: 32,250 a second, 14 times the load of every other task. Its part of the log falls behind first. Each chart waits for every task to close its minute. So every song’s chart is now as late as the busiest task.

Adding tasks does not help. Glasshouse is one key, and one key goes to one task. So count in two stages, the standard cure for a hot key.

In the first stage, plays are spread evenly: keyed by the play’s own random ID, not the song. Each of 64 pre-counters gets about 174,000 ÷ 64 ≈ 2,720 plays a second, whatever is popular. A pre-counter adds up what it saw in one second and sends one message per song, such as “Glasshouse, 00:00:41, 470 plays”. In the second stage, those messages are keyed by song, so all of Glasshouse’s partial counts meet in one counting task.

Replay the midnight. The Glasshouse task no longer receives 30,000 plays a second. It receives at most 64 messages a second for Glasshouse, one from each pre-counter, each carrying about 30,000 ÷ 64 ≈ 470 plays. Flink’s own table layer has a similar two-stage split, local-global aggregation, made “to solve data skew problem” (Flink). It sums on each upstream task before any shuffle. Here the first stage gets a shuffle of its own, by play ID, because the deep dive on restarts needs every copy of a play on one task.

The long tail passes through almost unchanged. A pre-counter that saw 2,720 plays in a second saw perhaps 2,000 different songs, so it sends about 2,000 messages. The saving is all on the hot songs, which is where it was needed. The cost is up to one more second of delay and one more hop across the network.

“470 plays of Glasshouse” is one sixty-fourth of the truth, and no pre-counter knows any song’s total. That matters in the next deep dive.

The interactive version of this example is available when JavaScript loads.

The experiment replays the first minute of Glasshouse three ways. The tabs are a database row per song, counting tasks keyed by song, and pre-counters in front of them.

The interactive version of this example is available when JavaScript loads.

The gap: One song can bring a sixth of all plays, and whatever counts that song must take all of them.

Option 1: A count row per song

Each play adds one to the song’s row in the database.

Works when: A few plays a second per song.

Breaks when: One row takes about 1,000 updates a second, and a release brings 30,000.

Option 2: Count in a stream, keyed by song

Plays go to a log, and one task per group of songs counts in memory.

Works when: Traffic spread over many songs.

Breaks when: The hot song’s task carries 14 times the load, and every chart waits for it.

Option 3: Pre-count by play ID, then key by song (start here)

The first stage spreads plays evenly and sums each second; the second gathers each song’s parts.

Works when: Once one song can outrun one task.

Watch for: Up to a second more delay, and the parts mean nothing until they meet.

In the interview: Open with option 3, and earn it with arithmetic. Say option 1’s number first, 1,000 updates a second against 30,000. Then show option 2’s one task at 32,250 against 2,250 for the rest.

Say this: A count row caps a song at about 1,000 plays a second, so plays go to a log and are counted in memory. Keyed by song, a release that takes 30,000 a second lands on one task, 14 times the load of the others. So I pre-count in a first stage keyed by play ID, summing each second, and key those partial counts by song in a second stage. A hot song then costs its counter one message a second from each pre-counter.

Each machine sends its top 1,000. Why is the most played song missing?

At 14:05 the chart for the last hour must be built. Suppose a teammate suggests skipping the second stage. Each of the 64 pre-counters would keep its own hour counts for the plays it saw. Each would send its own top 1,000 to the merger, which adds up the lists and keeps the best 1,000. Less data moves, and nothing is keyed twice.

Shrink it to see what happens: three pre-counters, four songs, and a chart of two. In the hour, the first pre-counter saw Neon Rain 52 times, Paper Moon 45, Slow Orbit 40 and Low Tide 3. The second saw Paper Moon 51, Low Tide 44, Slow Orbit 40 and Neon Rain 5. The third saw Low Tide 50, Neon Rain 43, Slow Orbit 40 and Paper Moon 7.

Each sends its top two. The merger adds what it received. Paper Moon has 45 + 51 = 96, Neon Rain 52 + 43 = 95, and Low Tide 44 + 50 = 94. It publishes Paper Moon and Neon Rain.

Now add up everything. Slow Orbit had 40 + 40 + 40 = 120 plays, more than any other song. It was third on every machine, so no list mentioned it. No merge can find a song that nobody sent. The published numbers are wrong too. Paper Moon really had 45 + 51 + 7 = 103. Its 7 plays on the third machine sat below that machine’s top two, so the chart says 96.

The natural patch is a longer list. Ask each pre-counter for its top three instead. Slow Orbit now appears on all three lists and wins with 120. But Paper Moon still shows 96, because its 7 plays were fourth on the third machine.

A longer list fixed who is on this chart, not the numbers, and only because the length was picked after seeing the data. Whatever the length, a song can sit just below every machine’s list and still have the highest total. A longer shortlist makes a miss less likely. It never makes one impossible, and nothing on the page can prove that a given length is enough.

The fix is the second stage from the previous deep dive: key the counts by song. Every partial count for Slow Orbit goes to one counting task, which adds them into one complete total, 120. Each counting task now owns a set of songs that no other task holds, and holds each of them in full.

Replay the minute. Slow Orbit and Neon Rain happen to share a task, so that task sends Slow Orbit 120 and Neon Rain 100. The other two send Paper Moon 103 and Low Tide 97. The merger publishes Slow Orbit 120 and Paper Moon 103, which is the true chart.

Why is that enough for any data? Take any song that is not in its own task’s top K. At least K songs on that same task beat it. Their counts are complete, so those K songs beat it everywhere. So a song that loses on its own task cannot be in the overall top K. Every song that is in the overall top K is on its task’s list.

Three conditions make this work. Each song lives on one task. Its count there is complete. And every task counts the same window and breaks ties the same way, by song ID.

The merge itself is small. 64 tasks send 1,000 candidates each, 64,000 per window each minute, about a megabyte. The expensive part was the shuffle that keyed the counts by song, and the hot-song deep dive already paid for it.

There is one more answer, and a staff candidate may name it. If the counts must stay where they are, an exact merge takes three rounds. Each machine sends its top K. The merger adds those up and takes the K-th best sum as a threshold T. It then asks each of the m machines for every song whose local count is at least T ÷ m. A song below that on every machine cannot reach T. Last, it asks for the exact counts of the songs that survive. This is the TPUT algorithm (Cao and Wang). It suits a one-off query over data that cannot move. A chart rebuilt every minute is cheaper to key by song once.

The experiment runs the minute three ways. The tabs are each pre-counter sending its top two, each sending its top three, and counting tasks keyed by song.

The interactive version of this example is available when JavaScript loads.

The gap: A machine can only rank what it counted, and a shortlist drops a song before its parts are added up.

Option 1: Each machine sends its top K

The merger adds the lists and keeps the best K.

Works when: Only when each song lives on one machine.

Breaks when: A song just below every list is never seen, and listed songs are undercounted.

Option 2: Each machine sends a longer list

Ask for the top 2K or 10K instead.

Works when: As a guess, when the data is known not to spread.

Breaks when: A song just below every longer list is still lost, and nothing proves the length is enough.

Option 3: Key by song, then merge each owner’s top K (start here)

Every count for a song reaches one task, so each task’s top K is complete and the merger reads 64 lists.

Works when: Always, for counts that add up.

Watch for: It needs the shuffle that keys every count by song, which the hot-song deep dive already built.

Option 4: Three rounds with a threshold (TPUT)

Fetch the top K, then every song above a threshold, then exact counts.

Works when: A one-off query over data that cannot move.

Watch for: Three round trips for every chart, every minute.

In the interview: Open with option 3, and prove it in two sentences: a song that loses on its own task loses everywhere. Show option 1 failing with a small example like this one. Mention option 4 only if the interviewer asks how to merge without moving the data.

Say this: Taking each machine’s top K and merging loses any song that sits just below every list, and undercounts the songs it keeps. So I key counts by song, and each counting task owns its songs completely. Then each task’s top K is enough, because a song that loses on its own task loses everywhere. The merger reads 64 lists of 1,000 each minute.

Do you sort 20 million songs every minute to find the top 1,000?

Each counting task now owns about 20,000,000 ÷ 64 = 312,500 songs that were played in the last hour. Every minute it must find its own top 1,000 of them. Sorting all 312,500 would work, but it does more than needed. Nobody cares whether a song is 5,000th or 6,000th.

The usual tool is a min-heap of size K. Walk the counts once, and keep the best 1,000 seen so far in a heap with the smallest of them on top. Compare each song with that smallest member. If the song is larger, it replaces it, which costs about 10 steps, the base-2 logarithm of 1,000, with a heap that swaps its top in place. Most songs lose that one comparison and are skipped. At worst the walk costs about 312,500 × 10 ≈ 3.1 million steps, a few milliseconds.

A teammate suggests something cheaper still: keep the heap alive between minutes. Each play updates its song’s count. A song already in the heap moves whenever its count changes. A song outside it goes in when a play makes it beat the heap’s smallest member. There is no walk at all. It is the textbook answer to “top K in a stream”.

Watch it in a window. Take one task with six songs and a chart of three. At 14:00 the hour runs from 13:00 to 13:59. Radio Hearts has 900 plays, Paper Moon 700, Low Tide 650, Copper Sky 600, Wax Wings 300 and Lanterns 100. The heap holds Radio Hearts, Paper Moon and Low Tide. Copper Sky, fourth, is not in it.

At 14:01, minute 13:00 leaves the hour. Radio Hearts had a radio premiere in that minute, 400 plays, so it drops to 900 − 400 = 500. Paper Moon and Low Tide lose 10 plays each from 13:00 and gain 10 each in the new minute, so they stay at 700 and 650.

Copper Sky got no plays in the new minute. Nothing tells the heap about it. The heap shows Paper Moon 700, Low Tide 650 and Radio Hearts 500. Copper Sky has 600 and belongs in third place. The heap will not look at it again until someone plays it. A heap kept alive is correct only while counts go up, and in a window they go down.

The fix is the walk from the start of this deep dive. Each minute, after the totals change, the task rebuilds its heap from every song’s count, not only from the songs that just got a play. Replay 14:01. The walk meets Copper Sky at 600 and puts it third, above Radio Hearts at 500.

The cost is the walk itself. For the hour it is the 3.1 million steps. The day and 30-day windows add about 40,000,000 ÷ 64 = 625,000 and 80,000,000 ÷ 64 = 1,250,000 songs per task. Together that is about 2.2 million songs, about 22 million steps at worst, tens of milliseconds a minute on one core.

The live heap is not wrong everywhere. All-time counts only go up, so a song can only enter the all-time top K by getting a play, and the heap sees every play. The all-time chart keeps a live heap and skips the walk. A window lets counts fall, so it needs the walk.

Why cap K at 1,000? Each task keeps its best 1,000, and the merger keeps the best 1,000 of 64,000. A reader who asks for the top 50 gets the first 50 of that list. A reader who asks for the top 5,000 cannot be answered from it. The 5,000th song may be 1,200th on its own task, and no task sent that far down. A larger K means longer lists from every task, every minute.

Ties are broken by song ID everywhere, on every task and in the merger. Two songs with the same count then come out in the same order every time.

The experiment steps through 14:00 and 14:01 on one task. The tabs are a heap kept alive between minutes and a heap rebuilt from every count each minute.

The interactive version of this example is available when JavaScript loads.

The gap: Counts in a window go down as old plays leave, so a song can move up without getting a play.

Option 1: A heap kept alive between minutes

Each play updates its song, which enters the heap if it beats the smallest member.

Works when: Counts that only go up, such as all time.

Breaks when: A song that climbs because others lost plays is never seen until someone plays it.

Option 2: Walk every count each minute into a size-K heap (start here)

After the totals change, compare every song with the heap’s smallest member.

Works when: Every window, at tens of milliseconds a minute per task.

Watch for: The walk grows with the songs a task owns; at a billion keys, count differently.

Option 3: An ordered index updated on every change

A sorted structure over every song, such as a balanced tree, kept in order as counts move.

Works when: When readers need any song’s rank, not only the top K.

Watch for: Every play and every leaving minute reorders it, many thousands of times a second.

In the interview: Open with option 2, and say why option 1 fails in a window: a song can rise without a play. Then say that the all-time chart can use option 1, because its counts only go up.

Say this: Each task walks its counts every minute into a min-heap of size 1,000, a few million comparisons. A heap kept alive between minutes is right only when counts only go up. In a window a song can rise because another song’s old plays left, and a live heap never sees it. So windows are rebuilt each minute, and only the all-time chart keeps a live heap.

Last hour, last 24 hours, last 30 days: how many counts does one song need?

The hour chart keeps 60 minute counts per song and a total. At 14:05 it adds minute 14:04 and subtracts minute 13:04. Now the product asks for the last 24 hours and the last 30 days as well, each at most a minute behind.

The obvious extension keeps a count per minute for as long as the longest window. Thirty days is 30 × 1,440 = 43,200 minutes. A song that is played every minute fills all of them. About 80 million songs are played in a month. At 4 bytes a count, that is up to 80,000,000 × 43,200 × 4 bytes, about 13.8 TB of memory. The 24-hour window alone, 1,440 minutes for 40 million songs, is 230 GB.

The next idea keeps coarser counts for longer windows: 60 minute counts for the hour, 24 hour counts for the day, and 30 day counts for the month. That is 114 counts per song, at most 36.5 GB. But now a window can only move by a whole bucket. At 14:05 the 24-hour chart cannot drop part of yesterday’s 14:00 hour, so it moves once an hour and says “as of 14:00”. The 30-day chart moves once a day. That misses the requirement. Many products accept it, and if the interviewer does, it is a good answer.

Look at what the hour chart actually does each minute. It adds the minute that arrives and subtracts the minute that leaves. It never needs the 58 minutes in between. So keep only a running total per window, three numbers a song, and fetch the leaving minute only when it is needed.

Each minute, every counting task writes its closed minute to Cassandra as one row: its songs and their counts for that minute. At 14:05 it adds minute 14:04 to all three totals. Then it reads back three old rows, for 13:04 today, 14:04 yesterday and 14:04 thirty days ago, and subtracts each from its own window’s total.

The counts in memory are now 80,000,000 songs × 3 totals × 4 bytes, 960 MB across the whole fleet. Song IDs and the hash map add a few GB in any of these designs. Disk holds every minute row for 30 days. About 2 million different songs are played in a minute, and a song ID with its count is about 12 bytes. So the rows take 2,000,000 × 43,200 × 12 bytes, about 1 TB, which Cassandra holds easily. Each task reads three rows a minute for each group of songs it owns. All three charts move every minute.

Subtracting on a timer has one more effect. A song that nobody is playing still loses its old plays, because the subtraction runs every minute whether the song got a play or not. A design that only expires a song’s counts when its next play arrives keeps an abandoned song on the chart for as long as nobody plays it.

Resizing the job raises one more problem. Say Paper Moon is counted by task 12 of 64, whose minute rows are saved as “task 12”. The job grows to 128 tasks, and Paper Moon moves to task 75. Tomorrow task 75 reads its own rows, finds no Paper Moon, and never subtracts yesterday’s plays. Flink avoids this with key groups: a fixed number of groups, as many as the job’s maximum parallelism, and a key never changes group (Flink). So rows are keyed by key group and minute. Each task reads the rows of the groups it owns. The maximum parallelism is fixed before the first deploy, since changing it reassigns every key.

A real-time analytics database offers a different design. It stores minute counts in a real-time analytics database, such as Apache Pinot, Apache Druid or ClickHouse. Each chart is then a query that sums each song’s plays over the window and keeps the top 1,000. It answers any window and any filter, such as a country or a genre, without new code. The price is that every query reads the window. Thirty days is 2,000,000 × 43,200 = 86.4 billion song-minutes, which these stores roll up into hours and days to stay fast. It fits a product that asks new questions every week. A chart with four fixed windows, read thousands of times a second, is cheaper to compute once a minute.

The experiment plays one hour on all three charts. The tabs are a count for every minute, coarser counts for longer windows, and running totals that subtract the minute that leaves.

The interactive version of this example is available when JavaScript loads.

The gap: Old plays must leave each window on time, and the longest window is 43,200 minutes.

Option 1: A count per minute for 30 days

Keep every song’s minute counts in memory for the longest window.

Works when: Short windows only.

Breaks when: Up to 13.8 TB of counts for the 30-day chart.

Option 2: Coarser counts for longer windows

Minutes for the hour, hours for the day, days for the month.

Works when: When the day chart may move hourly and the month chart daily.

Breaks when: Long charts move in steps, up to an hour or a day behind.

Option 3: A running total per window, minus the minute that leaves (start here)

Write each minute to Cassandra, add it to three totals, and subtract the rows leaving each window.

Works when: Fixed windows that must all move every minute.

Watch for: About 1 TB of minute rows on disk, keyed by key group so a resize keeps working.

Option 4: Query an analytics store

Sum each song over the window at read time, in Pinot, Druid or ClickHouse.

Works when: New windows or filters every week.

Watch for: Each query reads the whole window, so cache each chart for a minute.

In the interview: Open with option 3. Do option 1’s arithmetic first, 13.8 TB, so the interviewer sees why. Offer option 2 as the cheaper answer if hourly movement is acceptable, and option 4 if the questions will keep changing.

Say this: A count per minute for 30 days is up to 13.8 TB, and coarser buckets make long charts move in steps. So each counting task keeps three running totals per song, 960 MB of counts for the fleet, and writes each closed minute to Cassandra. Each minute it adds the new minute and subtracts the rows leaving the hour, the day and the month. The subtraction runs on a timer, so a song nobody plays still falls.

The interactive version of this example is available when JavaScript loads.

The code has four tabs. They are the two stages from the first deep dive, closing a minute from this one, a task’s top 1,000 from the heap deep dive, and publishing a chart.

A counter restarts. Why did Glasshouse gain 270,000 plays that never happened?

Go back to midnight, and to the simplest counter anyone would write before reaching for Flink. It reads plays from Kafka and adds them to a count in Redis with INCRBY as they arrive. Every 10 seconds it tells Kafka how far it has read, so a replacement knows where to start. That saved position is its offset.

At 00:00:10 the counter has added 300,000 plays of Glasshouse, and it saves its offset. At 00:00:19 Redis says 570,000. Then the machine dies, one second before the next save. A replacement starts from the saved offset, 00:00:10, and reads those nine seconds again. Redis already has them, and the replacement adds them again: 9 × 30,000 = 270,000 plays that never happened. The chart says 840,000.

Saving the offset first and counting afterwards fails the other way. Say the counter saves 00:00:20 and dies before adding the plays from that stretch. The replacement starts at 00:00:20, and those plays are never counted. The count and the offset are two facts, and a crash can land between any two writes.

The fix is to save them as one. Flink takes a checkpoint every few seconds, and here the last one completed at 00:00:10. A checkpoint is a consistent snapshot of every task’s counts, together with the Kafka offsets those counts include. After a crash, Flink “selects the latest completed checkpoint”, gives each task the counts from it, and sets the sources to read from the checkpoint’s offsets (Flink).

Replay the crash. The count goes back to 300,000 and the offset to 00:00:10, together. Reading the nine seconds again adds them to a count that never had them, and the chart reads 570,000, the truth. Flink calls this exactly-once state: each play changes the counts once, however often it is read.

After the replay, the task writes the minute row for 00:00 and the charts again. Flink’s guarantee covered its own memory, not what it writes elsewhere. Each write is keyed by what it describes: the key group and minute, or the window and the minute it is as of. A second write replaces the same row with the same numbers, so writing twice is harmless.

A different kind of duplicate gets past checkpoints. Lena’s phone sends a play, the API stores it in Kafka, and the reply is lost on a weak signal. The phone sends the play again. Kafka now holds two records at two offsets. Both are real records, so a checkpoint counts both. Only the phone knows they are one play.

So the phone gives every play a random ID and resends it unchanged. The first stage is already keyed by play ID, so both copies reach the same pre-counter. It remembers each ID for 10 minutes and drops a repeat. At peak that is 174,000 × 600 = 104.4 million IDs. At about 40 bytes each, with the hash set’s overhead, that is 4.2 GB across 64 pre-counters, about 65 MB each. A retry more than 10 minutes after the first copy arrived would count twice. The app retries within seconds.

Some plays arrive late for honest reasons. Lena listens on a six-hour flight in offline mode. When the plane lands at 14:10, her phone uploads 80 plays made between 08:00 and 14:00. Counting them by arrival would put six hours of her listening into the 14:10 minute. A full plane of offline listeners could then push a song up this hour’s chart. So each play is counted in the minute it was played, played_at, not the minute it arrived.

Her play at 08:12 is outside the hour, so the hour chart ignores it. It belongs in the 24-hour and 30-day totals, and the counter adds it to both. It must also be in what gets subtracted later. Tomorrow, when 08:12 leaves the 24-hour window, the stored rows for 08:12 are subtracted from the total. If the late play is in the total but not in those rows, the subtraction removes too little. Her play then stays in the 24-hour total for good.

The obvious way is to add one to the stored 08:12 row. That is a read and a write to Cassandra. Cassandra does not roll back with the checkpoint, so a replay after a crash would add it a second time. So a late play is written as a row of its own, beside the minute’s row, keyed by its minute and its play ID. The subtraction reads both. A replay writes the same late-play row again, which changes nothing.

The current minute needs a moment of patience too. Flink tracks a watermark: its estimate of how far play time has progressed. Here the watermark trails the newest play time by ten seconds. Minute 14:04 closes when the watermark reaches 14:05, which is once plays from 14:05:10 have arrived on every partition. A play for 14:04 that arrives later is handled as a late play. A play older than 30 days changes only the all-time total. The play time comes from the phone, so a phone whose clock runs ahead could drag the watermark forward. The API caps played_at at the time the play arrived.

The experiment replays the crash at 00:00:19. The tabs are a counter that saves its offset separately, and Flink checkpointing counts and offsets together.

The interactive version of this example is available when JavaScript loads.

The gap: A count and the position it has read up to are two facts, and a crash can land between them.

Option 1: Save the offset after counting

Add to Redis as plays arrive, and save the offset every 10 seconds.

Works when: A count that may run a little high.

Breaks when: A crash replays up to 10 seconds of plays: 270,000 extra for one hot song.

Option 2: Save the offset before counting

Save the offset, then add the plays.

Works when: A count that may run a little low.

Breaks when: A crash between the two loses the plays for good.

Option 3: Checkpoint counts and offsets together (start here)

Flink snapshots every task’s counts with the offsets they include, and a crash rolls both back.

Works when: Always.

Watch for: Writes outside Flink must be keyed so a replay rewrites the same rows, and phone retries need play IDs.

In the interview: Open with option 3, and say what exactly-once covers: Flink’s own state, not its writes. Then give the two things that finish the job: outputs keyed by what they describe, and a play ID from the phone. Mention late plays if the interviewer asks about offline listening.

Say this: A count and its read position are two facts, so a crash between saving them either counts plays twice or loses them. Flink checkpoints both together and rolls both back after a crash, so each play changes the counts once. Outside Flink, minute rows and charts are keyed by what they describe, so a replay rewrites the same values. Phone retries carry a play ID, and the pre-counter keyed by that ID drops the repeat.

Could you count in fixed memory, and what would it cost?

An interviewer often asks this once the exact design is on the board: what if memory were tight? Before answering, work out what exact costs here. A song ID, its count and the hash map’s overhead take about 40 bytes. 20 million songs in the hour is 20,000,000 × 40 bytes = 800 MB, or 12.5 MB per counting task. Exact counts are cheap for songs.

The question matters when the keys are not songs but search queries, hashtags or links, where a day brings billions of different keys, most of them seen once.

The standard answer is a Count-Min Sketch. It is a small grid of counters, say 5 rows of 262,144 each, and each row has its own hash function. To count a play of Glasshouse, hash the song once per row and add one to the counter each hash lands on. To estimate Glasshouse’s count, read its five counters and take the smallest. The grid is 5 × 262,144 × 4 bytes, about 5.2 MB, however many songs there are.

Other songs share counters with Glasshouse, so every counter it reads holds its own plays plus whatever collided there. So an estimate is never too low, only too high. The smallest of the five is the one with the least collision. The error has a bound. Take a grid w counters wide. Each estimate is too high by at most e ÷ w of all plays counted. That holds with a probability that grows with the number of rows (Cormode and Muthukrishnan). An average hour has about 208 million plays, so the bound is 208,000,000 × 2.718 ÷ 262,144, about 2,160 plays, with probability at least 99.3% for five rows.

Whether 2,160 matters depends on where a song sits. On an ordinary hour, say the top song has about 1.2 million plays: 2,160 is 0.2% of it. The 1,000th song has about 5,900. Songs near it differ by about 5 plays a place, so an error of up to 2,160 is more than a third of the count. The typical error is smaller than the bound, a few hundred plays. That is still far more than 5, so hundreds of places near the cutoff can swap.

A sketch also cannot name songs. It answers “how often was this song played?” for a song you already have. To produce a chart, keep a list of candidate songs beside it. On each play, update the sketch and estimate the song. If the estimate beats the smallest of the current top K, add the song to the candidates. Each minute, estimate every candidate again and walk them into a heap of K, for the same reason as in the heap deep dive. A song whose counters collide with a hit gets an inflated estimate, and can become a candidate without earning it.

The experiment shows the race for places 996 to 1,000. Static Bloom, really 1,001st, gains 1,480 from collisions and takes a place. Wax Wings, really about 1,450th, gains 2,030 and takes another. Undertow and Hollow Pine, which belong, fall off.

The repair keeps more candidates than K, say the top 1,100 by estimate. A second pass over the minute rows or the archive counts those exactly, and keeps the true top 1,000. Recounting fixes the number of every candidate it holds. It cannot bring back a song that never became a candidate. So how many extra to keep is measured, by comparing the fast chart with an exact one for the same hour.

A sketch can also move with a window. Add the counters of two minutes’ sketches, one pair at a time, and you get exactly the sketch both minutes would have built together. That needs the same width, depth and hash functions in both. So keep one sketch per minute, add the arriving minute and subtract the leaving one, exactly like the running totals.

A second family keeps the names inside the summary. Space-Saving keeps m counters, each holding a key and a count. A key with no counter takes over the one with the smallest count and adds one to it. After N plays, the smallest count is never more than N ÷ m. So every key played more than N ÷ m times keeps a counter. No count is too high by more than N ÷ m either (Metwally, Agrawal and El Abbadi). Its counters cannot be subtracted, so it suits all time, or a window that starts fresh each hour, not a sliding one.

Large systems often run both kinds of count. A fast path counts approximately and publishes within a minute. A slow path, a batch job over the archived plays, counts exactly an hour or a day later and replaces the fast numbers. A batch path beside a speed path is called a Lambda architecture, and this is a common use of it. Here exact counting is cheap enough that the fast path is exact, and the nightly batch job stays as the check and the rebuild.

The experiment shows the last five places of the chart three ways. The tabs are exact counts, a 5.2 MB sketch, and a sketch whose top 1,100 are counted again exactly.

The interactive version of this example is available when JavaScript loads.

The gap: Exact counts need memory for every key, and some key spaces never end.

Option 1: Exact counts, keyed by song (start here)

A hash map per counting task, walked into a heap each minute.

Works when: Keys that fit: 20 million songs is 800 MB across the fleet.

Watch for: Memory grows with the number of different keys, so count the keys before choosing.

Option 2: Count-Min Sketch plus a heap

A fixed grid of counters estimates each key, and a heap keeps the best estimates.

Works when: Endless keys, such as search queries, when a short list is enough.

Watch for: Estimates run high, very likely by less than e ÷ width of all counts, so order near the cutoff is noise.

Option 3: Space-Saving counters

Keep m keys with counts; a new key takes over the smallest.

Works when: Heavy hitters with a guarantee: every key above N ÷ m is kept.

Watch for: Counts can run high by up to N ÷ m, so order near the cutoff is uncertain too.

Option 4: Approximate now, exact later (Lambda)

A fast approximate stream, then a batch job that replaces its numbers.

Works when: When charts may be approximate for an hour but must be exact for payment.

Watch for: Two code paths that must agree, and numbers that change when the exact ones land.

In the interview: Open with option 1, and do its arithmetic: 800 MB for the hour. Offer a sketch only when the keys stop fitting, and say what its error does at the cutoff: 2,160 against a 1,000th song of about 5,900.

Say this: Exact counts for 20 million songs are 800 MB, 12.5 MB per task, so I count exactly. When keys are endless, such as search queries, a Count-Min Sketch counts in fixed memory with a heap beside it. Its error is a share of all plays, about 2,160 in an hour here, which scrambles the places near 1,000. So I would keep extra candidates, recount them exactly, or let a batch job replace the numbers later.

“Trending” usually means growing fast, not played most. A song going from 1,000 plays an hour to 1,100 has grown 10%. A new song going from 20 to 60 has grown 200%. The most-played chart shows the first song, and a trending chart shows the second. Trending needs a baseline window, such as the same hour last week, and a rule for tiny counts, since 1 play to 3 is also 200%. A common rule is a minimum, say 500 plays in the current hour, or a constant added to both sides before dividing. Each song’s score depends only on its own two counts, which its task holds in full. So each task ranks by score in the same walk, and the merge argument still holds.

If they push: a chart for every country

A play happens in one country, so it updates two charts: the world’s and its country’s. The counting key becomes the country and the song together, and each task owns some of those pairs completely, so the merge argument holds per country. The number of keys grows less than it seems: a song played in 40 countries has 40 keys, not 200. Combinations are what explode. Country by genre by age group multiplies the charts, and each needs its own top 1,000 per window. Past a few fixed dimensions, the analytics store from the windows deep dive becomes the better fit.

If they ask: why not a Redis sorted set?

A Redis sorted set keeps members ordered by score, and ZINCRBY adds to a score. One sorted set per chart, incremented on every play, gives a live ranking with no stream processor. It has two problems here. Every play becomes a write to Redis, 174,000 a second at peak. The chart is one key on one Redis shard, so all of those writes land on one machine, and the hot-song problem returns for the whole catalogue. And a sorted set has no window: removing 13:04’s plays at 14:05 needs the minute counts anyway. A sorted set is the right tool for a game leaderboard, where scores change a few thousand times a second and a player asks for their own rank. Here it is a good place to store the finished chart.

Walk one play through the final design

At 14:04:31 Lena’s phone sends a play of Glasshouse with play ID p-7731. The play API appends it to Kafka and replies 202. A pre-counter keyed by play ID has not seen p-7731, so it adds the play to Glasshouse’s count for that second and sends the sum on. The counting task that owns Glasshouse adds the sum to the 14:04 minute.

Once plays from 14:05:10 have arrived, the watermark passes 14:05 and the minute closes. The task writes the 14:04 row to Cassandra, adds the minute to Glasshouse’s hour, day, 30-day and all-time totals, and subtracts the rows leaving each window. It walks its counts into four heaps of 1,000 and sends them to the merger. The merger writes chart:hour:2026-09-27T14:05 to Redis and moves the pointer. When Lena refreshes, the chart API reads the pointer and returns the top 50, as of 14:05, with Glasshouse first.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 record every playPlay API into Kafka, archived to S3, deduplicated by play IDThe phone must send a stable play ID, and retry within minutes
FR2 top K, K ≤ 1,000Counting tasks keyed by song, each walking a size-K heap, one mergerK is capped, because every task sends K songs every minute
FR3 four windowsRunning totals minus the minute rows leaving each window; all time only addsAbout 1 TB of minute rows, and late plays rewrite old rows
Exact, counted onceFlink checkpoints counts with their offsets; outputs keyed by what they describeA crash replays a few seconds of plays into the restored counts
One song at 30,000 a secondPre-counters sum each second before the counts are keyed by songUp to a second more delay

How does the answer change for top K videos, hashtags or heavy hitters?

Interview variantWhat carries overWhat changes
Design top K YouTube videosEverything on this page, with views instead of playsDeciding what counts as a view. See the video streaming breakdown
Design trending hashtagsThe log, the stages, the windowsHashtags are endless keys, so a sketch or Space-Saving becomes the main answer, and trending needs a baseline
Design top K heavy hittersThe merge argument and the windowsThe approximate deep dive becomes the whole problem: error bounds and memory
Design the top K most shared links, or top K errors in logsThe whole pipelineKeys are endless and mostly seen once, as with hashtags
Design a leaderboardA precomputed ranked listScores change in place and a player asks for their own rank, so a sorted set fits
Design an ad click aggregatorCounting in a stream, exactly once, with late eventsCounts feed billing. See the ad click aggregator breakdown
Top K frequent elements (the coding question)The hash map and the size-K heapEverything fits on one machine, and there is no window

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelCounts plays in a hash map and finds the top K with a size-K heap. Puts plays in a log rather than writing each to a database. Serves a precomputed chart from a cache.
SeniorKeys the counts by song before ranking, and shows why merging each machine’s shortlist can lose the winner. Keeps every window moving with minute counts and says why a live heap fails in a window. Counts by the time of the play.
StaffSplits a hot song across two stages. Moves long windows with running totals and stored minute rows. Checkpoints counts with offsets and keys every output so a replay is harmless. Prices a sketch’s error at the cutoff before offering one.
PrincipalChooses exact or approximate from the key count and what the numbers are used for, what the batch recount is trusted to overrule, and how many dimensions the product may add before the design changes shape.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.