← Data structures

Count-Min sketch

Hashing and probabilistic sketches

A small grid of counters with d rows and w columns, where each row has its own hash function; an item increments one counter per row and its frequency estimate is the minimum of those d counters. It exists because keeping an exact count per item over a stream of billions of distinct keys needs a counter for every key, and the sketch needs a fixed few tens of kilobytes while never under-counting.

What it costs

OperationCostNote
Increment itemO(d): d hashes, d counter incrementsd is typically 4–7 rows. All d counters for the item go up by the amount.
Estimate frequencyO(d): d hashes, d reads, 1 minNever below the true count; above it by at most ε·N with probability 1 − δ.
Merge two sketchesO(d·w): element-wise addSame dimensions and hashes required. Lets shards and time windows combine.
Top-k heavy hittersO(d) per item + O(log k) heap updatePair the sketch with a k-entry min-heap of (item, estimate).

Memory: d × w counters: width w = e/ε and depth d = ln(1/δ). For ε = 0.001 (error ≤ 0.1% of total count) and δ = 1% that is 2,719 × 5 = 13,595 counters; at 4 bytes each about 54 KB, independent of how many distinct items appear.

d rows of counters, one hash per row, estimate = minimum

Each row hashes the item to a different column and increments it. Other items collide into some of those cells and inflate them; taking the minimum across rows removes most of the inflation and never goes below the truth.

How it works

  1. Choose the error bound ε (how far an estimate may exceed the truth, as a fraction of the total count N) and the failure probability δ (how often the bound may be exceeded). Width w = ceil(e / ε) and depth d = ceil(ln(1 / δ)). ε = 0.001, δ = 0.01 gives w = 2,719 and d = 5.
  2. Allocate a d × w grid of integer counters, all zero, and d independent hash functions, one per row.
  3. To count an occurrence of item x, compute row 0’s hash of x mod w and increment that counter; do the same for rows 1 to d − 1. Five hashes, five increments.
  4. To estimate how often x appeared, read the same five counters and return the smallest. Each counter holds x’s true count plus whatever other items collided into that cell, so every counter is at least the truth. Taking the minimum picks the row where x had the least collision noise.
  5. The guarantee: the estimate is never below the true count, and with probability at least 1 − δ it is at most the true count plus ε·N. Over-counting is the only error, and it is bounded by a fraction of total traffic, not by how many distinct items exist.

Why several rows instead of one wide row

  • One row is a hash table of counters with collisions adding up: a popular item’s neighbours in the row all look popular. A second row uses a different hash, so x collides with different items there. The minimum across rows discards the worst collisions; each extra row makes it exponentially less likely that every row is unlucky at once.

Worked example

Top referrers per short link

  • 345M clicks per day; each carries a referrer domain. The product wants the top 10 referrers per alias and an approximate count for each, without storing a counter per (alias, referrer) pair, of which there are hundreds of millions.
  • Sketch per alias per day: w = 2,000, d = 5, 4-byte counters: 40 KB. Error bound ε = e/2,000 ≈ 0.14% of that alias’s total clicks, exceeded with probability under 1%.
  • A click on alias aB3xZ9 from "news.ycombinator.com": hash it five ways to columns 1,204, 88, 1,999, 517 and 1,340; increment those five counters. Five hashes and five adds, under 100 ns.
  • Estimate for "news.ycombinator.com" after 1,000,000 clicks: the five counters read 41,230, 40,998, 42,105, 40,991 and 41,460. True count is 40,950. The minimum, 40,991, over-counts by 41, well inside the bound of 0.14% × 1,000,000 = 1,400.
  • Top 10: keep a 10-entry min-heap of (referrer, estimate). On each click, estimate the referrer; if it beats the heap’s smallest, replace it. The heap plus sketch is 40 KB and a few hundred bytes versus hundreds of thousands of exact counters for an alias with many distinct referrers.
  • Daily sketches add element-wise into a monthly sketch, so monthly top referrers need no re-scan of clicks.

When it is the wrong choice

  • You need counts for a known, small set of items: a plain hash map of counters is exact and barely larger.
  • Under-counting would be acceptable but over-counting is not (a limit that must never block a legitimate client): the sketch only ever over-counts, so it can produce false limit hits. Use it to find suspects, then confirm with an exact counter.
  • The distribution is flat with no heavy hitters: every item’s estimate is dominated by collision noise, and the sketch tells you little. It shines when a few items account for most of the traffic.
  • You need to list all items seen: the sketch stores counters, not keys. Pair it with a heap for the top k, or keep keys elsewhere.

Interviewer follow-ups

Answer out loud before you open each one.

Why does the sketch never under-count?

Every occurrence of x increments all d of its counters, and counters are never decremented. Each of x’s counters therefore holds x’s true count plus non-negative collision noise from other items. The minimum of numbers that are each at least the truth is at least the truth.

How do you size the width and depth?

Width controls the error: w = e/ε, so for an over-count of at most 0.1% of total traffic you need about 2,719 columns. Depth controls confidence: d = ln(1/δ), so 5 rows give a 99% chance the bound holds. Memory is d × w counters; doubling width halves the error, adding a row squares the failure probability down.

How does this give top-k, which a sketch alone cannot?

Keep a small min-heap of the k current leaders alongside the sketch. For each incoming item, query its estimate; if it exceeds the heap’s smallest estimate, pop that and push the new item. The heap holds keys, the sketch holds counts, and together they track heavy hitters in O(d + log k) per item.

When would you pick Count-Min over just INCR in Redis?

INCR per key is exact and fine when the key space is bounded, say a few million known items. When keys are unbounded and mostly rare (every distinct referrer URL, every source IP in an attack), a counter per key grows without limit; a 50 KB sketch gives the top items and their approximate counts at any scale.

Where it shows up

Building blocks
Count big things with small memory · Limit requests per client · Rank instead of sorting by time · Compute over events as they arrive · Catch spam and abuse · Spread a hot key
Problems
URL Shortener (TinyURL / bit.ly) · News Feed (Twitter / X timeline) · Distributed Rate Limiter