Sub topic 7
Sizing a Sketch: w = ⌈e/ε⌉ and d = ⌈ln(1/δ)⌉
This chapter assumes you know how a count-min sketch works: a grid of d rows and w columns, one hash per row, add by incrementing one counter per row, and estimate by taking the row minimum. It also assumes you know the guarantee that an estimate never undercounts and overcounts by at most εN with probability at least 1 − δ. Here you will learn how to turn a target ε and δ into a table size, and how to go the other way.
Two knobs, two different jobs
The sketch has two size parameters, and each one controls a different kind of error.
- Width
wcontrols how large the error can be. More columns mean fewer items share a counter, so each counter carries less noise. - Depth
dcontrols how often the error bound fails. Each extra row is another independent chance to get a counter with little noise. The minimum only needs one of them.
The guarantee uses two numbers:
- ε (epsilon) is the error tolerance, as a fraction of the total stream length N. An overcount of at most εN is acceptable.
- δ (delta) is the failure probability. The estimate for one item may exceed the true count by more than εN with probability at most δ.
The sizing formulas are:
w = ⌈e / ε⌉d = ⌈ln(1 / δ)⌉
Here e ≈ 2.71828 is Euler's number and ln is the natural logarithm. The brackets ⌈ ⌉ mean "round up to the next whole number". Rounding up is the safe direction, since a larger table only improves the guarantee.
Computing the dimensions
import math
def size_for(epsilon, delta):
"""Return (width, depth) for a target error and failure probability."""
if not (0 < epsilon < 1):
raise ValueError("epsilon must be between 0 and 1")
if not (0 < delta < 1):
raise ValueError("delta must be between 0 and 1")
w = math.ceil(math.e / epsilon)
d = math.ceil(math.log(1 / delta))
return w, d
for epsilon, delta in [
(0.1, 0.1),
(0.01, 0.1),
(0.01, 0.01),
(0.001, 0.01),
(0.001, 1e-6),
(0.0001, 0.01),
]:
w, d = size_for(epsilon, delta)
print(f"eps={epsilon:<7} delta={delta:<8} w={w:<6} d={d:<3} counters={w * d}")The output matches this table:
| ε | δ | w | d | Counters |
|---|---|---|---|---|
| 0.1 | 0.1 | 28 | 3 | 84 |
| 0.01 | 0.1 | 272 | 3 | 816 |
| 0.01 | 0.01 | 272 | 5 | 1,360 |
| 0.001 | 0.01 | 2,719 | 5 | 13,595 |
| 0.001 | 0.000001 | 2,719 | 14 | 38,066 |
| 0.0001 | 0.01 | 27,183 | 5 | 135,915 |
Reading across the rows shows how the knobs behave:
- Dividing ε by 10 multiplies the width, and so the memory, by about 10.
- Dividing δ by 10,000 (from 0.01 to 0.000001) takes depth from 5 to 14. The cost is under three times the memory.
Confidence is cheap and precision is expensive. A sketch that is wrong once in a million queries costs little more than one that is wrong once in a hundred.
Why the formulas look like this
The full proof comes in a later chapter. The sizing formulas follow from two facts in it.
- In a single row, the expected extra count in the item's counter, caused by other items colliding with it, is at most N/w.
- Markov's inequality says a non-negative quantity exceeds
ctimes its expectation with probability at most 1/c. The overcount cannot be negative, so the inequality applies.
Set w = e/ε. The expected overcount in one row is then at most εN/e. The chance that this row's overcount exceeds εN is at most 1/e, which is about 0.37.
The estimate is the minimum across rows, so it exceeds εN only if every row is that bad. With independent hash functions, the probability is at most (1/e)^d = e^(−d). Requiring e^(−d) ≤ δ gives d ≥ ln(1/δ). The smallest whole number that satisfies this is ⌈ln(1/δ)⌉.
The constant e appears because 1/e is the per-row failure probability and the depth formula uses a natural logarithm. A different choice of w would change the base of the logarithm for d.
Going backwards: from a memory budget to a guarantee
In practice you often start from a memory budget and want to know what you get. Invert the formulas:
ε = e / wδ = e^(−d)
import math
def guarantee_for(w, d, counter_bytes=8):
epsilon = math.e / w
delta = math.exp(-d)
memory_kib = w * d * counter_bytes / 1024
return epsilon, delta, memory_kib
epsilon, delta, kib = guarantee_for(w=1000, d=4)
print(f"epsilon={epsilon:.5f} delta={delta:.4f} memory={kib:.1f} KiB")For 1000 columns and 4 rows, this prints an ε of about 0.00272 and a δ of about 0.0183. The table takes 31.2 KiB with 8-byte counters. Because the formulas are rounded up, the real guarantee is at least as good as the one you asked for.
What the numbers mean for a real stream
The error bound is εN, so it scales with the stream length, not with the item's own count. Suppose a stream has N = 1,000,000,000 events and you choose ε = 0.001.
- An estimate may be too high by up to 1,000,000.
- For an item seen 50,000,000 times, that is at most a 2% error, which is usually fine.
- For an item seen 200 times, the same bound allows an estimate thousands of times too large. That bound is a worst case, and typical collisions add far less. But the guarantee gives you no protection for rare items.
The table for ε = 0.001 and δ = 0.01 has 13,595 counters. At 8 bytes each that is about 106 KiB, and it does not grow with the number of distinct items. Exact counting needs memory proportional to the distinct items, which can be hundreds of millions of keys.
Edge cases and gotchas
The guarantee covers one query at a time. For any single item, the failure probability is at most δ. If you query m items, the expected number of failing queries is at most mδ. To make all m answers correct at once with probability at least 1 − δ, size the depth for δ/m, which is d = ⌈ln(m/δ)⌉. Depth grows only with the logarithm of m. For m = 1,000,000 and δ = 0.01, that is ⌈ln(100,000,000)⌉ = 19 rows.
ε and δ are bounds, not typical errors. Real streams are usually skewed, with a few heavy items and many light ones. Observed errors are often far below εN. Don't treat a sketch with measured error well under the bound as oversized, because the bound must hold for adversarial or unlucky inputs too.
Rounding can surprise you at exact boundaries. If δ is exactly e^(−5), floating-point error in math.log may give a value slightly above 5, and ceil then returns 6. This does no harm, because the extra row only tightens the guarantee. It does mean two machines using different math libraries could pick different depths. Sketches you plan to merge must share dimensions, so compute w and d once and store them with the sketch.
Very large δ gives very small d. If δ = 0.5, then ln(2) ≈ 0.69 and d is 1. A sketch with one row has no minimum to take, and the overcount bound holds only with probability 1/2. Use a few rows in practice. The formula tells you the minimum, not a recommendation.
Width and counter size are separate choices. The formulas count counters, not bytes. If the stream can exceed 2^32 events, use 64-bit counters. In Python, integers do not overflow, but in a typed language or a packed array they can.
Choosing parameters in practice
- Decide the acceptable error as a fraction of N. Ask what overcount would change a decision. If a count must be right to within 0.1% of traffic, ε is 0.001.
- Pick δ from how costly a bad estimate is. Values from 0.01 to 0.0001 are common. Each extra decimal digit of confidence adds about 2.3 rows.
- Compute
wanddwithsize_for, and check the memory against your budget withguarantee_for. - If memory is too high, relax ε first. It dominates the cost, because width grows as 1/ε while depth grows only as ln(1/δ).
- If you will query many items at once, size depth for δ divided by the number of queries.
Exercise
A stream is expected to reach N = 10,000,000 events. You want every estimate to overcount by at most 20,000 events, and you accept a failure probability of 0.001 per query. What are w and d, how many counters is that, and what is the largest overcount the guarantee allows if the stream ends up with 40,000,000 events instead?
Show answer
ε = 20,000 / 10,000,000 = 0.002. Then w = ⌈e / 0.002⌉ = ⌈1359.14⌉ = 1360. For depth, ln(1/0.001) = ln(1000) ≈ 6.908, so d = 7. The table has 1360 × 7 = 9,520 counters. If the stream grows to 40,000,000 events, the bound is εN = 0.002 × 40,000,000 = 80,000, four times the original target. To keep the 20,000 bound at that length you would need ε = 0.0005, which makes w = ⌈e / 0.0005⌉ = 5437.