Part 4 of 12 · Data Structures

How do you find the top 10 among billions of events?

Counting every key exactly took 58-149 MiB for 5 million keys. A count-min sketch with a small heap found the true top 10 in 2 MiB; Space-Saving did it in 62 KiB. With too few counters on flatter traffic, Space-Saving found only 2 of the 10. Measured, and when each one is safe.

An illustration of a gold trophy cup, for the top 10

Short answer: the verdict, as the measurements will show: if the number of distinct keys fits in memory, count them exactly. When it doesn’t (streams of IPs, search queries, product views), use Space-Saving with a few hundred to a few thousand counters, or a count-min sketch plus a small heap. Both found the true top 10 out of 5 million keys in kilobytes to megabytes. Size them for your flattest traffic: when popularity is spread out, a small sketch returns confident-looking wrong answers.

Here’s the case. A stream of events pours in, far too many distinct keys to keep, and someone asks a simple question: who are the top 10? What delights me about this problem is how little you need to remember to answer it well. A few kilobytes can stand in for millions of keys, as long as you understand exactly where the shortcut stops being safe. And there’s a twist in this one: on the wrong kind of traffic, one of our heroes quietly names the wrong culprits. (Its cousin, counting distinct keys, is in the HyperLogLog post.)

The code is in systems-data-structures (Go, standard library only).

Case file

The case Too many distinct keys to keep, and someone asks for the top 10
Suspects Exact map + sort, count-min sketch + heap, Space-Saving
Culprit Too few Space-Saving counters on flatter traffic: plausible output, only 2 of the true 10
The fix At least 10× more counters than the k you report, sized for your flattest traffic
Evidence 20 million events over 5 million keys, Go code in systems-data-structures

The three detectives #

  • Exact map + sort: count every key; sort at the end. Perfect, but memory grows with distinct keys.
  • Count-min sketch + heap (Cormode and Muthukrishnan’s design): a grid of counters, depth rows × width columns. Each key increments one counter per row (chosen by a hash); its estimate is the minimum of those counters. It never undercounts, and overcounts by at most about e/width of the total with high probability. A min-heap keeps the 10 keys with the highest estimates. Taking the minimum is the key insight, and a lovely one: collisions can only add, so the least-inflated counter is the most honest witness.
  • Space-Saving (Metwally et al., 2005): keep exactly k counters. A new key, when all are taken, replaces the key with the smallest count and inherits that count plus one. Any key that occurs more than N/k times is guaranteed to be kept, and each counter knows how much of its count might be inherited. I like how modest it is: it’s frank about how much it might be wrong.
Flowchart: Event for key X, X already has a counter?, Add one to its count, Fewer than k counters in use?, New counter for X, count 1, Replace the key with the smallest count, X inherits that count plus one, recorded as possible errorFlowchart: Event for key X, X already has a counter?, Add one to its count, Fewer than k counters in use?, New counter for X, count 1, Replace the key with the smallest count, X inherits that count plus one, recorded as possible error
Diagram source
flowchart TD
  E["Event for key X"] --> K{"X already has a counter?"}
  K -- yes --> I["Add one to its count"]
  K -- no --> F{"Fewer than k counters in use?"}
  F -- yes --> N["New counter for X, count 1"]
  F -- no --> R["Replace the key with the smallest count"]
  R --> H["X inherits that count plus one, recorded as possible error"]

The evidence: 20 million events over 5 million distinct keys #

Very skewed traffic (Zipf s = 1.1; the 10th key appears 188,323 times) #

Method Memory ns per event True top 10 found Worst count error*
Exact map ~58 MiB 46 10 0
Count-min, width 4,096 × 4 129 KiB 61 10 0.7%
Count-min, width 65,536 × 4 2.0 MiB 66 10 0.0%
Space-Saving, 100 counters 6 KiB 117 10 0.0%
Space-Saving, 1,000 counters 62 KiB 112 10 0.0%

On skewed traffic, everyone solves the case. Even 100 Space-Saving counters, in 6 KiB, name the true top 10.

Flatter traffic (Zipf s = 0.8; the 10th key appears 29,935 times) #

Method Memory ns per event True top 10 found Worst count error*
Exact map ~149 MiB 116 10 0
Count-min, width 4,096 × 4 129 KiB 64 10 13.6%
Count-min, width 65,536 × 4 2.0 MiB 79 10 0.8%
Space-Saving, 100 counters 6 KiB 186 2 668%
Space-Saving, 1,000 counters 62 KiB 225 10 0.0%

*Largest difference between a reported count and the true count, as a percentage of the true 10th count.

Chart: True top 10 found, flatter traffic (Zipf s = 0.8)Chart: True top 10 found, flatter traffic (Zipf s = 0.8)
Diagram source
xychart-beta
  title "True top 10 found, flatter traffic (Zipf s = 0.8)"
  x-axis ["Exact map", "Count-min 4,096", "Count-min 65,536", "Space-Saving 100", "Space-Saving 1,000"]
  y-axis "of the true top 10"
  bar [10 , 10 , 10 , 2 , 10]

And there’s the twist: the same small Space-Saving now finds only 2 of the true top 10, with counts off by 668%.

The reveal: why the small Space-Saving failed #

This is the most instructive row in the tables, so it’s worth slowing down for.

Space-Saving’s guarantee covers keys with more than N/k occurrences. With 20 million events and 100 counters, that’s 200,000. On skewed traffic the top 10 all exceed it, so they’re found. On flatter traffic the 10th key appears only 29,935 times, below the guarantee, and the long tail keeps churning through the counters, each newcomer inheriting a large count. The result looks plausible and is wrong. That’s what makes it a proper red herring: nothing about the output warns you.

The fix is cheap: 1,000 counters (62 KiB) lowered the threshold to 20,000 and found all 10. Better still, Space-Saving can tell you which answers are guaranteed (count minus inherited error), so you can flag the uncertain ones. The algorithm carries its own alibi checker.

Where the same solution applies #

Question What I’d use
Trending hashtags or search terms per minute Space-Saving per time window, a few thousand counters; merge windows for longer periods
Noisiest API clients or IPs for rate limiting and abuse Count-min sketch for “how many requests has this client made?” plus a heap for the top offenders; the sketch answers point queries for any client, Space-Saving doesn’t
Hot keys in a cache or database Space-Saving on a sample of requests; Redis has redis-cli --hotkeys (with an LFU policy)
Exact top sellers for a report A GROUP BY ... ORDER BY count DESC LIMIT 10 in the database: exact and cheap enough for daily reports

Remember this

  • Count exactly whenever the distinct keys fit in memory.
  • Space-Saving only guarantees keys above N/k: size it for your flattest traffic.
  • A small sketch can return confident-looking wrong answers.

Case closed: what I’d do by default #

  1. Count exactly if distinct keys fit in memory or the database can do it.
  2. Space-Saving with at least 10× more counters than the k you report, more for flat traffic; report which results are guaranteed.
  3. Count-min sketch when you also need “how often did X occur?” for arbitrary keys.
  4. Test on your flattest day, not your most skewed.

I have a soft spot for algorithms that trade a little certainty for an enormous saving in memory, and then tell you honestly what they gave up. Size them with care and they’ll find your top 10 in the space of a small image.

Measured Nov 2026 with Go 1.27 on a laptop (Intel i7-8550U). Found counts and errors come from seeded streams and repeat exactly; nanoseconds depend on the machine. Code and full results: systems-data-structures.

Like (sign in first) 0 likes 💬 0

Written by

Vishal Kumar

Associate Director at CapGrid, running product and engineering in a CPTO capacity. 10+ years building distributed, multi-tenant SaaS and AI platforms. AWS Certified Solutions Architect - Professional. Based in Gurugram.

Comments

No comments yet.

Sign in to comment. We'll email you a link; no password needed.