Sub topic 5
Why the estimate can only be too high
This chapter assumes you know the sketch layout from the earlier chapters: a table of d rows and w columns, one hash function per row, and an estimate taken as the minimum across rows. You should also be comfortable with sums and with the idea that a hash function can map two different items to the same slot.
The goal is to explain why estimate(x) is never below the true count of x. This property is called one-sided error. It follows from a short argument that needs no probability, and it shapes how you use the sketch.
What each counter actually holds
Write f(y) for the true number of times item y has appeared. Write h_j for the hash function of row j. After the stream has been processed, the counter at row j, column c holds:
T[j][c] = sum of f(y) over all items y with h_j(y) = c
A counter is the total count of every item that hashes into its column. Nothing else changes it. Each add(y, count) adds count to exactly one counter per row, the one at column h_j(y).
Now take a particular item x and look at its counter in row j. The items sharing that column are x itself and every other item that collides with it:
T[j][h_j(x)] = f(x) + X_j
Here X_j is the sum of f(y) over all y ≠ x with h_j(y) = h_j(x). It is the collision noise in row j.
The argument
The argument has three steps.
- Every update adds a non-negative amount, so every
f(y)is at least 0. A sum of non-negative terms is non-negative, soX_j ≥ 0in every row. - Therefore each row gives a value
f(x) + X_j, which is at leastf(x). - The estimate is the minimum over the
drows. If every value is at leastf(x), their minimum is at leastf(x).
In symbols:
estimate(x) = min over j of (f(x) + X_j) = f(x) + min over j of X_j ≥ f(x)
The proof never mentions how the hash functions were chosen. It holds for any hash functions, including bad ones, and for any stream. It also holds on every run, not just with high probability. Randomness only matters when you ask how much higher the estimate can be, which is the next chapter's topic.
A worked example
Use a tiny sketch with d = 2 rows and w = 3 columns. The stream contains item a five times, b three times, and c twice. Suppose the two hash functions place the items like this:
| Item | True count | Row 0 column | Row 1 column |
|---|---|---|---|
| a | 5 | 0 | 1 |
| b | 3 | 0 | 2 |
| c | 2 | 1 | 1 |
The counters are the column sums:
- Row 0: column 0 holds 5 + 3 = 8, column 1 holds 2, column 2 holds 0.
- Row 1: column 0 holds 0, column 1 holds 5 + 2 = 7, column 2 holds 3.
The estimates are:
| Item | Row 0 value | Row 1 value | Estimate (minimum) | True count |
|---|---|---|---|---|
| a | 8 | 7 | 7 | 5 |
| b | 8 | 3 | 3 | 3 |
| c | 2 | 7 | 2 | 2 |
Item a collides with another item in both rows, so its estimate is too high: 7 instead of 5. Item b is exact because row 1 gave it a column with no other item in it. Item c is exact because row 0 did.
Taking the minimum helps because a wrong row is usually wrong in a different way from the other rows. The minimum picks the row where the least extra count landed. A row can only inflate a value, never deflate it, so no row can hide a high value from the minimum.
Checking the invariant in code
The following script builds a deliberately small sketch (8 columns, 3 rows) so that collisions are frequent. It feeds in a skewed stream of integers and checks the invariant for every item. Integers are used so the hash values are the same on every run.
import random
from collections import Counter
P = (1 << 61) - 1 # Mersenne prime for the hash family
W, D = 8, 3
rng = random.Random(1)
params = [(rng.randrange(1, P), rng.randrange(0, P)) for _ in range(D)]
table = [[0] * W for _ in range(D)]
def cols(x):
return [((a * x + b) % P) % W for a, b in params]
def add(x, count=1):
for row, c in zip(table, cols(x)):
row[c] += count
def estimate(x):
return min(row[c] for row, c in zip(table, cols(x)))
stream_rng = random.Random(7)
stream = [int(stream_rng.paretovariate(1.2)) for _ in range(2000)]
truth = Counter(stream)
for x in stream:
add(x)
overcounted = 0
for x, true_count in truth.items():
est = estimate(x)
assert est >= true_count, (x, est, true_count)
if est > true_count:
overcounted += 1
print("distinct items:", len(truth))
print("items overcounted:", overcounted)
print("estimate for an item never seen:", estimate(10**9))The assert never fires, whatever seeds you choose. The number of overcounted items depends on the seeds. With only 8 columns and many distinct items, expect many of them to be overcounted.
Consequences you can rely on
The invariant gives you several guarantees you can use when writing code.
- A lower bound for free. If
estimate(x) < t, thenf(x) < tfor certain. You can safely rule out items whose estimate falls below a threshold. - No false negatives for threshold queries. If you ask for all items with true count at least
t, every one of them has an estimate of at leastt. A heavy-hitter search that keeps items withestimate ≥ tnever misses a truly heavy item. It may include some light ones. - False positives are possible. An item that never appeared can have a positive estimate, as the last line of the script shows. A positive estimate does not prove the item was seen.
- Adding more items never lowers an estimate. Each update only increases counters, so estimates only grow over time.
When the property breaks
The proof used one assumption: every f(y) and every update is non-negative. Remove it and the property goes away.
- Negative updates. If you call
add(y, -1)to delete an item, a collision noise termX_jcan become negative. A row might then produce a value belowf(x), and the minimum can undercount. Streams with deletions are the turnstile model, and they need a different estimator. A later chapter covers it. - Counter overflow. The invariant is about mathematical sums. A fixed-width integer that wraps around does not follow it. Python integers never overflow, but a C, Java, or Rust implementation with 32-bit counters can. Use wide enough counters or saturate at the maximum value.
- Inconsistent hashing. The proof assumes
addandestimateuse the same column for the same item. Python's built-inhash()of a string differs between processes unlessPYTHONHASHSEEDis fixed. If you build a sketch in one process and query a saved copy in another, the columns won't match and the invariant fails. Use a stable hash such as one fromhashlibfor sketches that are stored or shared. - Mixing sketches. Adding tables built with different hash parameters gives sums of unrelated collisions. The result may be below some true counts. Merging is only valid when width, depth, and hash parameters match.
Conservative update keeps the property
Conservative update raises each of an item's counters only up to the new minimum estimate, instead of adding the count to every counter. It leaves some counters smaller than they would otherwise be, so you might worry it breaks the invariant. It doesn't, for non-negative counts. After the update, every counter of x is at least estimate_before(x) + count, and by induction that is at least the new true count f(x). Each row's value stays at least f(x), so the minimum does too. This is why conservative update reduces overcounting without giving up the guarantee.
Summary of the argument
- Each counter equals the sum of the true counts of all items hashed to it.
- For item
x, that sum isf(x)plus a non-negative collision term. - The minimum of values that are each at least
f(x)is at leastf(x). - The argument needs non-negative updates, consistent hashing, and counters that do not wrap around. It does not need randomness.
Exercise
A sketch has d = 3 rows. For item x, the three counters it maps to hold 41, 17, and 29. A second item y, which was added 25 times, maps to the same column as x in the row holding 17. What can you say about the true count of x?
Show answer
The estimate is min(41, 29, 17) = 17, so the true count of x is at most 17, and it is at least 0. Because y shares x's counter in the row holding 17 and was added 25 times, that counter would be at least 25 if it held y's full count, so it can't be 17. This means the scenario is inconsistent: a counter containing y's 25 additions must be at least 25. Either y was not added 25 times, or y does not map to that column. The check is useful because it shows the invariant at work: every counter is at least the sum of the true counts of all items that hash into it.
Exercise
Suppose you support deletions by calling add(x, -1) when an item expires. Give a concrete scenario with d = 1 where estimate(x) falls below the true count of x.
Show answer
Let w = 1, so every item shares one counter. Add item y once and item x once, so the counter is 2. Now delete y by calling add(y, -1), then delete y again by mistake or from a duplicate expiry event, which brings the counter to 0. The true count of x is 1, but estimate(x) = 0. Collision noise from y became negative, so the counter fell below f(x). The same can happen with correct deletions if x's count is queried when other items' deletions outnumber their insertions in the shared column. The one-sided property needs non-negative counts.