SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Bloom Filters
  • Cuckoo Filter
  • Skip Lists
  • Count-Min Sketch
  • HyperLogLog
  • Merkle Trees
  • MinHash
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Probabilistic and Other Structures

Count-Min Sketch

Count how often things appear in a huge stream, using a tiny fixed amount of memory.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A Count-Min Sketch answers "how many times did this item appear?" for a huge stream of events, using a small, fixed amount of memory. The price is that the answer can be a little too high, but never too low.

  • It is a small table of counters with several rows. Each row has its own hash function.
  • To add an item, add 1 to one counter in every row. To ask, read those counters and take the smallest.
  • Different items can share a counter (a collision), which only pushes counts up. Taking the minimum across rows keeps the over-count small.

02Concept: What is it?

Imagine you must count how often each search word appears, across billions of searches. A normal hash map (word → count) needs one entry per different word. If there are hundreds of millions of different words, that is a lot of memory, and it keeps growing.

A Count-Min Sketch uses a table with d rows and w columns, all starting at 0. Each row has a different hash function that turns an item into a column number.

  • Add an item: for each row, hash the item to a column and add 1 to that cell.
  • Ask for a count: for each row, hash the item to a column and read the cell. The answer is the minimum of those d numbers.

Why the minimum? A cell can hold the real count plus counts from other items that landed in the same cell. So every cell is at least the true count. The row where the item had the fewest "neighbours" is closest to the truth, so the smallest cell is the best guess. The sketch can only over-count, never under-count.

Adding and asking in a 3-row sketch
Add “cat”
🐱cat
↓3 hashes
Row 1column 2: +1
Row 2column 5: +1
Row 3column 0: +1
Ask about “cat”
Row 1reads 14
Row 2reads 9
Row 3reads 11
↓take the minimum
✅Estimate: 9true count is 9 or a bit lower
The same word lands in a different column in each row. The smallest of the three cells is the answer.
🧠One-sided error
The estimate is always greater than or equal to the true count. It is never smaller. This is useful: if the sketch says an item appeared fewer than 5 times, you can be sure it really did.

03Real-Life Example

🍵The Shared Tally Boards
A busy cafe wants to know how many cups of each drink it sells. There are thousands of drinks and very little wall space. So the cafe hangs 3 small boards. Each board has only 8 boxes. Each board has its own rule for turning a drink name into a box number (rule 1, rule 2, rule 3). When a drink is sold, the barista puts one tally mark in the matching box on each of the 3 boards. To estimate sales of a drink, look at its three boxes and read the smallest one. Some other drink may share a box on one board, so that box is too high. But it is very unlikely that the same other drinks share the box on all three boards, so the smallest box is usually close to the truth.
Cafe tally boards
Count-Min Sketch
One small board with 8 boxes
One row with w counters
3 boards with different rules
d rows with different hash functions
A tally mark for each sale
Add 1 to a cell in every row
Two drinks sharing a box
A hash collision
A box that is too high because of a neighbour
Over-counting
Reading the lowest of the 3 boxes
Taking the minimum across rows
Wall space that never grows
Fixed memory, however many drinks
Why the minimum is a good guess
🎯True count9
→↓+ neighbours
📋Row cells14, 9, 11
→↓min
✅Estimate9 (or a bit above)

04Why Do We Need It?

🧠Fixed memory
Size is d × w counters, no matter how many different items arrive. A hash map grows with every new item.
⚡Very fast
Adding and asking take d hash computations and d memory reads. That is a handful of operations.
🌊Made for streams
You see each event once and cannot store them all. A sketch updates in one pass.
🔀Easy to merge
Two sketches with the same size and hash functions can be added cell by cell. Great for many servers.
🔥Finds heavy hitters
The most frequent items stand out clearly, since they dominate their cells.
📐Provable error
You choose an error size and a confidence, and the sketch dimensions follow from those two numbers.
You do not need exact counts for every item. You need good counts for the popular ones, in tiny memory. A Count-Min Sketch gives you that.

05Where Do We Use It?

🔥Trending and top-K
Find the most popular hashtags, search words or videos in a live stream.
🚦Rate limiting
Count requests per client when there are too many clients for a counter each.
🛡️Abuse and DDoS detection
Spot an address that sends far more traffic than the rest.
🧠Cache admission
Cache libraries use a small frequency sketch to decide if a new item is popular enough to keep (TinyLFU).
📊Analytics
Approximate counts for dashboards over data too big for exact counting.
🗃️Database planning
Estimate how common a value is, to pick a good query plan.

06Types / Parts / How It Works

The two operations

Update and query
Update(item)
1️⃣For each row icolumn = hash_i(item) mod w
↓
2️⃣table[i][column] += 1
Estimate(item)
1️⃣For each row icolumn = hash_i(item) mod w
↓
2️⃣Read table[i][column]
↓
3️⃣Return the minimum
Both touch exactly one cell in each row.

Choosing the size

You chooseSymbolRuleMeaning
Error sizeε (epsilon)width w = ceil(e / ε)The over-count is at most ε × (total events) most of the time
Failure chanceδ (delta)depth d = ceil(ln(1 / δ))The chance the error is bigger than that is at most δ
Exampleε = 0.001, δ = 0.01w = 2719, d = 5About 13,600 counters for any number of different items

Related ideas

StructureAnswersErrorMemory
Hash mapExact count of every itemNoneGrows with the number of different items
Count-Min SketchHow often did this item appear?Over-counts onlyFixed (d × w counters)
Bloom filterWas this item seen at all?False positives onlyFixed (bit array)
HyperLogLogHow many different items were seen?About ±1 to 2%Fixed (a few KB)
Count Sketch (a cousin)How often? Allows deletesCan be too high or too lowFixed
📝Conservative update
A popular trick: on update, only raise the cells that are currently the smallest for that item. This keeps over-counting lower in practice, at the cost of not supporting deletes.
VisualizerA tiny sketch you can breakMake the table narrow and shallow and ask for a rare item: the estimate jumps too high. Then widen the table or add rows and watch the error shrink.
Ask for the count of
Each row is one hash function. Cyan = the cell that "seal" maps to in that row. Green = the smallest of them, which is the answer.
row 1
96
0
216
0
21
0
67
200
row 2
314
102
76
0
12
0
64
32
row 3
114
56
0
8
11
43
21
347
The row values for "seal" are 96, 64, 8. The estimate is the smallest one: 8.
Estimate
8
min over the rows
True count
8
a hash map would know
Over-count
0
never below 0
Counters used
24
for 10 different items
Exact answer for "seal": 8. In row 3, nobody else shared its cell (or the others added nothing). The sketch is allowed to be exact, it just is not promised to be.

Rule of thumb for these settings: with width 8 the extra count is usually at most about e/width × events = 204, and that holds with roughly 95% confidence with 3 rows. The table is tiny on purpose, so collisions are easy to see. Real sketches use thousands of columns.

07How to Use It / Steps / Implementation

Using a Count-Min Sketch well

  1. 1
    Decide the error you can accept
    For example: over-counts of at most 0.1% of all events, and right 99% of the time. That gives ε and δ.
  2. 2
    Compute the size
    Width w = ceil(e / ε). Depth d = ceil(ln(1 / δ)). The table is d × w counters.
  3. 3
    Use independent hash functions
    Each row needs its own hash function (or the same good hash with a different seed). Weak or similar hashes make collisions line up.
  4. 4
    Pick counter sizes
    A 32-bit counter is usually enough. Use 64 bits for very large streams, or small saturating counters in cache admission.
  5. 5
    Keep a small top-K list on the side
    A sketch does not store item names. To list the top items, keep a small heap of the best candidates and update it using the sketch estimate.
  6. 6
    Merge across machines
    Give every machine the same dimensions and hash seeds. Add the tables cell by cell to get a combined sketch.
  7. 7
    Reset or age the counts
    For recent trends, use one sketch per time window, or halve every counter now and then.
💡Most useful for heavy hitters
The error does not depend on the item, it depends on the total number of events. So a big count is barely affected, while a tiny count can be many times too high. Use the sketch to find the popular items, and be careful about reading much into small numbers.
⚠️Deletes need care
Plain sketches cannot handle removing items safely if the count could go negative, because the minimum trick only works for non-negative counts. Use a time-windowed sketch, or a sketch variant that supports deletes.

08Key Terms to Know

TermMeaning in easy words
SketchA small summary of a big data stream that can answer some questions approximately
Count-Min SketchA d × w table of counters used to estimate how often each item appeared
Width (w)The number of columns. Wider means fewer collisions and smaller error
Depth (d)The number of rows. More rows make a bad estimate less likely
Hash functionA function that turns an item into a number. Each row uses a different one
CollisionTwo different items landing in the same cell
Over-countAn estimate that is higher than the truth. This is the only kind of error
Heavy hitterAn item that appears much more often than most
ε (epsilon)The error size you accept, relative to the total number of events
δ (delta)The chance you allow for the error to be bigger than ε
Streaming algorithmAn algorithm that sees each item once and keeps only a small summary

09Pros, Cons and Trade-offs

✅ Pros
  • Tiny, fixed memory
  • Constant time for update and estimate
  • One pass over the data
  • Sketches from many machines can be merged
  • Error bounds can be proven
⚠️ Cons
  • Estimates can be too high
  • Small counts have a large relative error
  • Does not store or list the items
  • Cannot safely delete items in the basic form
  • Needs good independent hash functions

Trade-offs

ChoiceWe gainWe lose
Wider tableFewer collisions, smaller errorMore memory
More rowsHigher confidence in the answerMore hashing per operation, more memory
Sketch instead of a hash mapFixed, small memoryExactness, and the list of items
Conservative updateLess over-countingNo support for deletes or merging by simple addition
Small countersEven less memoryCounters can saturate on very popular items
One sketch per time windowRecent data stays relevantMore sketches to store and combine

10Common Problems and Mistakes

Common mistakes

  1. Trusting small counts. A true count of 3 can read as 300 if the table is too small for the stream.
  2. A table that is too narrow. If w is small compared with the number of different items, nearly every cell is shared.
  3. Using the same hash for every row. The rows then collide in the same way and the minimum does not help.
  4. Expecting it to list items. A sketch only answers questions about items you ask about. Use a top-K heap or another structure for the list.
  5. Subtracting counts. The one-sided error guarantee breaks if counts can go down.
  6. Mixing sketch settings when merging. Sketches with different sizes or seeds cannot be added together.
  7. Never resetting. Counts only grow, so old events dominate. Use windows or decay.

Things to watch

📏Size versus stream
The error grows with the total number of events. A bigger stream needs a wider table for the same relative error.
🎲Hash quality
Use well-tested hash functions with different seeds.
🧮Counter overflow
Very popular items can overflow small counters.
🕒Old data
Without windows or decay, a sketch remembers everything since the start.

11Real-World Examples

🔥Trending topics
Social and video platforms look for items whose counts rise faster than the rest.
🧠Caching libraries
Frequency sketches (TinyLFU in Caffeine, for example) help decide what deserves cache space.
🛡️Network monitoring
Routers and security tools spot sources that send unusually many packets.
📈Big data tools
Stream and analytics systems offer sketch libraries for approximate counts, such as Apache DataSketches.
🗃️Redis modules
Redis offers Count-Min Sketch and Top-K as probabilistic data types (in Redis Stack).
🔎Query planning
Databases estimate how often values appear to choose faster plans.
📝Note
Product features and defaults change between versions. Check the current documentation before relying on a specific one.
Mini case: finding the top search words
🔍Billions of searches
→↓update
🧮Count-Min Sketcha few MB
→↓estimate
🏆Top-K heapbest 100
Stream Sketch Answer
A tiny sketch plus a small top-K list replaces a huge counter table.
Memory of a hash map for 200 million different words (idea)grows with the data
Memory of the sketchfixed

12Related Topics to Read Next

Bloom Filters→

Same family: tiny memory, one-sided error, but it answers a yes or no question.

HyperLogLog→

Counts how many different items appeared, not how often each did.

Skip Lists→

A different kind of structure that uses randomness to stay fast.

MinHash→

Another sketch, used to compare how similar two sets are.

Rate Limiting→

Counting requests per client is a classic use.

Streaming Engines→

Where sketches are often used on endless event streams.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a d × w table of counters that estimates how often each item appeared.
  • ✔Add: +1 in one cell per row, chosen by that row hash.
  • ✔Ask: read one cell per row, return the minimum.
  • ✔Error: over-count only. Never below the truth.
  • ✔Size: w = ceil(e / ε), d = ceil(ln(1 / δ)). Memory does not grow with the data.
  • ✔Strength: heavy hitters. Weakness: small counts can be far too high.
  • ✔Extras: sketches merge by adding cells. Keep a top-K heap for item names.
  • ✔One line: “A few shared tally boards: read the lowest box and you are close to the truth.”
← Previous
Skip Lists
Next →
HyperLogLog