Sub topic 14
When to Use Count-Min Sketch and When Not To
This chapter assumes you have read the earlier chapters. You should know how a count-min sketch (CMS) stores a d by w grid of counters, how the row minimum gives an estimate that never undercounts, and how w = ⌈e/ε⌉ and d = ⌈ln(1/δ)⌉ follow from the (ε, δ) guarantee. Here you will use those facts to decide whether a sketch fits a given problem.
What you get: memory that does not grow with the data
An exact counter, such as a Python dict or Counter, stores one entry per distinct item. Its memory grows with the number of distinct keys. A sketch stores w * d counters whatever the stream contains. The sizes depend only on ε and δ.
import math
def sketch_size(epsilon, delta, counter_bytes=8):
w = math.ceil(math.e / epsilon)
d = math.ceil(math.log(1 / delta))
return w, d, w * d * counter_bytes
for eps in (0.01, 0.001, 0.0001):
w, d, size = sketch_size(eps, 0.01)
print(f"eps={eps}: {w} x {d} counters, {size:,} bytes")With δ = 0.01 this prints about 11 KB for ε = 0.01, about 109 KB for ε = 0.001, and about 1.1 MB for ε = 0.0001. A dictionary over hundreds of millions of distinct keys needs gigabytes. That gap is the reason to use a sketch.
Updates and queries cost O(d) time. They touch exactly d cells, and the cost does not depend on stream size. The table is also a fixed block of integers, so it is easy to serialize, ship between machines, and keep in cache.
What you give up
The error is relative to the stream length, not to the item
The guarantee says that, with probability at least 1 − δ, an estimate exceeds the true count by at most εN, where N is the total of all counts. The bound does not shrink for rare items. Suppose N = 10,000,000 and ε = 0.001. Any estimate may be off by up to 10,000. An item seen 50 times may be reported as 50 or as 9,000. A heavy item seen 2,000,000 times has a relative error of at most 0.5%.
So a sketch is good at telling large counts from small ones. It cannot resolve differences smaller than εN. The next experiment shows this. It uses a stable hash (zlib.crc32) so that results do not depend on Python's per-process hash() seed.
import math
import random
import zlib
from collections import Counter
class Sketch:
def __init__(self, epsilon, delta, seed=0):
self.w = math.ceil(math.e / epsilon)
self.d = math.ceil(math.log(1 / delta))
self.p = (1 << 61) - 1
rng = random.Random(seed)
self.params = [(rng.randrange(1, self.p), rng.randrange(self.p))
for _ in range(self.d)]
self.table = [[0] * self.w for _ in range(self.d)]
def _cols(self, item):
x = zlib.crc32(str(item).encode()) % self.p
return [((a * x + b) % self.p) % self.w for a, b in self.params]
def add(self, item):
for row, col in zip(self.table, self._cols(item)):
row[col] += 1
def estimate(self, item):
return min(row[col] for row, col in zip(self.table, self._cols(item)))
rng = random.Random(1)
keys = list(range(1, 5001))
weights = [1 / k for k in keys] # a skewed, Zipf-like distribution
stream = rng.choices(keys, weights=weights, k=100_000)
sketch = Sketch(epsilon=0.01, delta=0.01)
truth = Counter()
for item in stream:
sketch.add(item)
truth[item] += 1
print("epsilon * N =", 0.01 * len(stream))
for key in (1, 10, 1000, 5000):
true, est = truth[key], sketch.estimate(key)
print(f"key {key}: true={true} estimate={est} overcount={est - true}")Key 1 is very frequent, so its estimate is close to the truth in relative terms. Key 5000 appears only a handful of times. Its estimate is typically far above its true count, because every cell it hashes to also holds counts from many other keys. The overcount is never negative.
The sketch cannot list its keys
A sketch answers "how many times did x appear?" for any x you supply. It does not store keys, so you cannot ask for the top items or iterate the contents. The heap from the heavy-hitters chapter exists for this reason. You keep candidate keys next to the sketch.
It does not say whether an item appeared
Querying an item that never appeared usually returns a positive number, because collisions fill its cells. An estimate of 300 does not tell you the item was seen. If you need set membership, use a Bloom filter. If you need "seen at least k times", compare the estimate against a threshold much larger than εN.
The bound holds per query
The probability 1 − δ applies to one query. If you query many items, some of them will probably exceed the bound. If the guarantee must hold for all m queries together, replace δ with δ/m. This adds only ln m rows, so it is cheap.
Comparing the alternatives
| Method | Memory | Error | Deletions | Notes |
|---|---|---|---|---|
| Exact dictionary | Proportional to distinct keys | None | Yes | Simplest option. Use it whenever it fits. |
| Count-min sketch | `O(1/ε · ln(1/δ))` | One-sided, at most εN | Limited (see below) | Mergeable, fast, easy to implement. |
| Count Sketch | `O(1/ε² · ln(1/δ))` | Two-sided, relative to the L2 norm of the frequencies | Yes | Unbiased, uses random ±1 signs and a median. |
| Misra-Gries or Space-Saving | `k` counters | Deterministic, at most N/k | Not designed for it | Gives top-k candidates directly, with no hashing. |
Count Sketch adds a second hash per row that assigns each item a sign, +1 or −1. Updates add the signed count, and the estimate is the median over rows of the signed cell values. Collisions then cancel in expectation instead of piling up. The estimate is unbiased, and its error scales with the L2 norm of the frequency vector. That norm is never larger than N and is much smaller on skewed data. The price is a width of order 1/ε² instead of 1/ε, and the one-sided guarantee is lost.
Deletions
The number of rows still follows from δ. What changes with deletions is whether the minimum is a valid estimator.
- Insert-only streams. The row minimum never undercounts. This is the setting the rest of the tutorial uses.
- Strict turnstile. Updates may be negative, but every item's true count stays at least zero. Each cell is still the true count plus collisions from other nonnegative counts, so the minimum is still an upper bound.
- General turnstile. True counts may go negative. A cell can then be pushed below the true count by a colliding negative item, and the minimum can undercount. Use the median of the rows, or use Count Sketch. You lose the one-sided guarantee, and the error analysis changes.
Conservative update assumes nonnegative increments. Do not combine it with deletions.
Merging and distribution
Sketches built with the same width, depth, and hash parameters merge by adding their tables. The result equals a sketch that saw both streams. This makes the CMS a good fit for map-reduce style jobs and for per-window sketches. If different machines use different seeds, or different hash implementations, the merge is meaningless. Fix the seed and the hash function, and prefer a stable hash such as crc32, MurmurHash, or xxHash over Python's built-in hash().
A decision procedure
Good fits include:
- Network traffic monitoring, where a few flows carry most of the packets.
- Trending-term detection in search or social feeds.
- Frequency lookups inside query planners, where a rough count is enough.
- Approximate counters in distributed logs that are merged per time window.
Poor fits include:
- Billing or auditing, where every count must be exact.
- Uniform data, where all items have similar counts and none stands out above εN.
- Small key spaces, where a dictionary is cheaper and exact.
- Cases where you need the rare items, because the sketch cannot resolve them.
Practical tips
Before building a sketch, estimate the answer to one question: how large is the smallest count you must distinguish, compared with N? Set ε below that ratio. Then check the memory with sketch_size. If the result is not much smaller than an exact dictionary, use the dictionary.
Exercise
A stream has N = 50,000,000 events. You use ε = 0.0005 and δ = 0.01. What are w and d, how many counters does the sketch hold, and what is the largest overcount you should expect for most queries? Can the sketch reliably tell an item seen 10,000 times from one seen 20,000 times?
Show answer
w = ⌈e/0.0005⌉ = ⌈5436.56⌉ = 5437 and d = ⌈ln 100⌉ = ⌈4.605⌉ = 5, so the table holds 5437 × 5 = 27,185 counters. The overcount is at most εN = 0.0005 × 50,000,000 = 25,000 with probability at least 99% per query. The error bound (25,000) is larger than both counts, so the sketch cannot reliably separate 10,000 from 20,000. An estimate of 20,000 might come from a true count anywhere from 0 up to 20,000, and the item seen 10,000 times might be reported higher than the item seen 20,000 times. Tightening ε or choosing another method is needed.
Exercise
A stream of inserts and deletes keeps every item's net count at zero or above. Can you still use the row minimum? What changes if net counts can go negative?
Show answer
Yes. This is the strict turnstile model. Each cell equals the true count plus the nonnegative counts of colliding items, so the minimum is still an upper bound on the true count. If net counts can go negative, a cell can fall below the true count when a negative item collides with it. The minimum may then undercount, and you need the median of the rows or Count Sketch. The one-sided guarantee no longer holds.