"Design top-K trending" asks for a leaderboard of the ten hottest videos, hashtags or products over the last hour, refreshed every minute, computed from a firehose of events. It is a favorite of interviews that want to see stream processing handled with numbers rather than vocabulary.
The stream processing lesson already walks through a trending-hashtags pipeline: a sliding window, event time and a Redis cache in front. This page assumes you have seen that shape and goes where the interview goes next. How is the count actually stored so the window can slide cheaply? Why can many workers each keep a local top-K and still produce an exact global one? When is exact counting too expensive, and what does the approximation cost? And is the most popular item the same thing as the most trending one?
Clarify the requirements
Functional requirements:
- Ingest an event for each view (or use, or purchase) of an item.
- Return the top 10 items by activity over the last hour, refreshed every minute.
- Optionally, return a top-K for a segment, such as a country or category.
- Surface items that are rising, not only those that are always large.
Out of scope, said aloud: personalized trending, spam and bot filtering (mention it, do not design it), long-term analytics and historical charts.
Non-functional requirements:
- Fresh: the list is at most a minute or two behind real traffic.
- Fast reads: the list is read by millions of users, so a read is a cache hit.
- Accurate enough: the order among the top few items matters, small errors in the tail do not.
- Bounded memory: the item space is huge and unbounded, so memory must not grow with the number of distinct items forever.
- Resilient: a worker crash must not corrupt the counts.
Estimate the scale
Assume 100 million users, each generating about 86 events a day, and a one-hour sliding window.
Event rate: 100M × 86.4 = 8.64 billion a day ÷ 86,400 s = 100,000 events per second on average, about 300,000 per second at peak.
Ingest bandwidth: 100,000 events × 100 bytes = 10 MB/s. Small; the stream is not the cost.
Events in a window: 100,000 × 3,600 s = 360 million events in an hour.
Distinct items: assume 50 million different items are active in any hour, and 5 million in any one minute.
Exact counts: keep one counter per item per one-minute bucket, about 32 bytes with overhead. One bucket is 5M × 32 B = 160 MB, and 60 buckets are 9.6 GB across the cluster. Split over 12 workers, that is about 800 MB each, comfortably in memory.
Sketch alternative: a Count-Min sketch with error ε = 0.0001 of the total and failure probability δ = 1% needs width e ÷ ε ≈ 27,200 and depth ln(1/δ) ≈ 5, so about 136,000 counters of 4 bytes, 544 KB per sketch. One sketch per minute bucket is 60 × 544 KB ≈ 33 MB. The error summed over the window is at most ε × N = 0.0001 × 360M = 36,000 counts (with 99% probability), and it can only overcount.
Reads: if 200 million users open the trending list twice a day, that is 400M ÷ 86,400 ≈ 4,600 reads per second, all served from one cached list.
"At this scale, exact counting fits in memory: about 800 MB per worker. That is worth saying plainly before reaching for a sketch. Approximation earns its place when the keyspace multiplies, for example top-K per country and per category, which turns 50 million items into billions of counters. The design must work out when to flip."
The capacity estimator reproduces the 100,000 events per second. Ignore its storage line: trending needs only the last hour, not a year of events.
API and data model
POST /v1/events { itemId, ts, segment? } (batched in practice)
GET /v1/trending?window=1h&segment=us&k=10 -> [ { itemId, score }, ... ]stream events partitioned by itemId
worker state bucket[minute] : itemId -> count (60 buckets in a ring)
total : itemId -> count in window (kept incrementally)
result Redis: trending:{segment}:{window} -> top K list, replaced every minuteThe non-obvious choice is the partition key. Partitioning the stream by item id means every event for an item reaches one worker, so that worker's count for the item is complete. That one fact makes the merge exact.
High-level design
The slice to simulate is the counting pipeline: events enter a partitioned stream, aggregators maintain windowed counts, and the current top-K is served from Redis.
- The event API accepts views and publishes them to a stream partitioned by item.
- Aggregators each own a share of the items and keep windowed counts and a local top-K.
- The merged top-K is stored in Redis, where the API reads it.
Describe this diagram
Components
- viewers (Client)
- event api (Service)
- view events (Kafka)
- aggregators (Service)
- top-k lists (Redis)
Connections
- viewers sends to event api
- event api sends to view events
- view events sends to aggregators
- aggregators sends to top-k lists
- event api sends to top-k lists
Run it, then try raising the event rate or reducing the stream's partitions, and watch which stage saturates first. The partition count caps the number of aggregators that can work in parallel.
The write path: the event API appends each event to the stream, keyed by item id. Aggregators read their partitions, add one to the item's counter in the current minute's bucket and to its window total.
The read path: every minute each aggregator emits its local top candidates, a merger combines them into the global top-K and replaces one value in Redis. The user-facing read is a single GET.
The interesting problem: top-K over a sliding window
Approach A: one global sorted set
Send every event to a Redis sorted set with ZINCRBY, and read the top ten with ZREVRANGE.
Good: four lines of code, and Redis keeps the order for you.
Bad: 100,000 increments per second on one key is one node's throughput limit, which is the hot-key problem from the distributed counter. There is also no window: old events never leave, so you must schedule decrements for each event an hour later, which doubles the write load and needs the events stored somewhere.
Approach B: partition by item, bucketed windows, merge local top-Ks
Partition events by item id across 12 workers. Each worker keeps a ring of 60 one-minute buckets (a map of item to count per minute) and a running total per item. Each minute:
- Drop the oldest bucket, and subtract its counts from the totals. The cost is proportional to the distinct items in that bucket, not to the window.
- Scan the totals, keeping a min-heap of size K, to find the worker's local top-K (about 4 million entries per worker, well under a second).
- Publish that local list. A merger takes the 12 lists of 10, sorts 120 entries and writes the global top 10.
Why the merge is exact: every item lives on exactly one worker, so a worker's count for its items is the true count. The global top 10 must be within the union of the workers' local top 10s, because an item beaten by ten items on its own worker cannot be in the global ten. (Had we partitioned by event randomly, an item's count would be split over workers and the merge would be wrong.)
Good: exact, memory-bounded by the window, and a sliding update costs one bucket's worth of work per minute. The slide granularity is one minute, which matches the refresh requirement.
Bad: memory grows with the number of distinct items in the window (800 MB per worker here), and a hot item still lands on a single partition, though a worker can handle 100,000 increments per second on an in-memory map.
Approach C: approximate with sketches
When distinct items are too many to count exactly, use a Count-Min sketch (a grid of counters indexed by several hash functions) to estimate each item's count, plus a small heap of the current heavy hitters (the Space-Saving algorithm works this way).
Good: memory is fixed (33 MB for the 60 buckets in our example) regardless of how many distinct items appear. Updates are constant time.
Bad: it overestimates (hash collisions only add), by up to ε × N, so items near the cutoff may be misordered. A sketch cannot be "un-added", so a sliding window needs one sketch per bucket, summed on query.
Diagram, as text
- Events by item id leads to Worker 1: buckets + local top K
- Events by item id leads to Worker 2: buckets + local top K
- Events by item id leads to Worker 3: buckets + local top K
- Worker 1: buckets + local top K leads to Merge lists
- Worker 2: buckets + local top K leads to Merge lists
- Worker 3: buckets + local top K leads to Merge lists
- Merge lists leads to Redis: global top K
The recommended answer is B at this scale, with C when the keyspace multiplies. Say the flip point out loud: exact counting costs 32 bytes per item per bucket, so it breaks when segments multiply the item count by hundreds. That sentence shows you did the arithmetic rather than assuming sketches are always better.
The second decision: popular is not trending
The top ten by raw count are nearly the same items every hour, the biggest creators or the most common hashtags. Users asking for "trending" want what is rising.
- Count only: simple, stable and boring. It answers "most popular."
- Growth ratio: score = (events in the last 10 minutes) ÷ (the item's baseline rate, for example its average over the previous week). Large and steady items score near 1, and an item that jumps 40× scores 40.
- Smoothed ratio: add a constant to the denominator,
recent ÷ (baseline + c), so a brand-new item with a baseline of zero does not get an infinite score from three views, and require a minimum count (for example 500 events) to qualify.
A good answer tracks two windows per item, a short one (10 minutes) and a long baseline (a week, stored coarsely, for instance one number per hour), and ranks by the smoothed ratio. State the effect: raw counts favor incumbents, ratios favor novelty, and ratios need a floor so noise does not win. Spam and coordinated bot traffic exploit ratio ranking easily, so mention that you would require a number of distinct users, not only events, before an item can trend.
Bottlenecks and failures
A worker crashes. Its in-memory counts are gone. Checkpoint each worker's state periodically (every few minutes, to object storage) together with the stream offset it had reached. On restart, load the checkpoint and replay the stream from that offset, which rebuilds the state exactly with no double counting.
Late and out-of-order events. Events arrive after their minute has passed. Assign each to its event-time bucket and accept events up to a lateness bound (say two minutes), using a watermark as described in the stream processing lesson. Later ones are dropped or sent to a side channel.
A hot item. One viral item can receive a large share of the 300,000 per second. The worker that owns it does an in-memory increment per event, which is fine, but that partition's consumer lag can grow. Pre-aggregate in the producer or at the event API, batching increments for the same item over a few hundred milliseconds into one message.
The merger fails. Redis keeps the previous list, which is a minute stale. Run two mergers and let the last writer win with a version number, so the list never regresses.
What if the stream lags by ten minutes? Show the last list with its timestamp, not nothing. A "trending" list that is ten minutes old is still better than an empty box.
Trade-offs to name aloud
- Exact over approximate: about 800 MB per worker, in exchange for correct ordering of close items.
- One-minute buckets: a list that slides in minute steps, in exchange for cheap updates and expiry.
- Partition by item: exact merging, in exchange for exposure to a hot item on one partition.
- Ratio ranking over raw counts: surfaces novelty, at the price of tuning smoothing and floors, and of gaming by bots.
- Checkpoint plus replay: recovery in minutes, in exchange for periodic checkpoint cost.
What interviewers listen for
- A working answer: events into a stream, counters per item, a window and a sorted top-K served from a cache.
- A strong answer: buckets for the sliding window, partitions by item so the merge of local top-Ks is exact, with memory estimated per worker.
- A standout answer: also names Count-Min plus heavy-hitter structures, says when exact counting stops fitting, distinguishes trending from popular with a smoothed growth ratio, and recovers from crashes with checkpoints and replay.
Check your understanding
Common mistakes
One sorted set for everything. It is the first answer and a hot key by 100,000 writes per second. Say the number and move on.
Partitioning events randomly. Then no worker has an item's whole count, and merging local top-Ks silently gives wrong answers.
Using sketches without checking the sizes. If exact counts fit in 800 MB per worker, a sketch is needless complexity. Do the arithmetic first.
Mixing up popular and trending. The interviewer asked for rising items. If your list is the biggest creators, you answered a different question.
No recovery story. In-memory counts disappear with the process. Checkpoints with offsets, then replay, are the answer.
Practice
Product wants top-10 per country (200 countries) and per category (50 categories), a total of 250 segments, each over the same hour. What happens to your memory estimate, and what do you do?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Multiply the keyspace, then decide which segments really need exact counts.
Show a strong answer
Multiply it out. In the worst case every item in a minute appears in every segment: 5 million × 250 = 1.25 billion counters per bucket, at 32 bytes each 40 GB per bucket, and 2.4 TB for 60 buckets, against 9.6 GB for the single list. Real traffic is sparser (an item is rarely active in all 200 countries), but the long tail of small segments still multiplies counters.
Count only what can qualify. For most segments, a handful of items can reach the top ten. Keep exact counters only above a small threshold, and use a Count-Min sketch for the tail. A sketch per segment per bucket at 544 KB is 250 × 60 × 544 KB ≈ 8.2 GB for the whole window, about 300 times smaller than the worst case.
Keep heavy hitters exactly. Track the sketch's current top candidates (a few hundred per segment) with exact counters, so the visible top ten is accurate while the long tail is approximate.
Route events carefully. Partition by item id as before and fan each event out to the segments it belongs to (country, category) inside the worker, so the merge argument still holds per segment.
The pattern worth keeping: when the keyspace multiplies, spend exact memory only on the few keys that can win, and approximate the rest.
An aggregator crashes and restarts. How do you recover its counts without double counting or losing events?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Recovery needs both a snapshot of the state and a way to resume the input at the matching place.
Show a strong answer
Snapshot the state with its input position. Every few minutes, a worker writes its bucket ring and totals to durable storage together with the stream offset of the last event included. The state and the offset are saved as one unit, so they always agree.
On restart, load the snapshot and start reading the stream from the saved offset. Events after the snapshot are replayed in order and rebuild the counts exactly, because the snapshot contains none of them.
Handle the gap. The list shown to users is stale until the worker catches up. With a replay rate many times faster than live traffic, a few minutes of backlog takes seconds. Keep serving the last published list in the meantime.
Make the output idempotent. The merger writes a versioned list, so a restarted worker that republishes an old result cannot overwrite a newer one.
The pattern worth keeping: durable state plus a replayable input and a stored position gives exact recovery without distributed transactions.
Key takeaways
- Partition by item id so each item's count is complete on one worker, and local top-Ks merge exactly.
- Slide the window with one-minute buckets, subtracting the oldest instead of recounting.
- Check whether exact counts fit (about 800 MB per worker here) before reaching for a sketch.
- Count-Min sketches only overcount, and cost fixed memory when the keyspace explodes.
- Popular is not trending: rank by a smoothed ratio to a baseline, with a minimum volume.
- Recover with checkpoints plus replay, not by trusting memory.
Further reading
- G. Cormode and S. Muthukrishnan, "An Improved Data Stream Summary: The Count-Min Sketch and its Applications", Journal of Algorithms (2005).
- A. Metwally, D. Agrawal and A. El Abbadi, "Efficient Computation of Frequent and Top-k Elements in Data Streams", ICDT (2005): the Space-Saving algorithm.
- T. Akidau et al., "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing", VLDB (2015).