Design: top-K and heavy hitters

In one sentence

Count events per item in time buckets, keep a size-K heap over the counts, and sum buckets for sliding windows; switch to a count-min sketch when exact per-item counters stop fitting in memory.

Each shard owns the full counts of its items and keeps a local top K over the last 60 minute buckets; a merger builds the global list that the API reads from cache.

How it works

  • Count per item in 1-minute buckets; a sliding hour is the sum of the last 60.
  • A size-K min-heap over the counts keeps the top K; reads hit a precomputed, cached list.
  • Exact needs a counter per distinct item; a count-min sketch uses fixed memory and only overcounts.
  • Partition by item so each count lives on one shard: merging local top-K lists is then exact.
  • Otherwise an item just below the cut on every shard can be first overall.

Check yourself

Answer to mark it learned; your answers aren't scored.

View events are load-balanced round robin across 20 counting servers. Each reports its local top 10 and you merge the lists into a global top 10. QA finds that the video with the highest total views is missing. What is the cause, and the fix?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: return the K most frequent items (videos, hashtags, search queries) over the last hour or day, K up to ~1,000, optionally per country. Non-functional: results at most about a minute stale; a read is a lookup, not a scan; and a stated accuracy contract: exact counts, or approximate with a known error.

Scale (assumed): 1B events/hour ≈ 278k/s over 50M distinct items.

Questions I'd ask:

  1. Exact or approximate? A trending widget and a royalty payment have different answers.
  2. Which windows: last hour, last day, all time? Sliding, or calendar periods?
  3. Which dimensions? Each one multiplies the state.

API and data model

GET /top?window=1h&k=100&country=MX → [(item, count)]. Internally: counts per (item, minute bucket) and one precomputed list per window, refreshed every minute and cached.

Architecture

  1. Events land in Kafka partitioned by item id, so all events for an item meet in one partition.
  2. A stream job counts per item in 1-minute buckets (Stream processing: windows, watermarks, state) and keeps a local top list per partition with a size-K min-heap (Heaps and top-K).
  3. A merger combines the per-partition lists into the global top K for each window and writes it to a cache; the API only reads the cache.
  4. Longer windows sum buckets: the last hour is the last 60 minute buckets.

The hard parts

  1. Memory: exact counting needs a counter per distinct item per bucket; a count-min sketch plus a heap runs in fixed memory (Probabilistic data structures).
  2. Sliding windows: old events must leave the count.
  3. Merging shards: local top-K lists only merge exactly when each item lives on one shard.
Code Approximate top-K: count-min sketch plus candidates
pythonApproximate top-K: count-min sketch plus candidates
import hashlib, heapq, math

class TopK:
    """Approximate heavy hitters: a count-min sketch for counts, K candidates beside it."""
    def __init__(self, k: int, eps: float = 1e-5, delta: float = 0.01):
        self.k = k
        self.w = math.ceil(math.e / eps)          # overcount <= eps * N ...
        self.d = math.ceil(math.log(1 / delta))   # ... with probability 1 - delta
        self.rows = [[0] * self.w for _ in range(self.d)]
        self.top: dict[str, int] = {}             # the answer: candidate -> estimate

    def _cells(self, item: str):
        h = hashlib.blake2b(item.encode(), digest_size=16).digest()
        h1, h2 = int.from_bytes(h[:8], "big"), int.from_bytes(h[8:], "big") | 1
        return [(r, (h1 + r * h2) % self.w) for r in range(self.d)]

    def estimate(self, item: str) -> int:
        return min(self.rows[r][c] for r, c in self._cells(item))   # never undercounts

    def add(self, item: str, n: int = 1) -> None:
        for r, c in self._cells(item):
            self.rows[r][c] += n
        self.top[item] = self.estimate(item)
        if len(self.top) > self.k:                # evict the weakest candidate
            del self.top[min(self.top, key=self.top.get)]   # a min-heap in production

    def merge(self, other: "TopK") -> None:       # same w, d and hash functions
        for mine, theirs in zip(self.rows, other.rows):
            for i, v in enumerate(theirs):
                mine[i] += v                      # sketches add cell by cell
        cands = set(self.top) | set(other.top)    # re-score both candidate lists
        best = heapq.nlargest(self.k, cands, key=self.estimate)
        self.top = {x: self.estimate(x) for x in best}
Real example

Trending hashtags over the last hour, K = 100, with 1B events and 50M distinct tags (assumed). Exact: 50M counters × ~100 B each (also assumed) ≈ 5 GB per window, more with minute buckets. Approximate: suppose the 100th tag has 0.01% of traffic, 100k events. Pick ε = 0.00001 so the overcount stays under ε·N = 10k, 10% of that count. The sketch is ⌈e/ε⌉ = 271,829 counters × 5 rows × 8 B ≈ 11 MB per bucket, ~650 MB for 60 minute buckets, however many tags exist.

Trade-offs +3 · −3

+ You gain

  • Reads are a cache lookup of a precomputed list, whatever the event volume.
  • Minute buckets serve many windows (5 minutes, 1 hour, 24 hours) from one set of counts.
  • Sketches have a fixed size and merge by addition across shards and buckets.

− You pay

  • Exact counting holds a counter per distinct item per bucket; the long tail dominates memory.
  • Sketch counts only overcount and are noise for rare items: fine for ranking, wrong for billing.
  • Every extra dimension (country, category) multiplies the state.

Use it when

Trending and most-popular lists over large streams: top videos, hashtags, search queries, products; also finding noisy API clients or hot keys.

Avoid it when

If the counts already sit in a database or OLAP store at modest scale, ORDER BY count DESC LIMIT k is enough. Don't use sketches where the count itself is billed or audited.

Numbers to know 5
  • Assumed: 1B events/hour ≈ 278k/s over 50M distinct items.
  • Space-Saving with m counters keeps every item above N/m occurrences; a count is at most N/m too high.
  • Count-min: w = ⌈e/ε⌉, d = ⌈ln(1/δ)⌉. With ε = 0.00001 and δ = 1%: 271,829 × 5 counters ≈ 11 MB at 8 B each.
  • Exact: 50M distinct items × ~100 B (assumed) ≈ 5 GB per window.
  • Elasticsearch shard_size default: size × 1.5 + 10 terms per shard (checked Nov 2026).
Common pitfalls 4
  • Merging per-shard top-K lists when items are spread across shards: the global #1 can be missing from every list.
  • Sizing the sketch from total volume instead of the K-th item's share: collisions lift tail items into the top.
  • Ranking "trending" by raw count: the same evergreen items win forever. Rank by growth against a baseline.
  • A tumbling window behind a "last hour" feature: the list empties at every hour boundary.
Interview questions 3

Answer out loud first, then reveal.

You have 100 counting servers. Can you just merge their top-100 lists?Show answer

Only if each item's count lives on one server. If events are partitioned by item id, the global top 100 is inside the union of the local top 100s, so the merge is exact. If events are spread by user or region, an item ranked 101st everywhere can be first overall. Then I repartition by item before counting, or merge full counts or sketches. Over-fetching, like Elasticsearch's shard_size, only shrinks the error.

Exact or approximate: how do you choose?Show answer

I ask what the number is used for and how many distinct items there are. Exact is a hash map plus a heap: it is right and it shards by item, so I keep it while the keys fit. For a trending widget over hundreds of millions of items, a count-min sketch plus a heap gives fixed memory and an overcount bounded by ε·N. I size ε from the K-th item's share, and I never bill from it.

How do you make the window slide?Show answer

I don't track when each event expires. I keep 60 one-minute buckets of counts or sketches, and the last hour is their sum. Every minute I add the new bucket and drop the oldest, so the window is accurate to one bucket. Sketches add cell by cell, so this also works approximately. For longer windows I roll minutes up into hours to keep the number of buckets small.

Deep dive 3

Exact vs approximate counting

Exact: a hash map from item to count per bucket, in the stream job's state, plus a heap. It is correct, it shards by item, and it costs a counter per distinct item per bucket: the long tail of items seen once dominates memory. Approximate: a count-min sketch gives each item an estimate that is never low and at most ε·N high (with probability 1−δ); a heap keeps the K best estimates. Size ε from the K-th item's share of traffic, not from N, or collisions push tail items into the list. Space-Saving (Metwally et al., 2005) is the counter-based alternative: m counters, and a new item replaces the smallest one and inherits its count plus one, so any item with more than N/m occurrences is always kept. Redis TOPK uses HeavyKeeper: decaying counts plus a min-heap.

Sliding vs tumbling windows

A tumbling window (each calendar hour) is cheap: one set of counts, dropped when the hour closes. But "this hour" is nearly empty at 10:01. A true sliding window would have to expire every event individually, which means storing all of them. The standard compromise is buckets: keep 60 one-minute buckets, answer "last hour" by summing them, and each minute add the newest and drop the oldest. The window is then accurate to one bucket. Sketches add cell by cell, so the same trick works for approximate counts. Roll minutes up into hours for a 24-hour or 7-day window. For trending, rank by growth against the item's own baseline, not by raw count, or the same evergreen items win forever.

Merging shards: why local top K is not enough

If events are routed by user, region or round robin, each item's count is split across shards. Then item X can sit just below the cut on every shard, appear in no local top K, and still have the largest total. No fixed over-fetch removes this in general. Three ways out. Partition by item: each shard holds the full count of its items, so the global top K is inside the union of local top Ks and the merge is exact. Over-fetch and accept an error: Elasticsearch's terms aggregation asks each shard for size × 1.5 + 10 terms by default and reports an error bound. Merge counts, not lists: sum full count maps or sketches, then take the top K. One hot item can still overload its shard: pre-aggregate upstream before partitioning by item.