Scrivio Interview library
InternalsIntermediate7 min read · updated 13 November 2026

A Count-Min Sketch estimates how often items occur in a stream using a small, fixed amount of memory. It is used for heavy-hitter detection, per-key rate limiting and cache admission policies.

How does a Count-Min Sketch work, why does it only ever overestimate, how do its width and depth set the error, and how do you combine sketches computed on 50 pods?

A Count-Min Sketch is a table of d rows by w counters, each row with its own hash function: adding an item increments one counter in every row, and a query returns the minimum of the item's d counters. Collisions can only add to a counter, so estimates never go below the true count, and the minimum keeps the error smallest. With w = ceil(e / epsilon) and d = ceil(ln(1 / delta)), an estimate exceeds the truth by more than epsilon times the total count with probability at most delta, and sketches with the same dimensions and hash functions merge by adding counters cell by cell, so 50 pods each keep one and a collector sums them.

Why this question is asked

Counting how often each item occurs is easy with a hash map until the stream has hundreds of millions of distinct keys: user ids, IP addresses, URLs. A Count-Min Sketch gives approximate counts in a fixed amount of memory, a few hundred kilobytes, no matter how many distinct items pass through. It powers heavy-hitter detection, per-key rate limiting and cache admission policies such as the TinyLFU policy used by Caffeine. Interviewers ask about it to test whether we understand why it errs in one direction and how its parameters control the error. In this answer, we will look at the structure, implement it, see why it only overestimates, size it from epsilon and delta, merge sketches from 50 pods and look at its weaknesses.

1The Structure: d Rows of w Counters

The sketch is a two-dimensional array of counters with d rows and w columns. Each row has its own hash function that maps an item to one column. To add an item, we hash it once per row and increment one counter in every row, so each addition touches exactly d counters. To estimate an item's count, we look at the same d counters and return the smallest.

Memory is fixed at d x w counters and does not grow with the number of distinct items, which is the whole point.

2A Small Implementation

As in a Bloom filter, we can derive the d row hashes from one 128-bit hash by double hashing, so each operation computes a single hash.

Java
public final class CountMinSketch {
private final int w, d;
private final long[][] counts;
private long total;
public CountMinSketch(double epsilon, double delta) {
this.w = (int) Math.ceil(Math.E / epsilon); // epsilon 0.001 -> 2,719
this.d = (int) Math.ceil(Math.log(1 / delta)); // delta 0.01 -> 5
this.counts = new long[d][w];
}
public void add(String item, long n) {
long[] h = hash128(item); // two 64-bit halves of Murmur3
for (int row = 0; row < d; row++) counts[row][col(h, row)] += n;
total += n;
}
public long estimate(String item) {
long[] h = hash128(item);
long min = Long.MAX_VALUE;
for (int row = 0; row < d; row++) min = Math.min(min, counts[row][col(h, row)]);
return min; // never below the true count
}
private int col(long[] h, int row) { return (int) Math.floorMod(h[0] + row * h[1], (long) w); }
}

The hash128 helper is the same as in a Bloom filter, for example the two halves of Guava's murmur3_128 hash.

3Why It Only Ever Overestimates

Every time our item is added, all d of its counters go up, so each of them is at least its true count. Other items may hash to the same counter in a row and add to it too, which can only push that counter higher. Nothing ever decreases a counter. So every one of the item's d counters is greater than or equal to the true count, and the minimum of them is too: the estimate is never below the truth.

Taking the minimum is how the sketch fights collisions. Each row uses a different hash function, so an item that collides with a heavy item in one row is unlikely to collide with heavy items in all rows. The row with the fewest collisions gives the smallest, most accurate counter, and the minimum picks exactly that one.

Estimating "user-42" (true count 1,000)
RowCounter valueWhy
01,412shares the counter with a busy item
11,003a few rare items collide
21,086a moderate collision
31,251collides with a busy item
41,019small collision
The estimate is the minimum, 1,003: only 3 too high.

4How Width and Depth Set the Error

The guarantee has two parameters. Epsilon controls how large an error is: with w = ceil(e / epsilon) columns, where e is about 2.718, the expected collision mass in a row is at most epsilon times the total count. Delta controls how likely a large error is: with d = ceil(ln(1 / delta)) rows, the estimate exceeds the true count by more than epsilon x total with probability at most delta. In short, width buys accuracy and depth buys confidence.

For epsilon = 0.001 and delta = 0.01, w = ceil(2.718 / 0.001) = 2,719 and d = ceil(ln 100) = ceil(4.6) = 5, so 2,719 x 5 = 13,595 counters, about 109 KB with long counters. If the stream contains 10 million events, the error bound is 0.001 x 10,000,000 = 10,000: with 99 percent probability, any item's estimate is at most 10,000 above its true count. Notice that the bound is relative to the total, not to the item.

5Merging Sketches From 50 Pods

Sketches merge easily. If two sketches have the same w, the same d and the same hash functions, then the counter at row r, column c in each sketch counts the same items, so adding the two counters gives exactly the counter a single sketch would have had for both streams. Merging is cell-by-cell addition.

Java
public void merge(CountMinSketch other) {
if (other.w != w || other.d != d) throw new IllegalArgumentException("different dimensions");
for (int row = 0; row < d; row++)
for (int c = 0; c < w; c++) counts[row][c] += other.counts[row][c];
total += other.total;
}
// 50 pods x 13,595 counters: about 5.4 MB per collection round, summed into one sketch
Step throughFleet-wide heavy hitters every minute
  1. Each pod adds events to its own sketchsame w, d and hash seeds
  2. Pods ship sketches to the collectorabout 109 KB each
  3. Collector adds counters cell by cellone fleet-wide sketch
  4. Check candidate keys against the merged sketchtop-k heap per pod
  5. Publish heavy hitters, reset for next minute

5 steps in order. Play them, or step through them one at a time.

So each of the 50 pods keeps its own sketch for the current interval, say one minute, and ships it to a collector, which sums them into one sketch for the whole fleet. The hash functions must be identical everywhere, so the seeds are fixed in configuration, never random per pod. The merged sketch's error bound is relative to the merged total.

6Weaknesses and Common Improvements

Because the error is relative to the total stream size, rare items get poor estimates. In a stream of 10 million events, an item seen 50 times may be estimated at anything from 50 up to about 10,050, so the sketch is excellent for finding heavy items and useless for comparing rare ones.

A sketch also cannot list its items; it can only answer questions about an item we name. To find the top items, we pair it with a small heap of candidates: when an item is added, we estimate its count, and if that is larger than the smallest count in the heap, the item goes into the heap. Finally, conservative update reduces overestimation: when adding an item, instead of incrementing all d counters, we raise each counter only as far as the new estimate (the current minimum plus the increment), leaving counters that are already higher untouched. Estimates become tighter, though merging and decrementing become less straightforward.

7Follow-up questions

How does Caffeine use a Count-Min Sketch?

Its TinyLFU admission policy keeps a compact frequency sketch of recent accesses and only admits a new entry into the cache if its estimated frequency is higher than that of the entry it would evict. The counters are periodically halved so that old popularity fades.

8Conclusion

In this answer, we saw that a Count-Min Sketch keeps d rows of w counters, increments one counter per row for each item and answers with the minimum of the item's counters. Since collisions only add, estimates never fall below the true count, and the minimum picks the least polluted row. Width w = ceil(e / epsilon) sets the size of the error and depth d = ceil(ln(1 / delta)) its probability, giving 2,719 by 5 counters for epsilon 0.001 and delta 0.01. Sketches with identical dimensions and hashes merge by adding cells, so 50 pods can be summed by a collector, and a top-k heap and conservative update address its weakness with rare items and overestimation.

What to say in the interviewAbout 100 seconds aloud

Open with

A Count-Min Sketch is a table of d rows by w counters, and each row has its own hash function. To add an item I hash it once per row and increment one counter in each row; to query I look at those same d counters and return the minimum.

Then, if they want more

It only overestimates because every counter for the item has been incremented every time the item was added, and other items that collide can only add more, never subtract, so each counter is at least the true count, and so is the minimum.

The parameters come from the error guarantee: with w equal to the ceiling of e over epsilon and d equal to the ceiling of ln one over delta, the estimate exceeds the true count by more than epsilon times the total count with probability at most delta.

Epsilon point zero zero one and delta point zero one give two thousand seven hundred nineteen by five, about thirteen thousand six hundred counters.

To combine sketches from fifty pods, they must have the same dimensions and the same hash seeds; then merging is just adding counters cell by cell, so each pod keeps its own sketch per interval and a collector sums them.

The limitation is that error is relative to the total stream, so rare items get poor estimates; it's best for heavy hitters. To list the top items I'd pair it with a small heap of candidates, and conservative update, raising counters only up to the new minimum, reduces overestimation.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does a Count-Min Sketch work, why does it only ever overestimate, how do its width...": https://scrivio-interview-library.netlify.app/architecture/distributed-systems/f98b953b58/