Count-Min, HyperLogLog & Streaming Sketches
Frequency and distinct-count estimates in kilobytes.
How many distinct users visited today? A hash set of a billion IDs takes gigabytes; HyperLogLog answers to within about 1% from 12 kilobytes, and the summaries of a thousand servers merge by taking maxima. This lesson proves why such sketches work, shows what no sketch can do, and measures how close the best ones are to optimal.
What you’ll learn
- Define the streaming model, and explain why exact answers need memory linear in the data while randomized approximations need very little.
- Prove the Count-Min guarantee with Markov's inequality, and the Count sketch and AMS guarantees with second moments.
- Explain how Flajolet–Martin, LogLog and HyperLogLog estimate distinct counts, and where HyperLogLog's standard error comes from.
- State the optimal space for counting distinct elements, and use mergeability to design distributed summaries.
The streaming model
Why approximate and randomized? Suppose an algorithm counted distinct items exactly. From its memory after the stream, you could recover the whole set of items seen: run a copy of the algorithm on each possible next item and check whether the count goes up. A set of items from can be any of sets, so the memory needs bits. Alon, Matias and Szegedy (1996) showed that even a deterministic algorithm needs linear space to approximate within a small constant factor. Randomization and approximation together bring the space down to kilobytes.
The sketches in this lesson are built from hash functions with limited independence, and most are linear: the sketch is for a random matrix . Linear sketches handle deletions for free and merge by addition.
Count-Min: point queries with one-sided error
The Count-Min sketch (Cormode & Muthukrishnan, 2005) keeps rows of counters and one hash function per row, drawn independently from a universal family. An update adds to in every row; the estimate is .
One row. The counter of in row holds plus the noise , since all . Universality bounds each collision probability by :
Markov. Markov's inequality for the nonnegative :
Independent rows. The estimate is bad only if every row is bad, and the rows' hash functions are independent:
Why ? With per-row failure probability the sketch needs and , so , and is smallest at :
import math, random
P = (1 << 61) - 1
class CountMin:
def __init__(self, eps, delta):
self.w = math.ceil(math.e / eps)
self.d = math.ceil(math.log(1 / delta))
self.rows = [[0] * self.w for _ in range(self.d)]
self.ab = [(random.randrange(1, P), random.randrange(P)) for _ in range(self.d)]
def _cols(self, x): # x: an integer item id
return [((a * x + b) % P) % self.w for a, b in self.ab]
def add(self, x, c=1):
for row, j in zip(self.rows, self._cols(x)):
row[j] += c
def estimate(self, x):
return min(row[j] for row, j in zip(self.rows, self._cols(x)))One Carter–Wegman function per row, drawn independently. For heavy hitters, keep a min-heap of the candidates whose estimates reach : every item with is reported, and an item with is wrongly reported with probability at most .
In the turnstile model the noise can be negative and the minimum loses its guarantee. Taking the median of the rows instead keeps the error within , at the price of a constant factor more rows for the same failure probability. A common practical refinement, conservative update, increments only the counters that equal the current minimum; it reduces overestimates on real data but works only for insertions.
Random signs: the Count sketch and AMS
Count-Min's noise only adds up. The Count sketch (Charikar, Chen & Farach-Colton, 2002) makes it cancel: each row also has a sign function , an update adds to , and the estimate is the median over the rows of .
Unbiased rows. Row reads . With pairwise independent signs, independent of , every cross term has mean zero:
Small variance. Squaring the noise, the products of two different signs again average to zero, which leaves only squares:
Chebyshev per row. With columns, Chebyshev's inequality bounds the chance that a row errs by more than :
Median of rows. The median errs only if at least half the rows do; with independent rows, a Chernoff bound makes that probability at most :
The trade is columns instead of , for an error in , two-sided but unbiased, that survives deletions. On skewed data the difference is dramatic: one item with frequency 1,000 among items with frequency 1 gives but .
The same signs estimate the second moment , which databases call the self-join size. Alon, Matias and Szegedy (1996) keep one counter , a single row of width 1, in a paper that founded the field and won the 2005 Gödel Prize.
Mean. Cross terms vanish under pairwise independence of the signs:
Fourth moment. With 4-wise independent signs, is 1 when the four indices pair up and 0 otherwise. There are three ways to pair four positions:
Variance. Subtract :
Median of means. Average independent copies of to make Chebyshev's error probability at most , then take the median of such averages:
Counting distinct elements: from Flajolet–Martin to HyperLogLog
Duplicates are the whole difficulty of counting distinct items, and hashing removes it: equal items have equal hashes, so any statistic of the set of hash values ignores repetition. Flajolet and Martin (1985) observed that long runs of leading zeros are rare, so the longest run seen reveals the scale of the count. Their probabilistic counting refined it into an estimator with stochastic averaging over many bitmaps; LogLog (Durand & Flajolet, 2003) kept only one small maximum per register; HyperLogLog (Flajolet, Fusy, Gandouet & Meunier, 2007) changed how registers are averaged.
One item. Hash each item to a uniform bit string and let be the position of its first 1-bit, so :
The maximum. For over distinct items, independence gives a probability near 0 when and near 1 when . So , and estimates only up to a constant factor:
Stochastic averaging. Use the first hash bits to send each item to one of registers, so each register sees about items and keeps , the largest of the remaining bits. A single register with an unusually long run would dominate an arithmetic mean of , so HyperLogLog takes a harmonic mean:
Accuracy. Flajolet et al. proved that is asymptotically unbiased, with relative standard error
import hashlib, math
def h64(x):
return int.from_bytes(hashlib.blake2b(str(x).encode(), digest_size=8).digest(), 'big')
class HyperLogLog:
def __init__(self, b=10): # m = 2^b registers
self.b, self.m = b, 1 << b
self.M = [0] * self.m
def add(self, x):
h = h64(x)
j = h >> (64 - self.b) # first b bits pick a register
w = h & ((1 << (64 - self.b)) - 1) # the remaining 64 - b bits
rho = (64 - self.b) - w.bit_length() + 1 # position of the first 1-bit
self.M[j] = max(self.M[j], rho)
def count(self):
m = self.m
E = 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in self.M)
zeros = self.M.count(0)
if E <= 2.5 * m and zeros: # small counts: linear counting
E = m * math.log(m / zeros)
return EWith registers, repeated runs on 100,000 distinct items gave a root-mean-square relative error of about 3.2%, matching . Below the estimator switches to linear counting on the number of empty registers, which is more accurate for small counts.
About how many HyperLogLog registers do you need for a standard error of 1%?
Show the answer
10816 registers
Solve : . Implementations round to a power of two, , for 0.81%: the 12-kilobyte configuration with 6-bit registers.
Merging, practice and the frontier
| Summary | Merge rule | Deletions |
|---|---|---|
| Bloom filter | bitwise OR (same , same hash functions) | no |
| Count-Min sketch | add the arrays (same hash functions) | yes, with the median estimator |
| Count sketch, AMS | add the arrays (linear sketches) | yes |
| HyperLogLog | register-wise maximum | no |
| Misra–Gries heavy hitters | add the counters, then subtract the -st largest count | no |
Servers A and B each keep a HyperLogLog of the user IDs they saw today, with the same hash function and the same . Some users visited both. How do you get the number of distinct users overall?
- Add the two estimates
- Average the two register arrays, then estimate
- Take the register-wise maximum of the two arrays, then estimate
- Add the two register arrays, then estimate
Show the answer
C. Take the register-wise maximum of the two arrays, then estimate
Each register stores the maximum over the hashes routed to it, and the maximum over the union of two sets is the maximum of the two maxima. The merged array is exactly the sketch that one server would have built from both streams, so users seen by both are counted once.
Sketches are infrastructure now. Redis's PFCOUNT is a HyperLogLog with registers (12 KB, standard error 0.81%); many SQL engines offer approximate distinct counts; Google's HyperLogLog++ (Heule, Nunkesser & Hall, 2013) added 64-bit hashing, empirical bias correction and a sparse representation for small counts; network monitors track heavy flows with Count-Min; and open-source libraries such as Apache DataSketches package mergeable sketches for distinct counts, frequencies and quantiles.
Key takeaways
- Counting distinct items exactly needs memory linear in the universe, and deterministic approximation is not much cheaper; randomized -approximations need only kilobytes.
- Count-Min: width , depth , never underestimates, and overestimates by more than with probability at most (Markov in each row, independence across rows).
- Random signs make estimates unbiased: the Count sketch has error with columns, and AMS estimates with from 4-wise independent signs.
- HyperLogLog keeps the longest leading-zero run per register and combines registers by a harmonic mean, for standard error about ; Kane, Nelson and Woodruff (2010) achieved the optimal bits.
- Linear sketches merge by addition and HyperLogLogs by register-wise maxima, so each machine summarizes its own data and the summaries combine exactly.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the Count-Min proof, what role does the constant in the width play?
- It makes each row's estimate unbiased
- It is required for Markov's inequality to apply
- It makes each row fail with probability at most , and that choice minimizes the total number of counters
- It is the base of the logarithm in the number of distinct items
Show the answer
C. It makes each row fail with probability at most , and that choice minimizes the total number of counters
Markov gives per-row failure for width , and independent rows then fail together with probability at most . The product is minimized at . Any constant would work, with more counters.
The AMS estimator of uses random signs . Where is 4-wise independence of the signs needed?
- To make
- To bound , which involves and hence products of four signs
- To make an integer
- It is not needed: pairwise independence gives the same guarantee
Show the answer
B. To bound , which involves and hence products of four signs
The mean needs only for , which pairwise independence provides. The variance needs unless the indices pair up, a property of 4-wise independence; it yields .
Why does HyperLogLog combine its registers with a harmonic mean of rather than an arithmetic mean of ?
- A single register with an unusually large maximum would dominate an arithmetic mean of ; the harmonic mean damps such outliers
- The harmonic mean is cheaper to compute
- The harmonic mean makes the estimate exact for small counts
- Registers can be negative, and the harmonic mean handles negative values
Show the answer
A. A single register with an unusually large maximum would dominate an arithmetic mean of ; the harmonic mean damps such outliers
has a heavy right tail: one register that happens to see a long run of zeros contributes an enormous term. Averaging and inverting bounds each register's influence, which is why HyperLogLog reaches LogLog's accuracy with about 64% of its memory (standard error against ).
Further reading
- G. Cormode & S. Muthukrishnan, "An improved data stream summary: the count-min sketch and its applications," Journal of Algorithms 55(1) (2005), 58–75.
- N. Alon, Y. Matias & M. Szegedy, "The space complexity of approximating the frequency moments," Journal of Computer and System Sciences 58(1) (1999), 137–147 (STOC 1996).
- P. Flajolet, É. Fusy, O. Gandouet & F. Meunier, "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm," Proceedings of the Conference on Analysis of Algorithms (AofA) (2007).
- D. M. Kane, J. Nelson & D. P. Woodruff, "An optimal algorithm for the distinct elements problem," Proceedings of ACM PODS (2010), 41–52.
- G. Cormode & K. Yi, Small Summaries for Big Data (Cambridge University Press, 2020).