Skip to content

Design Top-K / Trending (Top Videos, Leaderboards)

Advanced 87 min read Part 17 of 18

Return the K most-viewed videos for all time and for hour, day and month windows, at 700k views per second, fresh within a minute, served in milliseconds.

The Problem#

A top-K system answers one question over and over: "which K items are the most popular right now?" The items can be videos, songs, hashtags, search queries, products or players in a game. "Popular" usually means "counted the most times", for example the most views in the last hour. The answer is a short ranked list, maybe the top 10, the top 100 or the top 1,000.

You see top-K lists everywhere. YouTube and TikTok show trending videos. Spotify publishes charts of the most-streamed songs. X (formerly Twitter) shows trending topics. Amazon ranks best sellers in each category. An online game shows a leaderboard of the highest scores. Under the covers, each of these has the same shape: a huge stream of small events (a view, a play, a post, a purchase, a score) flows in, the system counts the events per item, and readers ask for the items with the biggest counts.

The question looks simple, because sorting a list is easy. It becomes hard at scale for four reasons:

  • The write rate is enormous. A platform with tens of billions of views a day receives hundreds of thousands of view events every second. Every one of them changes some item's count.
  • The item space is huge. There can be billions of videos. You cannot sort billions of counters on every request.
  • Time windows. "Top videos of all time" is one list. "Top videos in the last hour" is a different list that changes every minute, because old views must stop counting.
  • Readers want it instantly. The trending page is loaded millions of times a day. Each load must come back in tens of milliseconds, not the seconds it takes to scan data.

So the core skill in this design is to do the heavy counting and ranking work on the write side, ahead of time, so that the read side becomes a cheap lookup of a small, pre-built list.

Analogy. Think of a music chart such as a weekly top-40 radio countdown. Thousands of record shops and streaming services report their sales and plays. The chart office does not wait until someone asks "what is number one?" and then add up every sale in the country. Instead, it keeps running tallies all week, ranks the songs when the week closes, and publishes one small list. Listeners get the answer instantly because the work was done in advance. The chart office also does not need an exact count for every obscure song. It needs exact counts only for the songs near the top. A top-K system works the same way: count continuously, rank ahead of time, publish a small list, and spend precision only where it changes the answer.

Background: a few terms used in this design#

  • Top-K query: return the K items with the largest scores, in order. K is small (here at most 1,000) compared with the number of items (billions).
  • Heavy hitter: an item whose count is a large fraction of the total, for example any video that gets more than 0.01% of all views. Heavy hitters are the items that can appear in a top-K list. Most items are not heavy hitters.
  • Time window: the period over which counts are taken. A tumbling window has fixed, back-to-back boundaries (10:00-11:00, then 11:00-12:00). A sliding window always covers the most recent stretch of time (the last 60 minutes, measured from now).
  • Exact versus approximate counting: exact counting keeps one precise counter per item. Approximate counting uses a compact sketch, such as a count-min sketch, that uses far less memory and can be off by a bounded amount.
  • Precomputation: building the answer before anyone asks for it, so a read is just a lookup.
  • Stream processor: a system such as Apache Flink that consumes an endless stream of events, keeps state (such as counters), and emits results continuously. See Apache Flink and Stream Processing.
  • Sorted set: a data structure that keeps members ordered by a numeric score, so "top N" is fast. Redis sorted sets are the standard tool for live leaderboards.
  • Event time versus processing time: event time is when the view really happened on the user's device. Processing time is when our system handled it. They differ because of network delay, retries and buffering.

We will use "top videos by views", at the scale of a large video platform, as the main problem. That is the hardest common version. Along the way, and in the deep dives, we will show how the same design adapts to trending hashtags, top search queries, best-seller lists and real-time game leaderboards.

Clarifying Questions#

QuestionAssumed answerWhy it matters
What are we ranking, and by what?Videos, ranked by view countThe score is a simple count, so counting is the core problem. Trending by growth rate is a variant (Deep Dive 10)
How many views and videos?About 70 billion views per day, and roughly 1 million new videos per daySets the write rate (about 700k views per second at average) and the size of the item space
What windows do users need?All time, plus the last hour, last day and last monthEach window is a separate ranked list. Expiring old views is the hard part
Can users ask for arbitrary ranges, such as 3 March to 9 March?No. Only the fixed windows. Arbitrary ranges are out of scopeArbitrary ranges would force us to merge data at query time, which kills latency
Sliding or tumbling windows?Start with tumbling windows (the last complete hour, day or month). Discuss sliding as a refinementTumbling windows are much cheaper. Sliding windows need subtraction of old counts (Deep Dive 6)
How large is K?At most 1,000A list of 1,000 ids is tiny, so it can be precomputed and cached for every window
How fresh must the list be?A view should be reflected within 1 minuteRules out a nightly batch job. Pushes us toward stream processing
Must counts be exact?Exact at first. Approximation is acceptable only if we justify itExact counting is harder. Approximation is a deliberate later trade-off (Deep Dive 7)
How fast must reads be?Tens of milliseconds (p99 under 50 ms)Reads must hit a precomputed list in memory, never scan raw data
Are lists global, or per region or category?Global first. Per-country and per-category lists are extensionsEach extra dimension multiplies the number of lists to maintain
Must we filter fake or repeated views?Assume an upstream service already deduplicates and filters viewsKeeps the design focused on counting. We note where filtering fits
Does anyone need a push of live changes?Not for videos. A game leaderboard variant needs live rank updatesDecides whether we need a pull API only or also SSE or WebSockets (Deep Dive 11)

Requirements#

Functional#

  1. Clients can query the top K videos for all time, with K up to 1,000.
  2. Clients can query the top K videos for a tumbling window of 1 hour, 1 day or 1 month.
  3. Each result includes the video id and its view count, in descending order of views.

Out of scope: arbitrary time ranges and arbitrary start points, personalised ranking, spam and bot filtering (assumed upstream), the video metadata itself (titles and thumbnails are joined from another service), and recommendation.

Non-Functional#

  • Freshness: at most 1 minute between a view happening and that view being counted in the results.
  • Accuracy: results must be precise, not approximate, unless we explicitly choose approximation and explain the cost.
  • Read latency: return results in tens of milliseconds (p99 under 50 ms).
  • Write scale: sustain about 700k views per second on average, with peaks two to three times higher, without losing views.
  • Item scale: support billions of videos, most of them with very few views.
  • Availability: reads should be highly available (99.99%). If the counting pipeline stalls, readers should still get the last good list, slightly stale, rather than an error.
  • Durability: a view accepted into the pipeline must not be lost, and must not be counted twice.

What matters most. Read latency and freshness are what users notice. Accuracy is what the business and creators care about, because view counts and rankings are public and influence money (creator payouts and advertising). The defining constraint, though, is write scale. Reads are perhaps a few thousand per second (and almost all of them can be served from a cache), while writes are hundreds of thousands per second. This is a write-heavy aggregation problem, like the ad-click aggregator case, and the design follows Pattern: Scaling Writes: partition the work, batch it, and pre-aggregate before anything touches a database.

Capacity Estimation#

We size the problem with round numbers, the way you would on a whiteboard. See Back-of-the-Envelope Estimation for the method.

Write rate.

  • 70 billion views per day. A day has 86,400 seconds, which we round to 100,000 (10^5) to keep the arithmetic easy.
  • 70 × 10^9 / 10^5 = 700,000 views per second on average.
  • Traffic is not flat. Evenings in big regions and viral moments push peaks to roughly two to three times the average, so we plan for about 2 million views per second at peak.

This number decides the whole design. A single well-tuned PostgreSQL primary can sustain somewhere around 10,000 to 50,000 small write transactions per second, depending on hardware and how writes are batched. A single Redis node can do roughly 100,000 to a few hundred thousand simple operations per second. Neither can absorb 700,000 individual increments per second on its own, let alone 2 million. So we must either partition the counting across many machines, batch the increments so each write carries many views, or both.

Item space.

  • About 1 million new videos are uploaded per day (that is close to one hour of video every second, at an average length of a few minutes).
  • Over 10 years: 1 million × 365 × 10 ≈ 3.6 billion videos. We round to 4 billion for headroom.

Counter storage, all time.

  • One counter per video: an 8-byte video id plus an 8-byte count is 16 bytes.
  • 4 billion × 16 bytes = 64 GB of raw counter data.
  • With index overhead and row headers in a relational database, multiply by about 3 to 5, so roughly 200 to 300 GB. That is too big for the memory of one ordinary machine, but it fits easily across a handful of machines, or on the SSD of one large machine.

Per-window data.

  • If we store a row per video per minute, the volume depends on how many distinct videos get a view in each minute, not on the total number of videos. Most videos get no views in a given minute. Assume about 50 million distinct videos are viewed per hour, and perhaps 5 to 10 million per minute.
  • Per-minute rows: 10 million × 16 bytes ≈ 160 MB per minute, about 230 GB per day, and about 7 TB per month if every minute is kept for a month.
  • Per-hour rows: 50 million × 16 bytes ≈ 800 MB per hour, about 20 GB per day.

These numbers show why querying raw fine-grained data at read time is hopeless. To answer "top videos this month" by summing per-minute rows, the database would need to read terabytes for every request. The design must pre-aggregate.

Read rate.

  • Suppose the trending page and the API get 100 million requests per day. That is about 1,000 reads per second on average, maybe 10,000 at peak.
  • But there are only a handful of distinct questions: 4 windows times a few K values (10, 100, 1,000), and later perhaps a few hundred countries and categories. The number of distinct answers is in the hundreds or thousands, not millions. Every answer is tiny: 1,000 entries × 16 bytes = 16 KB.

So reads are easy if answers are precomputed and cached: the entire set of answers fits in a few tens of megabytes of memory.

Event stream.

  • A view event (video id, timestamp, a few context fields such as country and device) is about 100 to 200 bytes on the wire.
  • 700,000 × 150 bytes ≈ 105 MB per second, about 9 TB per day into the event log.
  • Kafka handles this comfortably with a few dozen brokers. One partition can sustain roughly 10 MB/s of writes in practice, so we need at least 10 to 20 partitions for throughput, and in practice we would use a few hundred so consumers can scale out.

Summary of the estimates.

QuantityEstimateConsequence
Views per second700k average, about 2M peakMust partition and batch writes
VideosAbout 4 billion over 10 yearsCannot sort all items per request
All-time counters64 GB raw, about 250 GB in a databaseFits on a few machines
Per-minute dataAbout 230 GB per dayToo large to scan at read time
Distinct answersHundreds to thousands, 16 KB eachPrecompute and cache everything
Reads per second1k average, 10k peakEasily served from memory
Event log volumeAbout 9 TB per dayKafka with retention of days to weeks

The ratio of writes to reads is about 700 to 1, and every read asks the same few questions. That is the opposite of most web systems, and it tells us where to spend effort.

Core Entities#

  • Video: the item being ranked. For this system we only need its id. Titles, thumbnails and creators come from the video metadata service.
  • View: one event that says "video V was viewed at time T". Views are immutable facts. We never update a view, we only count them.
  • Time window: the period a ranking covers: all time, or a specific hour, day or month. A window has a type and a start time, for example "hour starting 2026-12-03 10:00 UTC".
  • Count: the number of views of one video in one window. This is the state we maintain.
  • Top-K list: the ranked result for one window: up to 1,000 pairs of video id and count, plus the time it was computed.

The relationships are simple. A view belongs to one video and one moment in time. That moment falls into exactly one hour, one day and one month, and also counts toward all time. So each view increments four counters: one in each window that contains it.

API Design#

The read API is deliberately tiny.

GET /v1/views/top-k?window={ALL_TIME|HOUR|DAY|MONTH}&k={1..1000}&start={optional window start}

Response:

{
  "window": "HOUR",
  "windowStart": "2026-12-03T10:00:00Z",
  "windowEnd": "2026-12-03T11:00:00Z",
  "computedAt": "2026-12-03T11:00:41Z",
  "videos": [
    { "videoId": "v_8f3a91", "views": 18234011 },
    { "videoId": "v_02bb7c", "views": 15100342 }
  ]
}

Design notes on the API:

  • window is an enum, not a free-form range. That is what makes precomputation possible: there is a fixed set of answers.
  • start is optional. Without it, the API returns the most recent complete window (the last full hour, day or month). With it, the client can ask for a past window, such as "the hour that started at 10:00", which we can serve because old lists are cheap to keep.
  • k is capped at 1,000. Internally we always compute the top 1,000 and slice the first K. That way K=10 and K=100 are the same cached object, cut short.
  • computedAt tells the client how fresh the answer is. If the pipeline lags, clients can show "updated 3 minutes ago" instead of silently showing stale data.
  • Responses are cacheable. The answer for a past, closed window never changes, so it can carry a long Cache-Control max-age and be cached by a CDN. The answer for the current window changes about once a minute, so a short max-age of 30 to 60 seconds is right.

There is no public write API. Views arrive from the playback system as events on a Kafka topic. Internally, the playback service (or an upstream view-validation service) publishes:

ViewEvent { videoId, eventTime, viewId, country, device }

The viewId is a unique id for the view, which lets us drop duplicates if an event is delivered twice (see Idempotency and Safe Retries).

High-Level Design#

We build the design one requirement at a time. We start with a version that works at small scale, see where it breaks, and fix each break. This is also the best way to present the design in an interview.

1) Top K of all time, the simple version#

The simplest design that could work is a table of counters and an index.

  • The playback service publishes a ViewEvent to a Kafka topic. Using a durable log instead of calling a database directly means a slow or failed database does not lose views. The views wait in Kafka until a consumer catches up. See Apache Kafka in Practice.
  • A Counter Service consumes the topic and, for each view, runs UPDATE video_views SET views = views + 1 WHERE video_id = ?.
  • The table has a B-tree index on views (a sorted index, see Database Indexing). A top-K query is then SELECT video_id, views FROM video_views ORDER BY views DESC LIMIT 1000. The database walks the index from the largest end and stops after 1,000 entries, so the query is effectively O(K), not O(N). It never sorts the whole table.
  • A Query Service handles GET /views/top-k and runs that query.

The read path here is already decent: an index walk for 1,000 rows takes a few milliseconds. The write path is the problem. Every increment updates the row and moves an entry in the views index, because the indexed value changed. Each index update costs O(log N), with N in the billions, plus random I/O and write-ahead-log traffic. At 700,000 increments per second, one database is hopeless. Worse, popular videos make the problem concentrated: a viral video receiving 50,000 views per second turns its single row into a lock hotspot, because every increment to that row has to wait for the previous one to commit.

Even so, this version is the right place to start. It is correct, it is simple, and it shows the interviewer that you know an index makes "top K" cheap to read. The rest of the design keeps the read idea and fixes the writes.

2) Adding time windows#

Now we need the top videos of the last hour, day and month. The natural first step is to keep a row per video per hour: video_hourly_views(video_id, hour, views). Each view increments the row for its hour. A query for the top videos of the last day becomes:

SELECT video_id, SUM(views) AS total
FROM video_hourly_views
WHERE hour >= now() - interval '1 day'
GROUP BY video_id
ORDER BY total DESC
LIMIT 1000;

This is correct, but slow. The WHERE clause selects 24 hours of rows, about 50 million distinct videos per hour, so up to a billion rows. The database must read them all, group them by video and sort the groups. That takes seconds to minutes, not tens of milliseconds. For a month it is hundreds of gigabytes per query. No index helps, because the ranking value (the sum) does not exist until the query computes it.

There is also a subtle point about what "the last hour" means:

  • A sliding window is the interval [T - 1 hour, T], where T is the exact current time. It changes every second.
  • A tumbling window is the last complete clock hour, [floor(T) - 1 hour, floor(T)], such as 10:00 to 11:00 when it is now 11:23. It changes once an hour.

Tumbling windows are far easier, because each view belongs to exactly one hour and the hour's total never changes after it closes (apart from late events). We propose tumbling windows to the interviewer and keep sliding windows as a refinement for Deep Dive 6.

3) Precompute the answers and serve them from a cache#

The key observation from the capacity estimates is that there are only a few hundred distinct answers, each about 16 KB. So there is no reason to compute an answer when a reader asks for it. Compute each answer once, when the underlying data changes, and store it.

  • A Top-K Builder recomputes the top 1,000 for each window on a schedule (every minute for the current hour and day, every few minutes for the month) and writes the result to a cache such as Redis, under keys like topk:HOUR:2026-12-03T10 and topk:ALL_TIME.
  • The Query Service reads only from the cache. A read is a single key lookup of 16 KB: well under a millisecond inside the data centre, and a few milliseconds end to end.

We could instead cache lazily: on a cache miss, run the slow query and store the result with a time-to-live (TTL). That fails in two ways. When a popular key expires, many readers miss at the same moment and all run the expensive query together, a cache stampede (see Cache Failure Modes: Stampedes, Hot Keys and Penetration). And whoever is unlucky enough to miss waits seconds for the slow query, which breaks the latency requirement. Request coalescing fixes the stampede but not the slow miss. Proactive precomputation fixes both: readers never trigger computation, so read latency is always a cache hit.

Two operational details matter:

  • Keep old entries for a while. If the builder for 11:00 runs late, readers should still see the 10:00 list rather than a miss. Give entries a TTL of a couple of window lengths, and have the Query Service fall back to the newest available window.
  • Monitor the builder. If the builder dies, the lists silently go stale. Alert when computedAt falls more than a few minutes behind.

This fixes reads completely. But the builder still has to rank fresh data every minute, which means summing huge tables, and the Counter Service still has to absorb 700,000 writes per second. The full design moves both pieces of work into a stream processor.

The full high-level design#

The production design pushes counting and ranking into the stream. A stream processor (Apache Flink in our examples) reads the view events, keeps per-window counts in its own state, maintains the top 1,000 for each window incrementally, and publishes small ranked lists. The database is no longer on the hot path. It stores history and serves as a reference copy.

Components:

  • Playback service and view validation: emit one ViewEvent per qualifying view (for example, a view counts after a few seconds of playback). An upstream validation stage drops duplicate view ids and obvious bots. We treat that stage as given, but its position matters: it must run before counting, because a count cannot be "un-incremented" cheaply once it is spread across windows.
  • Kafka view-events topic: partitioned by videoId, with a few hundred partitions and several days of retention. Partitioning by video means all views of one video go to the same partition, so one consumer owns that video's count and no two machines fight over it. Retention lets us replay the stream after a bug or an outage.
  • Pre-aggregation: the first Flink operator collapses raw events into (videoId, minute, count) before anything else happens. A viral video's 50,000 views per second become one record per minute per partition. This is the single biggest write reduction in the design.
  • Window counters: keyed by videoId, they keep the count for the current hour, day and month, and the all-time total. State lives in RocksDB inside Flink, checkpointed to object storage.
  • Local top 1,000: each parallel instance of the job keeps a small ranked structure (a min-heap or sorted map of 1,000 entries) per window, for the videos it owns.
  • Global merge: a single low-volume operator merges the local lists into the global top 1,000 per window, and publishes the result. Because each video is owned by exactly one partition, the merge is exact (Deep Dive 3).
  • Redis: stores the published lists, one key per window, as a sorted set or a serialised blob. It holds only a few megabytes in total.
  • Query Service: stateless, reads from Redis, slices to K, joins titles and thumbnails if needed, and sets cache headers.
  • CDN: caches responses for 30 to 60 seconds. With a CDN in front, most reads never reach our servers at all.
  • Object storage and batch recount: a copy of every raw event goes to object storage (via a Kafka sink). A daily batch job recounts closed windows from the raw events and corrects the counts store if the stream produced drift. This is the same "fast path plus correct path" idea used in the ad-click aggregator case.
  • Counts store: keeps historical per-window counts (for past windows, creator analytics and audits). It is off the read path for the top-K API.

Key Flows#

Flow 1: a view is counted and reaches the ranked list#

  1. The playback service publishes a view event with its event time. Kafka routes it to a partition by hashing the video id, so every view of v1 lands on the same partition.
  2. The pre-aggregation operator for that partition receives it.
  3. It adds 1 to an in-memory counter for (v1, minute 10:15). Nothing is written anywhere yet.
  4. When the watermark passes the end of 10:15 (that is, the job believes no more events for that minute are coming), the operator emits one record with the minute's total.
  5. The window-counter operator adds the minute total to v1's counters for the current hour, day, month and all time. This state lives in RocksDB on the same machine.
  6. If v1's new hourly count is larger than the smallest entry in the local top-1,000 for that hour, v1 enters (or moves within) the local list.
  7. Every 30 seconds, each partition sends the entries of its local list that changed since the last send. This is a few hundred small records per partition, so the merge operator receives tens of thousands of records per interval, not millions.
  8. The global merge operator keeps the union of all partitions' candidate lists and selects the top 1,000 per window.
  9. It writes the new lists to Redis. The total delay from view to list is roughly the minute bucket (up to 60 seconds) plus the publish interval (30 seconds) plus processing, so about 1 to 1.5 minutes in the worst case. To meet the 1-minute freshness goal strictly, we shrink the pre-aggregation bucket to 10 to 20 seconds and publish every 10 to 15 seconds.

Flow 2: a client reads the top K#

  1. The client asks for the 50 top videos of the current hour.
  2. The CDN has no fresh copy, so it forwards the request. For the trending page, the CDN hit rate is very high because every user asks the same question.
  3. The Query Service reads the precomputed list for the latest hour from Redis. This takes well under a millisecond inside the data centre.
  4. Redis returns the full list of 1,000 entries and the time it was computed.
  5. The service slices the first 50. Computing all 1,000 and slicing means every K shares one cached object.
  6. It fetches display data for those 50 videos from the metadata service in one batch call (which has its own cache).
  7. The metadata service returns titles and thumbnails.
  8. The service responds with a short max-age, matched to how often the list is rebuilt.
  9. The CDN serves this response to every client who asks in the next 30 seconds.

Flow 3: an hour closes and late views arrive#

  1. The watermark is Flink's estimate of how far event time has progressed. When it passes 11:00 plus the allowed lateness (say 2 minutes), the job treats 10:00 to 11:00 as complete.
  2. The counters for hour 10 are frozen.
  3. The final local lists for that hour go to the merge operator.
  4. The merged list is written to Redis with a flag that says the window is final. Clients and caches can now treat it as immutable.
  5. The final counts are also written to the counts store for history.
  6. A view for 10:58 that arrives at 11:20 (for example, from a phone that was offline) is too late for the stream.
  7. Instead of being dropped, it goes to a side output, a separate stream for late data, and is applied by the batch recount job. The published list for hour 10 might then be corrected once, the next day. In practice the correction almost never changes the top 1,000, because one late view cannot move a video that has thousands of views.

Data Model#

The stream processor holds the hot state. The databases hold history and the published results. The entity diagram below is the logical model behind both.

The relational form of the history tables, if we keep them in PostgreSQL (or a distributed SQL store), looks like this:

-- All-time counters, one row per video
CREATE TABLE video_views (
  video_id   BIGINT PRIMARY KEY,
  views      BIGINT NOT NULL DEFAULT 0,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX video_views_by_views ON video_views (views DESC);
 
-- One table per window type keeps each index small and hot
CREATE TABLE video_views_hour (
  hour_start TIMESTAMPTZ NOT NULL,
  video_id   BIGINT NOT NULL,
  views      BIGINT NOT NULL,
  PRIMARY KEY (hour_start, video_id)
) PARTITION BY RANGE (hour_start);
CREATE INDEX ON video_views_hour (hour_start, views DESC);
 
-- Published lists: the source of truth for past windows
CREATE TABLE topk_list (
  window_id   TEXT PRIMARY KEY,   -- e.g. 'HOUR:2026-12-03T10'
  computed_at TIMESTAMPTZ NOT NULL,
  is_final    BOOLEAN NOT NULL,
  entries     JSONB NOT NULL      -- [{videoId, views}, ...] up to 1000
);

Design notes.

  • The composite index (hour_start, views DESC) turns "top 1,000 for hour H" into an index range scan that stops after 1,000 entries. This is the same trick as the all-time index, applied inside one window.
  • Range partitioning by hour_start lets us drop old hours as whole partitions, which is far cheaper than deleting billions of rows. Day and month tables follow the same pattern. See Data Lifecycle, Tiering and Retention.
  • Published lists are stored whole, as a single JSON blob per window. Nobody queries inside a list. Storing it as one value makes reads one lookup, and the blob for a closed window never changes.
  • Minute-level counts are optional. We only need them for sliding windows (Deep Dive 6) or for reprocessing. If we keep them, they belong in a columnar store or object storage, not in the transactional database, because there are billions of rows per day.

Database choice. The hot path does not use a database at all. Flink state (RocksDB, checkpointed to object storage) holds the live counters. For the history tables, PostgreSQL works up to a few terabytes with partitioning. A columnar OLAP store such as ClickHouse is a better fit when analysts want to slice counts by country, device and time over years, because it compresses counts heavily and scans billions of rows per second. Redis holds the published lists because reads must be sub-millisecond and the data is tiny. For a fuller decision procedure, see Choosing a Database: A Decision Guide.

StoreWhat it holdsWhy this store
KafkaRaw view events, 3 to 7 daysDurable buffer, replay after bugs, partitioning by video
Flink state (RocksDB)Live per-window counters and local top listsCo-located with the computation, exactly-once via checkpoints
RedisPublished top-K lists per windowSub-millisecond reads of tiny values
PostgreSQL or ClickHouseHistorical per-window counts, all-time countsDurable history, analytics, audits
Object storageRaw events forever (or per policy) and Flink checkpointsCheapest durable storage, source for batch recounts

Deep Dives#

1. How do we absorb 700,000 views per second?#

The simple design sends one database write per view. We need to cut the number of writes, spread the remaining writes across machines, or, in practice, both. There are three tools, and a good answer uses them in this order.

Tool 1: partition by video id (sharding). If one database can take about 10,000 increments per second, then 700,000 per second needs about 70 shards, and the 2-million-per-second peak needs about 200. We route each view to a shard by hashing the video id, so every count for one video lives on one shard (see Partitioning and Sharding). The query side then asks every shard for its local top 1,000 and merges them. Because each video lives on exactly one shard, the merge is exact: the global top 1,000 must be among the union of the local top 1,000s (Deep Dive 3 proves this and shows when it stops being true).

Sharding alone is expensive and fragile. Seventy database clusters is a lot of operational weight for a feature, and hashing does not protect against a single viral video: all 50,000 of its views per second still go to one row on one shard.

Tool 2: batch, by pre-aggregating in the stream. Most of those 700,000 writes per second are to the same few hundred thousand popular videos. If a consumer collects views in memory for a short interval and writes one views = views + n per video per interval, the number of writes drops sharply. How much it drops depends on the distribution of views:

  • For a viral video with 50,000 views per second and a 10-second batch, 500,000 increments become 1 write.
  • For a video with one view per hour, batching saves nothing: one view is still one write.
  • Across a realistic long-tailed (Zipf-like) distribution, where a small fraction of videos get most of the views, the reduction for one-minute batches is typically somewhere between 2 times and 100 times, depending on how heavy the head is.

After batching, the database might see 10,000 to 100,000 writes per second, which needs perhaps 5 to 10 shards rather than 70. The cost is freshness: a view is visible only after its batch is flushed, so the batch interval must be well inside the 1-minute freshness budget.

A stream processor such as Flink is the natural place to batch, because it already handles the hard parts: partitioned state, checkpointing (so a crash does not lose or double-count an in-memory batch), and event-time windows. We configure a watermark with bounded out-of-orderness, for example 30 seconds, which tells Flink "events can arrive up to 30 seconds out of order, so wait that long before closing a window". Then a 1-minute tumbling window keyed by video id emits one count per video per minute. If the job crashes, it restarts from the last checkpoint and rewinds Kafka to the offsets saved in that checkpoint, so every view is counted exactly once in the state (see Delivery Guarantees: At-Most, At-Least and Exactly-Once).

Tool 3: make the counter cheap. Even after batching, every write to an indexed views column moves an index entry. Two refinements help:

  • Do not index the hot table. Keep counters in an un-indexed (or key-only indexed) table and let the stream processor, not the database index, maintain the ranking. The database becomes a write-only history store.
  • Use a store built for increments. Redis INCRBY and Cassandra counters are designed for this. In Redis, a sorted set even gives the ranking for free (ZINCRBY), which is exactly the leaderboard design in Deep Dive 11. For billions of items, though, keeping everything in Redis memory becomes the bottleneck, which is why the stream processor keeps the long tail on disk-backed RocksDB state.

The hot-key problem, quantified. Partitioning by video id means a viral video's events all land on one Kafka partition and one Flink task. Is that a problem? One Flink task can count simple events at a few hundred thousand to a million per second, because counting is a hash-map increment. A single video receiving 50,000 views per second is therefore fine for the counting task. The bottleneck is more likely the Kafka partition: if one video's events are 10% of all traffic, that partition receives 70,000 events per second while the average partition receives a few thousand. Two fixes, both covered in the ad-click aggregator case:

  • Pre-aggregate before the shuffle. The playback service, or an edge collector, can count views locally for a second or two and send (videoId, count) instead of individual events. This is a combiner, the same idea as in MapReduce.
  • Salt hot keys. Append a random suffix (0 to 9) to the key for known-hot videos, so their events spread across 10 partitions, then sum the 10 partial counts in a second stage. This breaks the "each video on one shard" property for those videos, which matters for the merge. Deep Dive 3 explains how to keep the merge exact anyway.

What to say in an interview. "700k writes per second means we cannot write per view. I will partition by video id so each video has one owner, and pre-aggregate in Flink over short windows so the hot head of the distribution collapses into a few writes. That cuts the write rate by one to two orders of magnitude. Then I keep the ranking in the stream rather than in a database index, so the database is not on the hot path at all."

2. How do we make reads fast and keep them fast?#

Reads are the easy half, but only if we resist computing anything at read time. The options, from weakest to strongest:

Bad: query on read. Run the SUM ... GROUP BY ... ORDER BY ... LIMIT query on each request. As shown in the high-level design, this scans hundreds of gigabytes for a month window. It fails the latency requirement by three to four orders of magnitude.

Good: cache with a TTL. Cache each answer under topk:{window}:{windowStart} with a TTL of one minute. Most requests hit the cache. This has two problems:

  • When the key expires, the next request pays the full query cost, seconds or minutes. That request breaks the latency SLA.
  • If many requests arrive just after expiry, they all miss and all run the expensive query. This is a cache stampede. Request coalescing (also called single-flight: only the first miss computes, and the others wait for its result) prevents the duplicate work, but everyone still waits.

Great: precompute and push into the cache. A scheduled builder (or, in the full design, the stream processor itself) computes each answer before it is needed and writes it into the cache. Readers only ever read. There is no miss path, so there is no stampede and no slow request.

  • For closed windows, compute once when the window closes, write the final list, and never touch it again. Past hours, days and months are immutable.
  • For the current window, refresh on a fixed interval (every 10 to 60 seconds). The list on display is at most one interval old.
  • Keep the previous version available. Write each version under a new key (topk:HOUR:10:v123) and then atomically switch a pointer key (topk:HOUR:latest → v123), or simply overwrite the single key in one SET. A reader always sees a complete list, never a half-written one.
  • Keep entries for a couple of window lengths, so a late builder does not leave readers with nothing. The Query Service falls back to the newest list available and reports its computedAt.
  • Alert on staleness. The biggest risk of precomputation is silence: a dead builder produces no errors, just old data. Emit a metric for "age of the newest list per window" and page when it exceeds a few minutes.

Layering the caches. With precomputation, the cache holds a few megabytes in total, so we can afford to replicate it everywhere:

  • Redis holds the source copy, replicated to each region.
  • Query Service instances keep an in-process copy of each list for a few seconds. At 10,000 reads per second spread across 20 instances, each instance serves 500 per second from its own memory.
  • The CDN caches the HTTP response for 30 to 60 seconds. For a global trending page, the CDN absorbs nearly all traffic.

This is a direct application of Pattern: Scaling Reads: when the set of distinct answers is small and they change slowly relative to how often they are read, compute them on write and replicate them close to readers.

Why the read path stays fast as features grow. Adding a dimension, such as per-country lists, multiplies the number of precomputed lists (200 countries × 4 windows = 800 lists, 13 MB) but does not change the read cost: a read is still one key. What changes is the write side, which must maintain 800 rankings instead of 4. That is the right place for the cost, because the write side is a controlled batch pipeline, while the read side faces users.

3. Sharded counting: when is merging local top-K lists correct?#

Once counting is spread over many shards (database shards, Flink tasks, regions), the global answer must be assembled from pieces. The obvious approach is: each shard computes its own top 1,000, and a coordinator merges those lists and keeps the best 1,000. Whether that is correct depends entirely on how the counts were split.

Case 1: partitioned by item. The merge is exact. If every view of a video goes to the same shard, each shard holds the complete count for the videos it owns. Then:

Claim: if video v is in the global top K, then v is in the local top K of the shard that owns it.

Why: every video ranked above v on that shard has a larger complete count than v, so it also ranks above v globally. If there were K or more such videos on v's shard, there would be K or more videos above v globally, and v would not be in the global top K. So fewer than K videos on its shard outrank v, which means v is in that shard's local top K.

So the union of the local top-K lists contains every member of the global top K, and the coordinator only needs to sort shards × K entries. With 64 shards and K = 1,000, that is 64,000 entries, a millisecond of work. This is why we partition the Kafka topic and the Flink job by video id: ownership makes the merge trivially exact.

Case 2: counts for one item are split across shards. The naive merge is wrong. Counts get split when we salt hot keys, when each region counts its own traffic, when each Kafka partition is counted independently without a re-key step, or when different time buckets are counted separately and then combined. In all of these, a video's total is the sum of partial counts held in different places. A small example with K = 1 shows the failure:

VideoShard AShard BTrue total
x1000100
y9090180
z0100100

Shard A's top 1 is x (100). Shard B's top 1 is z (100). The merged answer is x or z with 100 views. The true answer is y with 180, which appears in neither local list. A video that is consistently second everywhere can be first overall. The same failure appears at real scale: a video that is moderately popular in every country can beat a video that is huge in one country, and per-country top lists will miss it.

There are three ways to handle split counts.

Fix A: re-key before ranking (the standard answer). Do not rank partial counts. Send each partial count, keyed by video id, to a second stage that owns that video, sum there, and rank the complete totals. In Flink this is one extra keyBy(videoId) after the salted or regional pre-aggregation. It costs a network shuffle of partial counts, but partial counts are already pre-aggregated and small. This turns Case 2 back into Case 1. For per-region counting, it means regions ship counts, not lists, to the global stage.

Fix B: send more than K from each shard. Each shard sends its top c × K (say 3 × K) instead of K. This makes errors less likely but gives no guarantee: the adversarial example above fails for any c if enough videos sit just below the cut on every shard. It is a reasonable engineering compromise only when Fix A is too expensive and small errors are acceptable.

Fix C: a threshold algorithm with a proof of correctness. When partial counts must stay where they are (for example, they are in separate databases and shipping all of them is too expensive), a distributed top-K protocol can find the exact answer while exchanging far less data. The best-known is the Three-Phase Uniform Threshold (TPUT) algorithm from Pei Cao and Zhe Wang's "Efficient Top-K Query Calculation in Distributed Networks" (PODC 2004). With m shards:

  1. Phase 1. Each shard sends its local top K with their partial counts. The coordinator sums what it received per item and takes the K-th largest partial sum, τ1. Since partial sums are lower bounds of true totals, the true K-th largest total is at least τ1.
  2. Phase 2. The coordinator asks each shard for every item whose local count is at least τ1 / m. By the pigeonhole principle, any item whose total is at least τ1 must have at least one shard where its count is at least τ1 / m, so no candidate can be missed. The coordinator recomputes partial sums, takes the new K-th largest, τ2, and computes an upper bound for each item: its known partial sum plus τ1 / m for each shard that did not report it. Any item whose upper bound is below τ2 is pruned.
  3. Phase 3. For the remaining candidates, the coordinator fetches exact counts from every shard and picks the true top K.

A worked example with two shards (m = 2) and K = 2:

VideoShard EUShard USTrue total
a501060
b40242
c304575
d54247
e201535
  • Phase 1: EU sends a (50), b (40). US sends c (45), d (42). Partial sums: a 50, c 45, d 42, b 40. τ1 = 45, so the threshold is 45 / 2 = 22.5.
  • Phase 2: EU sends everything at or above 22.5: a 50, b 40, c 30. US sends c 45, d 42. Now c = 75 is exact, a ≥ 50, d ≥ 42, b ≥ 40, so τ2 = 50. Video e was reported by neither shard, so its count on each is below 22.5 and its total is below 45, which is less than τ2. It is ruled out without ever being sent.
  • Upper bounds: a ≤ 50 + 22.5 = 72.5, d ≤ 42 + 22.5 = 64.5, b ≤ 40 + 22.5 = 62.5. All are at least τ2, so all stay.
  • Phase 3: fetch exact counts for a, b and d: 60, 42, 47. The top 2 are c (75) and a (60), which is correct.

In this tiny example the pruning saves little, but on real data with millions of items per shard, Phase 2 typically ships a small multiple of K items per shard rather than millions. The related Threshold Algorithm of Ronald Fagin, Amnon Lotem and Moni Naor, "Optimal Aggregation Algorithms for Middleware" (PODS 2001), solves the same problem when each source can be read in sorted order and probed for any item's score, and is the classic reference for "top-K over several ranked lists".

The takeaway for an interview. Say explicitly: "Because I partition by video id, each video's count is complete on one shard, so merging local top-K lists is exact. If I ever split a video's count, for hot-key salting or per-region counting, I re-key the partial counts by video before ranking, otherwise the merge can miss the true winner." That one sentence shows you understand the most common correctness trap in this problem.

4. How do we answer window queries without scanning?#

The high-level design showed that summing hourly rows at query time is too slow. Precomputation moves the summing to the write side, but the builder still has to compute the rankings somehow. There is a ladder of options.

Good: coarser granularity. Instead of summing 720 hourly rows to answer a month query, keep daily rows too. A month is then about 30 rows per video instead of 720, a 24-times reduction, and an hour query reads only the hourly table. A cron job rolls hourly rows into daily rows after each day closes, and daily rows into monthly rows after each month closes. The weakness is chained delay: the day table is only complete after the last hourly job of the day, and the monthly ranking is only as fresh as the daily rollup. It also still requires GROUP BY and a sort over tens of millions of videos for the day and month queries, which takes seconds even on a strong machine. This is acceptable for a builder that runs every few minutes, but not for freshness under a minute.

Great: maintain one table per window, with a ranking index. Keep a separate counter table for each window, video_views_all_time, video_views_last_hour, video_views_last_day and video_views_last_month, each with an index on views DESC. Every incoming (pre-aggregated) count increments four rows, one in each table. A top-K query is then an index walk of 1,000 rows in the right table, which takes milliseconds, so the builder can run every few seconds. Two costs:

  • Writes go to four tables, each with an index update. After stream pre-aggregation this is manageable, but it is four times the write load.
  • Windows must be rotated. For tumbling windows, create the next hour's table (or partition) before the hour starts and switch writes at the boundary. The previous hour's table is now final and its top 1,000 can be extracted once.

Since every count in these tables can be rebuilt from Kafka or object storage, we can trade durability for speed. In PostgreSQL that means:

  • Unlogged tables (CREATE UNLOGGED TABLE) skip the write-ahead log, which can more than double write throughput. They are emptied after a crash, so they must be rebuilt by replay. See PostgreSQL in Practice.
  • Asynchronous commit (synchronous_commit = off) lets a commit return before the WAL is flushed to disk, which removes an fsync from every transaction at the risk of losing the last fraction of a second of writes on a crash.
  • Large batches. Applying thousands of increments in one statement (a multi-row INSERT ... ON CONFLICT DO UPDATE, or COPY into a staging table followed by one UPDATE ... FROM) amortises transaction overhead. Sorting each batch by video id also reduces deadlocks between concurrent batches and makes index updates more sequential.
-- Apply one pre-aggregated minute of counts to the hourly window table
INSERT INTO video_views_hour (hour_start, video_id, views)
SELECT date_trunc('hour', minute), video_id, views
FROM staging_minute_counts
ORDER BY video_id
ON CONFLICT (hour_start, video_id)
DO UPDATE SET views = video_views_hour.views + EXCLUDED.views;

Great, with caveats: keep the windows in the stream processor. The most elegant version removes the database from the ranking path. Flink holds, for each video, its running counts per window in keyed state, and a ranking operator keeps the top 1,000 per window:

  • A rolling window aggregator, keyed by video id, adds each minute's count to the video's hour, day, month and all-time counters, and emits the video's new counts.
  • A top-K aggregator keeps a bounded ranked structure (a heap or sorted map) per window and updates it with each emitted count. It runs first per partition, then once globally, as in Deep Dive 3.
  • A sink writes each updated list to Redis, for example as a sorted set per window.

This design has the lowest latency and the fewest moving parts at run time, and Flink's checkpoints give exactly-once state without any database. The caveat is that it demands real expertise in the stream processor: state size per video (billions of keys in RocksDB), timers for window rotation, checkpoint size and duration, rescaling the job without losing state, and handling of late events. An interviewer who knows Flink will probe these. If you do not know them well, the per-window tables design is safer to present, and it is a perfectly good answer.

5. Which data structure keeps the top K up to date?#

Every time a video's count changes, the ranking operator must decide whether the top 1,000 changes. The data structure choice depends on one question: can counts go down?

When counts only go up (all-time and tumbling windows), the standard structure is a min-heap of size K plus a hash map from video id to its heap position:

  • The heap's root is the smallest count currently in the top K. Call it the threshold.
  • When video v's count rises to c:
    • If v is already in the heap, update its entry and restore heap order, O(log K).
    • If v is not in the heap and c is greater than the threshold, remove the root and insert v, O(log K).
    • Otherwise, do nothing, O(1).

With K = 1,000, log K is about 10, so even the slow path is a handful of comparisons. More importantly, the fast path is the common path. In a long-tailed distribution, almost every update is for a video far below the threshold, so it is discarded after a single comparison.

Is this exact? Yes, because the heap is only an index over complete state. The window-counter operator keeps every video's full count in keyed state, and it sends every new count to the ranking operator. A video that drops out of the heap and later grows will be seen again with its new full count and re-enter. Nothing is lost by evicting it, because its count was never stored only in the heap.

A balanced ordered map (a red-black tree or skip list keyed by (count, videoId)) works equally well and makes it easy to read the list in order. Java's TreeMap or a TreeSet of pairs is a common choice inside Flink operators. Tie-breaking matters: two videos with the same count must sort in a fixed order (by video id, for example), otherwise the published list can flicker between equivalent orders on each refresh.

// Bounded top-K for counts that only increase. Ordered by (count, id).
// SortedSet stands for any ordered set (skip list, B-tree, red-black tree).
class TopK {
  private byId = new Map<string, number>();          // id -> count in set
  private ordered = new SortedSet<[number, string]>(); // ascending (count, id)
  constructor(private k: number) {}
 
  offer(id: string, count: number): void {
    const old = this.byId.get(id);
    if (old !== undefined) {                 // already a member: re-position
      this.ordered.delete([old, id]);
      this.ordered.add([count, id]);
      this.byId.set(id, count);
      return;
    }
    if (this.byId.size < this.k) {           // not full yet
      this.ordered.add([count, id]);
      this.byId.set(id, count);
      return;
    }
    const [minCount, minId] = this.ordered.first();
    if (count <= minCount) return;           // fast path: below threshold
    this.ordered.delete([minCount, minId]);  // evict the smallest
    this.byId.delete(minId);
    this.ordered.add([count, id]);
    this.byId.set(id, count);
  }
 
  top(): Array<[string, number]> {           // descending order
    return [...this.ordered.descending()].map(([c, id]) => [id, c]);
  }
}

When counts can go down (sliding windows, or corrections), a bounded heap is no longer enough. Suppose a video in the top 1,000 loses views as old minutes expire and falls below the threshold. Who is now number 1,000? The answer is some video outside the heap, and the heap has no record of the outsiders. There are three practical answers:

  • Keep a margin. Track the top K + M (say 1,000 + 500). Decreases rarely push more than M videos out between refreshes, so the true top 1,000 is almost always inside the larger set. When the set drops below K members whose counts are known to be correct, rebuild from full state. This is cheap and works well in practice, but it is a heuristic.
  • Keep a full ordered index per window. A skip list or B-tree over every video with a non-zero count in the window supports increments and decrements in O(log N) and gives the exact top K at any moment. This is exactly what a Redis sorted set is. It costs memory proportional to the number of active videos, about 50 million for an hour, which is roughly 5 GB in a sorted set (the per-entry overhead is around 100 bytes). That fits for an hour window, but is too much for a month.
  • Rebuild periodically. Decrements in a sliding window happen in bulk, once per slide (for example, once per minute). Instead of maintaining a perfect order, recompute the top K from the state once per slide using a selection algorithm (quickselect finds the top K of N items in O(N) average time). Scanning 50 million counters once a minute is a few seconds of CPU spread across the cluster, which is affordable.

A useful shortcut: the lower-bound filter. Wherever counts are kept, the ranking stage only needs to see videos that could enter the top K. Publish the current threshold (the K-th count) back to the counting stage. A counting task then forwards an update only when the video's new count exceeds the threshold. Since the threshold only rises within a tumbling window, this filter is safe, and it removes more than 99% of the traffic to the ranking stage for a typical long-tailed distribution.

6. What about sliding windows?#

The requirements accepted tumbling windows, but many products really want "the last 60 minutes, as of now". With tumbling windows, at 11:05 the "last hour" list shows 10:00 to 11:00, which is already 5 minutes stale and misses a video that went viral at 11:01. A sliding window fixes that, at a price.

The core technique: add the newest bucket, subtract the oldest. Divide time into small buckets (1 minute). For each video, keep the count per bucket. Then:

hour_count(v, now) = hour_count(v, now - 1 min)
                   + minute_count(v, newest minute)
                   - minute_count(v, minute that just left the window, 60 minutes ago)

Every minute, each video's sliding count changes by two bucket values, instead of being recomputed from 60 buckets. The window "slides" one bucket at a time. The resolution of the window is one bucket, so the list is accurate to within a minute.

The cost is storage of the old buckets. To subtract the minute that left the window, we must still have it.

  • For a sliding hour, we keep 60 minute buckets per active video: 60 × 10 million active videos per minute × 16 bytes is roughly 10 GB, which is fine.
  • For a sliding month, we would keep 43,200 minute buckets: about 7 TB, as estimated earlier. That is a lot of state just to subtract.

The mature compromise. Use different resolutions for different windows. A sliding hour with minute buckets. A sliding day with hourly buckets (so the day window is accurate to within an hour, which nobody notices). A month with daily buckets. Or simply keep sliding windows for the hour and tumbling windows for the day and month. Product managers rarely care whether the monthly list is a sliding 30 days or the last calendar month, but they always care that the hourly list feels live.

Alternative: a lagged consumer. Instead of storing old buckets, read the event stream twice. One Kafka consumer group reads at the head and increments. A second consumer group reads the same topic exactly one window behind (60 minutes behind for the hour) and decrements for every event it sees. The difference of the two is the sliding count. This needs no bucket storage, but it needs Kafka retention of at least the window length (a month for a sliding month, about 270 TB at 9 TB per day), and the two consumers must stay precisely one window apart, which is fiddly after outages. It works well for short windows.

Why not use the stream processor's built-in sliding windows? Flink has sliding windows with a size and a slide. But a sliding window of size 1 hour and slide 1 minute assigns each event to 60 overlapping windows, and keeps separate state for each. For a month with a 1-minute slide, each event belongs to 43,200 windows, so state is multiplied by 43,200. That is unworkable. The bucket-subtraction design above is the standard way to get the same result cheaply.

Alternative: exponential decay instead of a hard window. Trending lists often do not need a sharp window at all. Instead, give each view a weight that decays over time: a view one hour ago counts half as much as a view now. The score of a video is then the sum of decayed weights. Updating every video's score every second would be expensive, but there is a neat trick known as forward decay (described by Graham Cormode, Vladislav Shkapenyuk, Divesh Srivastava and Bojian Xu in "Forward Decay: A Practical Time Decay Model for Streaming Systems", ICDE 2009). Instead of shrinking old weights, give each new view a weight that grows with time, w = e^(λ·t), where t is the view's time. Old scores never need updating, because all scores are measured on the same growing scale, and relative order is the same as with true decay. Counts only increase, so the simple min-heap from Deep Dive 5 works again. The only maintenance is to rescale all scores occasionally (dividing by a common factor) so the numbers do not overflow. Decay gives a smooth "hotness" ranking without any bucket storage, which is why decayed scores are common in feeds and trending systems.

7. When should we approximate, and how does a count-min sketch work?#

So far every design keeps an exact counter for every video in every window. That is billions of counters. The requirement said "precise", so the exact design is the baseline. But an interviewer will often ask: "What if memory is the constraint, or you need thousands of lists (per country, per category, per hour)? Can you use less state?" The answer is approximate counting, and the standard tool is the count-min sketch (Graham Cormode and S. Muthukrishnan, "An Improved Data Stream Summary: The Count-Min Sketch and its Applications", Journal of Algorithms, 2005). See Probabilistic Data Structures for Big Data for the full family.

How it works. A count-min sketch is a small two-dimensional array of counters with d rows and w columns, and d independent hash functions, one per row.

  • Add(item, n): for each row i, compute column h_i(item) mod w and add n to that counter. That is d increments.
  • Estimate(item): for each row i, read the counter at h_i(item) mod w, and return the minimum of the d values.

Each counter holds the true count of our item plus the counts of every other item that happened to hash into the same column in that row. So every row over-estimates (never under-estimates), and taking the minimum picks the row with the least collision noise.

The guarantee. Let N be the total of all counts added (total views in the window). With width w = ⌈e / ε⌉ and depth d = ⌈ln(1/δ)⌉, the estimate for any item satisfies:

  • estimate ≥ true count, always, and
  • estimate ≤ true count + ε·N, with probability at least 1 − δ.

The intuition: in one row, the expected noise in our item's counter is at most N / w (the other N units of count are spread over w columns). By Markov's inequality, the chance that the noise exceeds e times its expectation, which is ε·N, is at most 1/e. Each row fails independently with probability at most 1/e, so the chance that all d rows fail together, which is the only way the minimum is bad, is at most e^(−d) = δ.

A worked sizing example. Take one hour of views: N = 70 billion / 24 ≈ 2.9 billion.

  • We want the error to be small compared with the counts that matter. The 1,000th video in an hour probably has at least a few hundred thousand views. Choose ε = 10^−6, so the error bound is ε·N ≈ 2,900 views, about 1% of the threshold.
  • w = e / 10^−6 ≈ 2.72 million columns.
  • Choose δ = 0.001 (one item in a thousand may exceed the bound): d = ln(1000) ≈ 7 rows.
  • Total: 2.72 million × 7 ≈ 19 million counters. At 4 bytes each, about 76 MB.

Compare that with exact counting for the same hour: about 50 million distinct videos × 16 bytes ≈ 800 MB of raw counters, and far more inside a hash map. The sketch is roughly 10 times smaller, and crucially, its size does not depend on the number of distinct videos. It depends only on the accuracy we ask for. If we needed per-country hourly lists for 200 countries, exact state would grow with each country's distinct videos, while 200 sketches would be a predictable 15 GB, or much less with a larger ε for small countries (whose N is smaller, so the same absolute error needs a smaller sketch).

The catch: a sketch cannot list its items. A count-min sketch answers "how many views does video v have?", but it cannot answer "which videos are the biggest?". It does not store item ids at all. So a sketch is always paired with a small structure that remembers candidates: a min-heap or sorted list of the top K ids with their estimated counts.

  • For each view of v: add it to the sketch, then read v's estimate.
  • If the estimate is above the heap's threshold, insert or update v in the heap.

Because estimates never under-count, a true heavy hitter is never missed. The risk is the other way round: a low-count video that collides with heavy ones can look bigger than it is and push a real member out. With ε chosen so that ε·N is small relative to the threshold, those errors are confined to items near the cut-off, which is exactly where a 1% error does not matter much to users.

Implementation option 1 (good): Redis. The RedisBloom module (included in Redis Stack) provides a count-min sketch type with commands such as CMS.INITBYPROB (create from error and probability), CMS.INCRBY and CMS.QUERY. A consumer can, for each batch of views:

  1. CMS.INCRBY topk-cms:HOUR:10 v1 n1 v2 n2 ... to add the batch.
  2. CMS.QUERY the same ids to get their estimates.
  3. ZADD topk:HOUR:10 estimate id for each id, then ZREMRANGEBYRANK topk:HOUR:10 0 -1001 to keep only the top 1,000.

A useful optimisation is the lower bound: read the current 1,000th score once per batch (ZRANGE ... 0 0 WITHSCORES) and only ZADD ids whose estimate beats it. That skips most writes to the sorted set.

The weakness is durability. Redis persists by snapshot and append-only file, but its persistence has no relation to the Kafka offsets the consumer has committed. After a crash, the Redis state might include views from offsets the consumer had not yet committed (they will be replayed and counted twice) or miss views it had committed (they are lost). Sketches cannot be "un-added" to fix this. For a trending page, a small error after a rare crash may be acceptable. For billing-like accuracy it is not.

Implementation option 2 (great): sketches in the stream processor. Keep the sketch and the heap in Flink state. Flink checkpoints the state and the Kafka offsets together, atomically, so after a crash both rewind to the same consistent point and every view is reflected exactly once in the sketch. The sketch is small enough that checkpointing it is cheap (76 MB per window). This combines the memory savings of approximation with the exactly-once guarantees of the stream design.

Sliding windows with a sketch. Count-min sketches support subtraction: subtracting a count you previously added restores the counters exactly, because addition is linear. So the bucket-subtraction design from Deep Dive 6 works, keeping one sketch per minute bucket (subtract the expiring minute's sketch from the hour sketch, cell by cell) or decrementing per item. Decrements are only valid for counts that were actually added earlier; subtracting something that was never added breaks the "never under-estimates" guarantee. As far as we know, RedisBloom does not offer a decrement command for its count-min sketch, so sliding windows with sketches are a further argument for keeping sketches in the stream processor, where we control the arithmetic.

Two refinements worth naming.

  • Conservative update: when adding n to an item, raise each of its d counters only up to (current estimate + n), instead of adding n to all of them. This never breaks the upper-bound guarantee and noticeably reduces over-estimation for skewed data. It does, however, make the sketch non-linear, so subtraction is no longer valid.
  • Count sketch (Moses Charikar, Kevin Chen and Martin Farach-Colton, "Finding Frequent Items in Data Streams", ICALP 2002) uses a random +1 or −1 sign per row and takes the median instead of the minimum. Its error is unbiased and bounded by the L2 norm of the counts rather than their total, which is tighter for very skewed distributions, at the cost of being able to under-estimate.

When to approximate. Use exact counting when results are public and contested (view counts, creator rankings, charts used for payouts) and the item space fits in the stream processor's state. Use sketches when you need many lists (per country, per category, per minute), when the item space is unbounded (search queries, URLs, IP addresses for abuse detection), or when the list feeds an internal decision where 1% error near the cut-off is harmless. A common hybrid: use a sketch to find candidates cheaply, then count only the candidates exactly. The sketch's job is to shrink billions of items to a few thousand. Exact counters for a few thousand items are cheap.

8. Heavy-hitter algorithms: finding the top items with fixed memory#

Count-min sketch plus heap is one way to find frequent items with bounded memory. A second family of algorithms keeps a fixed number of counters with item ids attached, and is often simpler and more accurate for pure top-K questions.

Misra-Gries (Jayadev Misra and David Gries, "Finding Repeated Elements", Science of Computer Programming, 1982). Keep at most k − 1 (item, counter) pairs.

  • If the incoming item has a counter, increment it.
  • Else, if there is a free slot, add the item with count 1.
  • Else, decrement every counter by 1 and remove any that reach zero.

Guarantee: every item whose true count exceeds N / k is still in the table at the end, and each stored counter under-estimates the true count by at most N / k. Intuition: each "decrement all" step cancels k distinct occurrences (the incoming one plus k − 1 stored ones), so it can happen at most N / k times.

Space-Saving (Ahmed Metwally, Divyakant Agrawal and Amr El Abbadi, "Efficient Computation of Frequent and Top-k Elements in Data Streams", ICDT 2005). Keep exactly m (item, count, error) entries.

  • If the incoming item is tracked, increment its count.
  • Else, find the entry with the smallest count, replace its item with the new one, set the new count to (old minimum + 1), and record the old minimum as the new item's maximum possible over-estimate.

Guarantee: any item with true count greater than N / m is tracked, and every tracked count over-estimates by at most its recorded error, which is at most N / m. Space-Saving is widely regarded as one of the most accurate counter-based algorithms in practice, and with a "stream summary" linked structure every update is O(1).

A tiny Space-Saving example with m = 3 slots, on the stream a b a c d a b e a b:

StepEventTable after the step (item: count, error)
1 to 4a b a ca: 2, 0; b: 1, 0; c: 1, 0
5dmin is b or c at 1, replace c: a: 2, 0; b: 1, 0; d: 2, 1
6aa: 3, 0; b: 1, 0; d: 2, 1
7ba: 3, 0; b: 2, 0; d: 2, 1
8emin is b or d at 2, replace d: a: 3, 0; b: 2, 0; e: 3, 2
9 to 10a ba: 4, 0; b: 3, 0; e: 3, 2

The true counts are a = 4, b = 3, c = 1, d = 1, e = 1. The table reports a and b exactly. It reports e as 3, but its error field says "at most 2 of these may be fake", so e's guaranteed count is only 1, and we can tell it is not a real heavy hitter. The error field is what makes Space-Saving answers checkable.

Lossy Counting (Gurmeet Singh Manku and Rajeev Motwani, "Approximate Frequency Counts over Data Streams", VLDB 2002) divides the stream into buckets of width 1/ε and periodically prunes items whose count plus error is too small. It uses somewhat more memory than Space-Saving but was one of the first algorithms with deterministic guarantees for this problem.

Mergeability matters for distributed counting. In our design, counting happens on many tasks and in many regions, so summaries must be combined. Pankaj Agarwal and co-authors, in "Mergeable Summaries" (PODS 2012), showed that Misra-Gries and Space-Saving summaries can be merged with the same error guarantees: add the counters of the two summaries, then reduce to k entries by subtracting the (k+1)-th largest counter from all of them. Count-min sketches merge even more simply: add the arrays cell by cell, as long as both used the same hash functions and dimensions. This is what makes approximate per-region counting practical. Each region builds a summary, ships it (kilobytes to megabytes), and the global stage merges them, avoiding the split-count trap of Deep Dive 3 by merging counts in summaries, not ranked lists.

TechniqueMemoryError directionLists items itself?MergeableBest for
Exact counters plus heapO(distinct items)NoneYesYes, by re-keyingPublic, contested rankings
Count-min sketch plus heapO((1/ε)·ln(1/δ)) plus KOver-estimatesNo, needs the heapYes, add arraysMany lists, unbounded keys
Count sketch plus heapO((1/ε²)·ln(1/δ)) plus KBoth directions, unbiasedNoYesVery skewed data
Misra-GriesO(1/ε)Under-estimatesYesYesSimple, deterministic
Space-SavingO(1/ε)Over-estimates, with error bound per itemYesYesMost accurate counter-based top-K
Lossy CountingO((1/ε)·log(εN))Under-estimatesYesPartlyHistorical baseline

9. Could a specialised database do this for us?#

An interviewer may ask: "Isn't this what a time-series or analytics database is for?" The honest answer is "partly", and the reasons are instructive.

Bad: a metrics time-series database (Prometheus, InfluxDB). These databases store a separate series for each unique combination of metric name and labels, and index each series. If each video is a label value, we have billions of series. That is called high cardinality, and it is the classic way to break such systems: the series index no longer fits in memory and ingestion collapses. They are built for millions of series (one per host, per endpoint), not billions. See Time-Series Databases.

Good: TimescaleDB. TimescaleDB is PostgreSQL with automatic time partitioning (hypertables) and continuous aggregates: materialised views that the database refreshes incrementally as new data arrives, instead of recomputing from scratch. We can define an hourly aggregate of views per video, refreshed every minute, and index it by (bucket, views DESC):

CREATE MATERIALIZED VIEW video_views_hourly
WITH (timescaledb.continuous) AS
SELECT time_bucket('1 hour', event_time) AS bucket,
       video_id,
       count(*) AS views
FROM view_events
GROUP BY bucket, video_id;
 
CREATE INDEX ON video_views_hourly (bucket, views DESC);
 
-- Top 1,000 for one closed hour: an index walk, not a scan
SELECT video_id, views FROM video_views_hourly
WHERE bucket = '2026-12-03 10:00+00'
ORDER BY views DESC LIMIT 1000;

This works for the hourly list. Day and month lists can be built as hierarchical aggregates on top of the hourly one. Two limits remain: inserting 700,000 raw rows per second into a single PostgreSQL-based system needs heavy batching (or pre-aggregation upstream, which brings us back to the stream processor), and we still want the precomputed list in a cache, since even an index walk adds milliseconds and load.

Good: OLAP databases built for real-time analytics.

  • Apache Druid can roll up at ingestion time: it stores pre-aggregated rows (for example, one row per video per minute with a count) instead of raw events, and compaction later merges small segments and coarsens the granularity of old data. Druid also has a dedicated TopN query type. Notably, Druid's documentation describes TopN as approximate when the data spans many segments, because each segment returns only its own top candidates before merging. That is exactly the split-count trap from Deep Dive 3, showing up in a real product.
  • Apache Pinot offers the star-tree index, which pre-aggregates metrics across combinations of dimensions so that group-by and top-N queries over chosen dimensions read pre-computed nodes instead of raw rows. LinkedIn built Pinot and uses it for user-facing analytics.
  • ClickHouse can use a materialised view that writes into a SummingMergeTree or AggregatingMergeTree table. As parts are merged in the background, rows with the same key (video and hour) are summed. Queries must still sum() and GROUP BY at read time to combine not-yet-merged parts. ClickHouse also ships an approximate topK aggregate function, which its documentation says is based on the Filtered Space-Saving algorithm, a variant of Space-Saving from Deep Dive 8.

These systems can serve the history and the analytics side of the problem well, and some teams do run trending lists straight off them. The caution is practical: at hundreds of thousands of events per second, their ingestion pipelines, segment management and rollup configuration need expert tuning, and performance can degrade unpredictably as data grows. In an interview, using one is fine if you can explain how it ingests and pre-aggregates. If you cannot, the primitives (Kafka, Flink, Redis, a relational history store) make for a clearer, more defensible answer, because you can explain every step.

"Top videos of the last day" is dominated by videos that are always popular: music videos, children's content, the same few channels every day. A trending list is supposed to show what is unusually popular right now. That needs a different score, not just a different window.

Common trending scores.

  • Velocity: views in the last hour minus views in the hour before. Rewards acceleration. It is noisy for small items: a video going from 2 views to 40 has a large relative jump but is not interesting.
  • Ratio to baseline: views in the last hour divided by the item's typical views for this hour of the week (for example, the average of the same hour over the previous 4 weeks). It corrects for daily and weekly cycles, so a video that is always popular at 8 pm does not trend every evening.
  • Z-score: (x − μ) / σ, where x is the current count and μ and σ are the mean and standard deviation of the item's recent history. "How many standard deviations above normal is this?" It is a natural fit for hashtags and search queries, which have long histories.
  • Decayed score: the sum of views weighted by age, as in the forward-decay trick from Deep Dive 6. A widely cited version of the Hacker News ranking formula is score = (points − 1) / (age in hours + 2)^1.8, where the exponent controls how quickly items fade. Reddit's historical "hot" ranking, from its open-sourced code, adds the logarithm of the vote score to a term proportional to the post's creation time, so newer posts start higher and every 10-times increase in votes is worth a fixed amount of time.

Smoothing small counts. All ratio-style scores explode for items with tiny baselines. Two standard fixes: add a constant to the denominator (a prior, as in "views / (baseline + 100)"), or require a minimum absolute count before an item is eligible (for example, at least 10,000 views in the hour). Bayesian versions shrink small-sample ratios toward the global average.

How the pipeline changes. The counting part is unchanged: we still need per-video counts per minute or hour. What changes is the ranking stage, which now needs two inputs per item: the current count and the baseline. Baselines change slowly, so they are computed by a batch job (hourly or daily) and loaded into the stream processor as a side input, a small lookup table per item. Only items above a minimum count need a baseline, which keeps that table to millions of entries, not billions.

Production trending lists also add editorial and policy rules that pure counting cannot express: remove unsafe or misleading content, limit how many items one creator or topic can take, and merge near-duplicates (several uploads of the same clip). YouTube, for example, has said publicly that its trending list considers signals such as view count and how quickly a video is gaining views, rather than raw views alone. The precise formulas companies use are not public, so in an interview present your scoring as a reasoned choice, not as "what YouTube does".

More dimensions: per-country and per-category lists. Each dimension multiplies the number of lists. A view in country C for a video in category G contributes to the global list, the country C list, the category G list and the (C, G) list, in each of 4 windows: 16 counter updates per view instead of 4. With 200 countries and 20 categories there are about 4,000 dimension combinations and 16,000 lists. Three techniques keep this affordable:

  • Pre-aggregate by the full key once, (videoId, country, category, minute), then derive coarser lists by summing. The fine-grained counts are the only thing that touches every event.
  • Compute only lists that people actually request. The (country, category) combinations follow a long tail too. Precompute the popular ones and serve rare ones from a slower path, or not at all.
  • Use sketches or Space-Saving summaries for small lists. A per-country-per-category list only needs the top 100 items with modest accuracy, which is a perfect fit for a small fixed-memory summary per list.

11. Real-time leaderboards with Redis sorted sets#

A game leaderboard is the same problem with a different shape. There are fewer items (millions of players rather than billions of videos), scores are often set rather than counted (a player's best score), users want their own rank, not just the top, and they expect updates within a second. This is the home ground of the Redis sorted set (see Redis in Practice).

What a sorted set gives you. A sorted set stores unique members, each with a numeric score, ordered by score. Internally it combines a hash table (member to score) with a skip list in which each link also records how many elements it skips. Those span counts let Redis compute a member's rank in O(log N), not just find it. The core operations:

ZADD     lb:season7 1520 player:42        # set score: O(log N)
ZADD     lb:season7 GT 1600 player:42     # only if higher (best score), Redis 6.2+
ZINCRBY  lb:season7 25 player:42          # add to score: O(log N)
ZREVRANGE lb:season7 0 9 WITHSCORES       # top 10: O(log N + 10)
ZREVRANK lb:season7 player:42             # my rank, 0-based: O(log N)
ZSCORE   lb:season7 player:42             # my score: O(1)
ZREVRANGE lb:season7 1195 1205 WITHSCORES # the players around rank 1200
ZCOUNT   lb:season7 1600 +inf             # how many have at least 1600
ZREMRANGEBYRANK lb:season7 0 -1001        # keep only the top 1000

The last command is the general trick for a bounded top-K list: after each ZADD, trim everything below rank K. It is how the earlier design keeps "top 1,000 videos this hour" in Redis, and how a feature such as "top 5 posts per keyword" can be maintained: ZADD the post with its like count to top:keyword, then ZREMRANGEBYRANK top:keyword 0 -6 to keep only the 5 highest.

Ties. Two players with the same score need a stable order, usually "whoever reached it first ranks higher". Sorted sets break ties by member name in lexicographic order, which is rarely what the game wants. The usual fix is a composite score: put the real score in the high bits and an inverted timestamp in the low bits, for example score × 2^32 + (2^32 − 1 − secondsSinceSeasonStart). Redis scores are 64-bit floating-point numbers, which represent integers exactly only up to 2^53, so the real score must fit in about 21 bits here (up to about 2 million). If it does not, use coarser timestamps or keep the tie-break in a second lookup.

Sizing one sorted set. With roughly 100 bytes of memory per member (skip list nodes, hash entry and the member string), 10 million players need about 1 GB, and 100 million players about 10 GB. A single Redis node handles on the order of 100,000 sorted-set operations per second. Two limits appear at large scale:

  • A sorted set is one key, so it lives on one shard of a Redis Cluster. It cannot be spread across nodes automatically.
  • Write throughput of one node caps the total score-update rate.

Sharding a very large leaderboard. If one key is too big or too busy, there are three designs:

  • Shard by player id. Keep N sorted sets, lb:s7:{0..N-1}, with each player in exactly one. The top K is exact by merging each shard's top K (each player has one owner, so the argument from Deep Dive 3 applies). A player's global rank is the sum over shards of ZCOUNT shard (score +inf, which needs N calls (pipelined, so this is one round trip per shard in parallel). That is fine for N around 10.
  • Shard by score range. Each shard holds a band of scores (0 to 999, 1,000 to 1,999, and so on), with bands chosen from the score distribution so they hold similar numbers of players. Rank is "players in all higher bands" (a small cached counter per band) plus the rank inside the player's band. The top K reads only the highest band. The cost is that a score change can move a player between shards, which is a delete and an insert on two nodes, and bands must be rebalanced as the distribution shifts.
  • Exact at the top, approximate below. Few players care whether they are number 48,213,551 or 48,213,552. Keep an exact sorted set for the top 100,000 or so, and for everyone else keep a histogram of scores (say 10,000 buckets, maintained with counters). A player outside the top set gets "top 12.4%", computed from the histogram. This makes the system's cost proportional to the number of players who care about exact ranks.

Time-scoped and relative boards.

  • Daily and weekly boards are just separate keys (lb:daily:2026-12-03) with a TTL. A weekly board can be maintained by incrementing it alongside the daily one, rather than computing ZUNIONSTORE over seven daily sets, which costs O(N log N) and stalls a single-threaded Redis node for seconds on large sets.
  • Friends leaderboards: fetch the scores of a player's few hundred friends from the global set (ZMSCORE, Redis 6.2+, gets many scores in one call) and sort them in the application. Fan-out of every score change to each friend's personal board is far more expensive and rarely needed.

Durability. Treat Redis as a fast index, not the system of record. Each score submission is written first to a durable store (a relational table or DynamoDB, keyed by player and season), and applied to Redis after the write commits. If a Redis node is lost, the leaderboard can be rebuilt by scanning the durable store, which for 100 million players is a few minutes of bulk ZADDs. For the trending-videos pipeline, Redis holds only published lists that the stream processor can republish at any time, so losing it costs at most one refresh interval.

Pushing live changes to viewers. A leaderboard on a stream or a tournament page should update without the user refreshing. The usual design:

  1. The game client reports the end of a match.
  2. The game server validates the score itself. Scores sent directly by clients are trivially forged, so the authoritative score must come from the server that ran (or verified) the match.
  3. The score is written to the durable store first.
  4. Redis is updated with ZADD GT, so only an improvement changes the board.
  5. The server reads the player's new rank (0-based 1199).
  6. The player sees their score and rank immediately.
  7. A change notification goes out through Redis pub/sub or a Kafka topic.
  8. The push service throttles: it re-reads the top 10 at most once per second, however many updates happened. Without throttling, a busy board would generate thousands of pushes per second per viewer.
  9. It pushes only the diff (who moved and to where) to connected viewers over Server-Sent Events or WebSockets. SSE is enough for one-way updates and works through most proxies. See Polling, Long Polling, SSE, WebSockets and Webhooks and Pattern: Pushing Realtime Updates.

For millions of viewers, the push service itself fans out through a tree of connection servers, exactly as in the live-comments case. Players who only care about their own rank can simply poll ZREVRANK every few seconds, which is cheaper than holding a connection open for each of them.

12. Failures, exactly-once counting and multiple regions#

Rankings are public. If a bug double-counts an hour of views, a video can appear at the top of a chart it did not earn, and creators notice. So the counting pipeline needs the same care as a billing pipeline, even though the output is "just" a list.

Where views could be lost or double-counted, and the defence for each.

  • Playback service to Kafka. The producer uses acknowledgements from all in-sync replicas (acks=all) and idempotent production, so a retried send does not create a duplicate record. Each event carries a viewId, so any duplicate that slips through can be dropped downstream.
  • Inside the stream processor. Flink takes periodic checkpoints: a consistent snapshot of all operator state (counters, heaps, sketches) together with the Kafka offsets that produced it, written to object storage. On a crash, every operator restores the last checkpoint and Kafka consumption rewinds to the saved offsets. Every view is then reflected exactly once in the restored state, even though some events are processed twice physically. See Apache Flink and Stream Processing.
  • Stream processor to Redis. Exactly-once state does not automatically mean exactly-once output: after a restore, the job re-emits lists it may already have written. That is harmless here, because each write replaces the whole list for a window. Writing the same list twice is idempotent. This is a key design choice: publish absolute values (the full list, or full counts), never deltas such as "add 5 to v1", so replays cannot inflate anything.
  • Stream processor to the history store. Count snapshots are written as upserts keyed by (window, videoId) with absolute values, so replays overwrite rather than add. Where increments must be used (for example, in the per-window tables design of Deep Dive 4), each batch carries an id, and the database records applied batch ids in the same transaction, the write-then-mark pattern.
  • Bugs. The worst failures are logical: a deploy that miscounts for three hours. Because Kafka retains raw events for days and object storage keeps them longer, we can fix the bug, start a new job version from an older offset (or from object storage) into new output keys, verify it, and then switch readers to the corrected keys. Never repair counts in place with ad hoc scripts.

Reconciliation. A daily batch job (Spark, or SQL on the warehouse) recounts closed hours and days from raw events in object storage and compares them with what the stream produced. The two should agree exactly for windows that the stream closed after the allowed lateness, apart from very late events routed to the side output. If they differ beyond that, it is a bug, and the batch result wins. This is the Batch vs Stream Processing "Lambda" idea used only as a safety net, while the stream remains the primary path (closer to a "Kappa" design).

Degraded modes.

  • The stream job lags or stops. Readers keep getting the last published lists, with an old computedAt. The UI can show "updated 6 minutes ago". Kafka buffers views (several days of retention), so when the job recovers it catches up without losing anything. Catch-up speed matters: the job should be sized to process at least 2 to 3 times the normal rate, so a one-hour outage is recovered within 30 minutes or so.
  • Redis is lost. The Query Service falls back to the topk_list table in the history store, which holds every published list. Reads become a few milliseconds slower until Redis is repopulated by the next publish cycle.
  • The global merge operator fails. It is a single task with tiny state, so it restarts within seconds from the checkpoint. Meanwhile the previous lists stay in Redis.

Multiple regions. A global platform ingests views in several regions. Users want a global trending list, and also regional ones. The tempting design is "each region computes its own top 1,000 and a global service merges the lists". Deep Dive 3 showed why that is wrong: a video that is moderately popular in every region can beat one that is huge in one region, and merging lists misses it. The correct designs ship counts, not lists:

  • Centralised counting. Every region forwards its view events (or, better, its per-minute pre-aggregated counts) to one global Kafka cluster, for example with MirrorMaker 2 or a managed replication service. One global Flink job counts and ranks. Simple and exact, at the cost of cross-region bandwidth (pre-aggregation shrinks this a lot) and a dependency on one region for the global list.
  • Regional pre-aggregation, global ranking. Each region pre-aggregates to (videoId, minute, count) and ships those records to a global stage keyed by video id. The global stage sums complete counts and ranks. Regional lists are computed locally from regional counts. This is the usual production shape.
  • Mergeable summaries. If shipping per-video counts for billions of videos is too much, each region ships a fixed-size summary (a Space-Saving summary of 100,000 entries, or a count-min sketch plus candidate list) and the global stage merges them (Deep Dive 8). This is approximate, but with a known error bound.

The global lists are tiny, so replicating them to every region's Redis is cheap, and reads are always local. See Multi-Region and Global Data for the general trade-offs.

Observability. The metrics that tell you the pipeline is healthy (see Observability: Logs, Metrics and Traces):

  • Consumer lag per Kafka partition, in seconds of event time. The primary freshness signal.
  • Age of the newest published list per window. Alert when it exceeds a few minutes.
  • Watermark progress and the number of late events sent to the side output. A sudden rise in late events usually means a clock problem or a delayed upstream batch.
  • Checkpoint duration and size. Growing checkpoints are the first sign that state is growing faster than expected (for example, if expired windows are not being cleared).
  • Reconciliation drift: the difference between stream counts and batch recounts per closed window. It should be zero or tiny.
  • Skew: events per second per partition. One partition far above the rest indicates a hot video that needs salting.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
One viral video floods its Kafka partitionLag on that partition, stale counts for every video sharing itCombiners at the edge, salt hot keys across partitions, then re-key partial counts by video before ranking
Database row lock on a hot counterWrite throughput collapses for the hot video and the shardNever increment per view. Pre-aggregate in the stream, batch writes, keep the ranking out of the database
Index updates on every incrementWrite amplification, slow inserts at hundreds of thousands per secondKeep the ranking in the stream processor. Index only per-window history tables that receive batched writes
Merging local top-K lists from split countsWrong winners: an item that is second everywhere never appearsPartition by item, or re-key partial counts before ranking, or use TPUT for exact distributed top-K
Query-time aggregation over windowsSeconds to minutes per request, database overloadPrecompute every list. Readers only read cached lists
Cache stampede when a list expiresBurst of expensive recomputation, latency spikesProactive refresh by the builder or stream job, no lazy recomputation, keep the previous version
Builder or stream job silently stopsLists go stale with no errorsAlert on the age of the newest list, show computedAt to clients
Late events after a window closesSmall undercount for that windowAllowed lateness in the watermark, side output, daily batch recount and one-time correction
Sliding month window stateTerabytes of minute buckets just to subtractCoarser buckets for long windows, or tumbling day and month windows, or exponential decay
Flink state and checkpoint growthSlow checkpoints, long recovery, job instabilityClear expired window state with timers, incremental RocksDB checkpoints, monitor checkpoint size
Count-min sketch over-estimationA low-count item displaces a real member near the cut-offSize ε so ε·N is small relative to the K-th count, conservative update, exact recount of candidates
Single huge Redis sorted set for a leaderboardMemory and throughput limit of one nodeShard by player id and merge, shard by score range, or exact top plus histogram for the long tail

What Interviewers Expect#

Mid-level. Produce a working end-to-end design: view events into Kafka, counters partitioned by video id, a table or Redis sorted set for ranking, and a cache in front of reads. Explain why ORDER BY views DESC LIMIT k on an index is cheap to read but expensive to maintain at hundreds of thousands of writes per second, and propose batching. Handle the all-time list well, and give a reasonable approach to windows, even if it is not optimal (for example, hourly rows summed by a periodic job into a cache). Know that count-min sketch exists for approximate counting.

Senior. Reach a near-optimal design and drive it. Estimate the write rate (about 700k per second) and show the effect of pre-aggregation on shard count. Precompute lists instead of caching lazily, and explain the stampede and SLA problems with TTL caching. Choose tumbling windows deliberately, and explain how sliding windows work (add the newest bucket, subtract the oldest) and what they cost. Explain why merging local top-K lists is exact only when each item is owned by one shard. Discuss stream versus batch, and how exactly-once state is achieved with checkpoints and Kafka offsets. Explain count-min sketch with its error bound and when approximation is acceptable.

Staff and above. Lay out the whole solution space and judge between options with reasons: per-window tables versus stream state versus OLAP databases, exact versus sketch versus Space-Saving, tumbling versus sliding versus decayed scores. Spot the split-count trap in multi-region and hot-key designs before the interviewer does, and know the fixes (re-keying, mergeable summaries, TPUT). Distinguish "top" from "trending" and propose a scoring and filtering pipeline. Plan for operations: reconciliation, replay into new keys after bugs, catch-up capacity, observability of freshness. Adapt the design to a game leaderboard with exact own-rank queries, tie-breaking and sharding of a huge sorted set, and live push with throttling.

Deep Dive: the Flink job, in outlineShow

The job below shows the shape of the streaming design in Java. It is a sketch for explanation, not production code. The pre-aggregation, window counters and ranking are three operators. The global ranking runs with a parallelism of 1, which is fine because it receives only candidate updates, not raw views.

DataStream<ViewEvent> views = env
    .fromSource(kafkaSource, WatermarkStrategy
        .<ViewEvent>forBoundedOutOfOrderness(Duration.ofSeconds(30))
        .withTimestampAssigner((e, ts) -> e.eventTimeMillis()), "views");
 
// 1. Pre-aggregate: one record per video per 20 seconds
DataStream<VideoCount> partial = views
    .keyBy(ViewEvent::videoId)
    .window(TumblingEventTimeWindows.of(Duration.ofSeconds(20)))
    .allowedLateness(Duration.ofMinutes(2))
    .sideOutputLateData(lateTag)
    .aggregate(new CountAgg());          // emits (videoId, windowEnd, n)
 
// 2. Rolling window counters per video: hour, day, month, all time.
//    Keyed state in RocksDB; timers clear expired windows.
DataStream<WindowCounts> counts = partial
    .keyBy(VideoCount::videoId)
    .process(new RollingWindowCounters());
 
// 3a. Local top 1000 per window, per parallel task (threshold filter inside)
DataStream<TopKDelta> local = counts
    .keyBy(c -> c.videoId().hashCode() % 128)   // spread over 128 rankers
    .process(new LocalTopK(1000, Duration.ofSeconds(10)));
 
// 3b. Global merge, exact because each video has one owner
local
    .keyBy(d -> d.window())               // one key per window type
    .process(new GlobalTopK(1000))
    .addSink(new RedisListSink());        // SET topk:{window} <full list>

Three details worth explaining if asked:

  • The 20-second pre-aggregation window plus a 10-second publish interval keeps end-to-end freshness well under a minute, while still collapsing the head of the distribution.
  • RollingWindowCounters registers an event-time timer at the end of each hour, day and month. When the timer fires, it emits the final count for the closed window and clears that window's state, so state does not grow forever.
  • LocalTopK keeps one bounded ordered structure per window type, sends only entries that changed in each interval, and ignores updates below its current threshold.
Deep Dive: one hour, worked end to endShow

Follow one hour, 10:00 to 11:00, for one viral video (v_viral) and the pipeline as a whole.

Inputs. 2.5 billion views arrive in the hour from all videos, about 700,000 per second. v_viral is a new music video that receives 30 million views in the hour, about 8,300 per second, rising from 2,000 per second at 10:00 to 15,000 per second at 11:00.

Kafka. v_viral's views all hash to partition 173. That partition normally carries about 2,700 events per second (700,000 / 256 partitions). With v_viral, it carries up to 17,700 per second at the end of the hour, about 6.5 times the average. That is high, but within what one partition and one consumer handle (a partition can typically take tens of thousands of small events per second), so no salting is needed yet. A video at 100,000 views per second would need salting.

Pre-aggregation. Every 20 seconds, the task owning partition 173 emits one record for v_viral, for example (v_viral, 10:41:20, 211,000). Over the hour, v_viral produces 180 records instead of 30 million. Across all videos, the pre-aggregation stage emits roughly one record per distinct (video, 20-second window), on the order of 2 to 5 million per minute, a reduction of about 10 times compared with 42 million raw events per minute. The head of the distribution collapses by thousands of times; the tail barely changes.

Window counters. For each record, v_viral's hour, day, month and all-time counters increase. At 10:30, its hourly count is about 11 million.

Ranking. The current 1,000th place for the hour is held by a video with about 380,000 views at 10:30. v_viral entered the hourly top 1,000 at about 10:03 and reached first place around 10:25. Of the millions of count updates per minute, only those above 380,000 views pass the threshold filter: a few thousand per minute.

Publishing. Every 10 seconds, the global stage writes topk:HOUR:current. Each write is about 16 KB. That is 360 writes per hour per window, trivial for Redis.

Closing. At 11:02, the watermark passes 11:00 plus 2 minutes of allowed lateness. The hourly list for 10:00 is written as final, with v_viral first at 30,004,112 views. Over the next day, 3,100 late views for that hour arrive from devices that were offline. They are routed to the side output and counted by the batch job, which corrects v_viral's final count to 30,007,212 the next morning. The ranking does not change, so the published list is updated only in its counts.

The lesson is quantitative: the expensive work (counting every view) is spread thinly over many tasks, and the ranking work happens only for the few thousand items near the top.

Deep Dive: the batch-only version, and why it is not enough hereShow

Before stream processors were common, top-K was a batch job, and it is still the right design when freshness of an hour or a day is acceptable (for example, "top songs this week" for a published chart).

A MapReduce or Spark version for one day:

  1. Map: read the day's raw events from object storage and emit (videoId, 1).
  2. Combine: sum locally on each mapper, so each mapper emits one record per video it saw.
  3. Shuffle and reduce: partition by video id, and sum to get each video's complete daily count.
  4. Local top-K: each reducer keeps a bounded heap of its top 1,000.
  5. Global top-K: a single final step merges the reducers' lists. Exact, because each video went to one reducer.

This is the same partition-then-merge structure as the streaming design, applied to a finite dataset. It is simple, cheap and easy to verify. Its weakness is latency: the job can only start after the window closes, and processing 9 TB of raw events takes tens of minutes even on a large cluster, so the "last hour" list would always be one to two hours old. That fails the 1-minute freshness requirement, so batch keeps its role as the reconciliation path rather than the primary path.

Deep Dive: rough cost of the designShow

Rough monthly sizing for the streaming design at 700k views per second average, using commodity cloud instances. These are order-of-magnitude figures to show where the cost sits, not quotes.

  • Kafka: about 9 TB per day ingested, replicated 3 times, with 3 days of retention: about 80 TB of broker storage, served by perhaps 20 to 30 brokers. This is the biggest piece.
  • Flink: pre-aggregation and counting at 700k events per second, with 2 to 3 times headroom for catch-up, needs on the order of 50 to 150 CPU cores. State for billions of video counters (all-time plus open windows) is a few hundred GB in RocksDB, spread across the task managers' local SSDs, plus checkpoints in object storage.
  • Redis: a few megabytes of published lists. A small replicated cluster per region.
  • Object storage: 9 TB per day of raw events, compressed to perhaps 2 to 3 TB per day in a columnar format. A year is about 1 PB, and it is the only store that grows without bound, so lifecycle rules move it to colder tiers after a few weeks.
  • History store: hourly and daily per-video counts, around 20 GB per day, plus all-time counts.

The striking result is that serving the top-K API costs almost nothing. Nearly all of the money goes to ingesting and counting the firehose, which is the work the product needs anyway for view counts on every video page. A top-K system usually shares that pipeline with per-video view counting and creator analytics, rather than owning its own.

Deep Dive: why exact top-K in a single pass needs lots of memoryShow

It is worth knowing why approximation appears in every streaming top-K discussion. Suppose we want the exact most frequent item in a stream, in one pass, with memory smaller than the number of distinct items. Here is an intuition for why that is impossible in general.

Imagine a stream in which every item appears once, except possibly one item that appears twice at the very end. To decide whether the final item is a repeat, the algorithm must have remembered whether it appeared earlier, for any of the items it saw. That means storing information about every distinct item seen so far, which needs memory proportional to the number of distinct items. This is the intuition behind formal lower bounds in streaming complexity: finding the exact maximum frequency (or the exact top K) in one pass requires memory linear in the number of distinct items in the worst case. The landmark paper on this kind of space bound is Noga Alon, Yossi Matias and Mario Szegedy, "The Space Complexity of Approximating the Frequency Moments" (STOC 1996), which showed that some frequency statistics can be approximated in tiny space while others cannot be computed exactly without linear space.

Two practical consequences follow:

  • Exact counting is possible here only because we pay for the memory: one counter per video, on disk-backed state across many machines. That is a deliberate engineering choice, not a free lunch.
  • Approximation is not a hack. When the number of distinct keys is unbounded (search queries, URLs, IP addresses), approximation with a proven error bound is the only way to work in bounded memory, and Count-Min, Count Sketch and Space-Saving are the standard tools.

Real data helps: view counts are highly skewed (roughly Zipf-like), and on skewed data Space-Saving and count-min sketches are far more accurate than their worst-case bounds suggest, because the heavy items stand well clear of the noise.

Deep Dive: adapting the design to other top-K problemsShow

The same skeleton (partitioned counting, precomputed lists, cheap reads) covers many interview variants. What changes is the key, the score and the tolerance for error.

  • Top search queries and autocomplete. Keys are query strings, an unbounded space with heavy typo noise. Normalise first (lower-case, trim, collapse whitespace), then count with a sketch or Space-Saving, because exact counters for every query ever typed are wasteful. The search-autocomplete case uses these counts, per prefix, to rank suggestions.
  • Trending hashtags or topics. Keys are extracted from posts. Use a trending score (velocity or ratio to baseline, Deep Dive 10) and strong spam filtering, because coordinated accounts try to push hashtags into trends. Windows are short (minutes to an hour), and per-country lists matter.
  • Best sellers and sales rank. Keys are products, scores are units sold, often with decay so recent sales count more. Lists are per category, so the number of lists is large (tens of thousands of categories) but each is small. Freshness of minutes to an hour is usually acceptable. See the sales-rank case.
  • Most active users or abusive IPs. An internal top-K for operations or security. Keys are unbounded and adversarial, which makes count-min sketch or Space-Saving the natural fit, and the output feeds rate limiting or blocking rather than a public page.
  • Game leaderboards. Scores are set rather than counted, users want their own exact rank, and updates must show within a second. Redis sorted sets as the index, a durable score store as the system of record (Deep Dive 11).
  • Top-K in monitoring. "Which endpoints have the highest error rate?" or "which hosts have the highest CPU?" over metrics. The number of keys is moderate (thousands to millions), so exact counts per key in a time-series database followed by a top-k query at read time can work. See the metrics-monitoring case.
Deep Dive: testing the pipelineShow

A ranking bug is visible to everyone, so the pipeline deserves serious tests.

  • Golden datasets. Build synthetic streams with a known answer: Zipf-distributed views with planted heavy hitters, adversarial split-count cases (the "second everywhere" example from Deep Dive 3), ties, and late events. Run the job on them in CI and compare the output lists exactly.
  • Property tests for the data structures. Feed random sequences of updates to the bounded top-K structure and compare with a brute-force sort after every step. Do the same for the sketch: check that estimates are never below true counts, and that the error exceeds ε·N for at most about a δ fraction of items.
  • Replay tests. Re-run yesterday's raw events through a new job version and compare its lists and counts with production's. Any difference must be explained before deploying.
  • Failure injection. Kill task managers mid-window, restart the job from a checkpoint, and verify that counts match a run without failures. This is the only real proof that exactly-once works in your configuration.
  • Clock skew. Inject events with timestamps from the future and the distant past, and verify the watermark is not dragged forward by bad clocks (for example, by bounding event time to within a few minutes of ingestion time).
Deep Dive: a 45-minute interview planShow
MinutesWhat to do
0 to 5Clarify: what is ranked, windows (fixed, tumbling), K at most 1,000, freshness of 1 minute, exact counts, scale of 70B views per day
5 to 8Estimates: about 700k writes per second, about 4B videos, 64 GB of counters, tiny number of distinct answers
8 to 15Simple design: Kafka, counters, index on views, query. Then windows, and show why query-time aggregation is too slow
15 to 20Precompute lists into a cache. Explain why TTL caching causes stampedes and slow misses
20 to 30Scale writes: partition by video, pre-aggregate in Flink, keep ranking in the stream. Explain why the merge of local top-K is exact
30 to 38One or two deep dives chosen by the interviewer: sliding windows, count-min sketch, hot keys, or multi-region
38 to 43Failure modes: exactly-once via checkpoints, idempotent publishing, late events, reconciliation
43 to 45Summary and extensions: trending scores, per-country lists, leaderboards

The most common mistake is spending the first 20 minutes on the read path. Reads are easy once lists are precomputed. Get there quickly and spend the time on writes, windows and correctness.

Deep Dive: follow-up questions and short answersShow
  • "What if K could be 100,000?" Lists become 1.6 MB each. Still precompute, but store them as a sorted set or in pages, and serve k by range reads. The threshold filter becomes less selective, so the ranking stage needs more parallelism.
  • "What if users can choose any start and end time?" Precomputation no longer covers every answer. Keep per-hour (or per-minute) top lists with complete counts for a larger candidate set, and merge at query time. That merge is not exact unless you also keep full counts, so either accept approximation (and say so), or answer arbitrary ranges from an OLAP store with seconds of latency.
  • "How do you count unique viewers instead of views?" Replace each counter with a HyperLogLog per video per window (about 12 KB each in Redis for a standard error near 0.8%). Rank by the estimate. HyperLogLogs merge by taking the per-register maximum, so windows can be combined.
  • "How do you stop someone from botting a video to the top?" View validation before counting (dedupe by viewer and video in a short window, bot detection), plus policy filters on the trending list. Ranking only after filtering matters, because removing counts afterwards is expensive.
  • "Your all-time counts are 64 GB. Why not just Redis?" It would work for the counters on a cluster of a few nodes, but sorted-set overhead makes an all-video sorted set around 400 GB, and every increment updates the skip list. Keep counts in stream state or a plain key-value store, and keep only the top lists in sorted sets.
  • "What happens at the hour boundary?" The current-hour list starts empty at 11:00 and fills over the first minutes, which looks odd. Show the previous complete hour until the new hour has enough data, or use a sliding hour.

Key Takeaways#

  • Top-K is a write problem disguised as a read problem. Reads ask the same few questions; writes arrive at hundreds of thousands per second. Do the work on the write side.
  • Precompute every answer. There are only hundreds of distinct lists of a few kilobytes each. Readers should only ever read a cached list, never trigger computation.
  • Partition by item, then merge. If each item's count is complete on one shard, merging local top-K lists is exact. If counts are split (hot-key salting, regions), re-key the partial counts before ranking, or the merge can miss the real winner.
  • Pre-aggregate in the stream. Short tumbling windows in Flink collapse the head of the distribution and cut writes by one to two orders of magnitude, with exactly-once state from checkpoints.
  • Prefer tumbling windows; make sliding windows cheap. Sliding windows mean subtracting expired buckets, which costs storage. Use fine buckets for short windows, coarse buckets or tumbling windows for long ones, or exponential decay.
  • Approximate deliberately. Count-min sketch (w = e/ε, d = ln 1/δ) and Space-Saving use fixed memory with proven error bounds, and they merge across shards. Use them for many lists or unbounded keys; keep exact counts for contested public rankings.
  • Trending is a different score. Velocity, ratio to baseline or decayed scores, plus filters for spam, policy and diversity.
  • Redis sorted sets are the leaderboard tool. O(log N) updates and rank queries, ZREMRANGEBYRANK for bounded lists, composite scores for ties, sharding or histograms for very large boards, and throttled SSE or WebSocket pushes for live views.