Sub topic 1
The problem: counting items in a stream with limited memory
This chapter defines the problem that a count-min sketch solves. You will see why exact counting fails at scale, which constraints define a streaming problem, and what a sketch gives up in return for a fixed memory budget. The chapter builds no sketch. It sets up the requirements that the sketch in the next chapters has to meet.
Prerequisites
This chapter assumes you already know the following:
- Basic Python: dictionaries, generators, and
collections.Counter. - Hash functions and hash tables: a hash maps a key to an integer, and a table stores entries by that integer.
- Basic probability: expected value and independent events. You will need these more in later chapters.
- Big-O notation, especially the difference between O(1), O(n), and "grows with the number of distinct items".
You don't need any prior knowledge of sketches or streaming algorithms.
What a stream is
A data stream is a sequence of items that arrives one at a time, possibly without end. Examples include:
- search queries arriving at a search engine
- packets crossing a network router
- product views on a shop website
- log lines from thousands of servers
In the streaming model, three constraints hold:
- One pass. You see each item once. You can't rewind and re-read the stream.
- Small working memory. The memory you may use is far smaller than the stream. Often it must stay fixed no matter how long the stream runs.
- Fast updates. Each item must be processed in roughly constant time, because the next one is already arriving.
Items usually come from a large universe, the set of all values that could appear. The universe might be all IPv4 addresses (about 4.3 billion values), all URLs, or all user IDs. Only some of those values will actually show up, and the number of distinct values that do appear is not known in advance.
The frequency estimation problem
The frequency of an item x is the number of times x has appeared so far. This chapter writes it as f(x). The total stream length so far is N, so the frequencies of all items add up to N.
Two questions come up repeatedly:
- Point query. How many times has
xappeared? The answer isf(x). - Heavy hitters. Which items are the most frequent? An item is often called a heavy hitter if its frequency is at least some fraction of
N, such as 1%.
Practical uses include spotting a single IP address that sends a flood of traffic, finding trending search terms, deciding which database keys to cache, and detecting abusive clients for rate limiting.
Exact counting and where it breaks
The obvious solution is a hash table from item to count. In Python, that is a Counter.
import random
import sys
from collections import Counter
def stream(n, universe, seed=1):
rng = random.Random(seed)
for _ in range(n):
yield f"user-{rng.randrange(universe)}"
counts = Counter()
for item in stream(200_000, 100_000):
counts[item] += 1
distinct = len(counts)
table_bytes = sys.getsizeof(counts)
key_bytes = sum(sys.getsizeof(key) for key in counts)
print("stream length:", 200_000)
print("distinct items:", distinct)
print("table + keys, bytes:", table_bytes + key_bytes)
print("bytes per distinct item:", (table_bytes + key_bytes) // distinct)This runs in a second or two. The stream has 200,000 items drawn from 100,000 possible IDs, so about 86,000 of them appear at least once. Expect a few megabytes in total, which is roughly 60 to 100 bytes per distinct item. The exact figure depends on your Python version. The getsizeof numbers also leave out the integer objects that hold the counts, so the real footprint is somewhat larger.
The key point is that memory grows with the number of distinct items, not with the length of the stream. A stream of a billion events that only ever repeats ten keys is cheap to count exactly. A stream with a billion distinct keys is not. At 60 to 100 bytes per key, that is 60 to 100 GB for one counter table.
The cost compounds in practice:
- You often need one table per time window, per region, or per metric.
- Hash tables resize as they grow, which causes latency spikes and temporarily needs extra memory.
- A hot-path counter that doesn't fit in CPU cache is much slower than one that does.
- If the table lives on several machines, you must combine many large tables.
Exact counting is a correct answer when it fits. The streaming problem is about the case where it doesn't.
Why you can't just be clever
Several workarounds look attractive but fail for specific reasons.
| Approach | What it does | Why it falls short |
|---|---|---|
| Exact hash table | One counter per distinct item | Memory grows with distinct items |
| Sort on disk, then count | Writes the stream out, sorts, counts runs | Needs multiple passes and storage, and can't answer queries while the stream is running |
| Random sampling | Keeps each item with probability `p`, scales counts by `1/p` | Rare items are mostly missed, and a frequency of 5 may be estimated as 0 or 20 |
| Keep only a fixed number of keys | Evicts keys when full | Evicted keys lose their counts, and the error is hard to bound |
| Sketch | Fixed-size array of counters updated through hashes | Answers are approximate, but memory is fixed and the error is bounded |
There is also a theoretical limit behind this. If you must report the exact count for every item and the number of distinct items is unbounded, you need memory that grows with that number. Exactness for all items cannot be compressed. Only an approximate answer can escape that limit.
What a sketch trades away
A sketch is a small data structure that summarizes a stream. It does not store the items. It stores a compressed numerical summary that is good enough to answer particular questions. The count-min sketch you will build is one such structure.
You give up two things:
- Exactness. The answer to "how many times did
xappear?" is an estimate, not the true value. - The item list. The sketch can't tell you which items it has seen. You can ask about any
xyou name, and you will get a number back, even for items that never appeared.
In return you get:
- Fixed memory. The size is chosen up front and does not change as the stream grows.
- Constant-time updates and queries. The cost per item does not depend on how many items were seen.
- A stated error bound. The error is not a vague "close enough". It is a guarantee with two parameters.
The guarantee has the following shape. You pick an error fraction ε (epsilon) and a failure probability δ (delta). The sketch's answer for x is never below f(x). With probability at least 1 − δ, it is at most f(x) + εN. Later chapters define this precisely and prove it. For now, notice that the error is measured against the total stream length N, not against f(x).
That has a practical consequence. The error is small compared with big counts and large compared with small counts. With ε = 0.01 and N = 1,000,000, an estimate may be off by up to 10,000. That is negligible for an item seen 400,000 times and meaningless for an item seen 12 times. The sketch is therefore best suited to finding and measuring frequent items.
Memory depends on ε and δ, not on the number of distinct items. For ε = 0.01 and δ = 0.01, the table you will build in later chapters has 5 rows of 272 counters. That is 1,360 counters, whether the stream has a thousand distinct items or a billion.
Common mistakes when framing the problem
- Treating the stream length as the cost. Memory for exact counting depends on distinct items. Check how many distinct keys your data really has before reaching for a sketch. If it is a few thousand, use a
Counter. - Assuming a sketch lists the top items. It answers point queries. Finding heavy hitters needs extra bookkeeping, which a later chapter covers.
- Expecting small counts to be accurate. The error bound is proportional to
N, so low-frequency items can be badly overestimated. - Querying items you never added and trusting the answer. The sketch returns a number for any key. A nonzero result does not prove the key appeared.
- Mixing up the two probabilities.
εlimits the size of the error.δlimits the chance that the bound is violated. They are separate knobs.
Where this goes next
The next chapter reviews hashing and collisions, because the sketch is built on them. After that, you will see the grid of counters, how to add an item, and how to read an estimate back. Each later chapter returns to the requirements in this one: fixed memory, one pass, and a bounded, one-sided error.
Exercise
A stream has 50 million events but only 200 distinct keys. Another stream has 50 million events and 40 million distinct keys. For which stream is exact counting with a hash table a poor choice, and why? Also, with ε = 0.01 and N = 2,000,000, what is the largest overcount the guarantee allows for an item, assuming the failure event (probability δ) does not occur?
Show answer
Exact counting is a poor choice for the second stream. Memory for a hash table grows with the number of distinct keys, and 40 million keys at roughly 60 to 100 bytes each is several gigabytes. The first stream needs only 200 entries, however long it is. The largest overcount is εN = 0.01 × 2,000,000 = 20,000. The estimate is never below the true count, and it is at most 20,000 above it.
Exercise
Why can a sketch not tell you which items appeared in the stream, even though it can give an estimate for any item you name?
Show answer
A sketch stores only numerical counters that mix together the contributions of many items. It does not keep the items themselves, so there is nothing to list. When you query a named item, the sketch reads the counters that item maps to and returns a number. For an item that never appeared, that number may still be nonzero because other items share those counters.