System design paper · 2007
HyperLogLog
How HyperLogLog estimates a distinct count in about 1.5 kB with roughly 2% error, and what Google and others changed to make it work in production.
You’ll learn to
- Explain why a hash that starts with many zeros hints at how many distinct items were seen.
- Trace an item through a HyperLogLog sketch and read an estimate from its small counters, called registers.
- Work out the memory and the typical error for a given number of registers.
- Name what Google, Redis and others added to the original algorithm, and why.
The idea in short
Counting how many different users, IPs or search terms you have seen is easy with a set, but the set grows with the data. HyperLogLog gives an estimate instead, using a small, fixed amount of memory: the paper’s example is about 1.5 kB, which can count billions of items with an error near 2%.
Hash every item to random-looking bits. Use the first few bits to pick one of many small counters. In each counter keep one number: the longest run of zeros seen at the start of the remaining bits. A long run of zeros is rare, so it hints at how many items there were. A careful average of the counters gives the estimate, and two sketches merge by keeping the larger value in each counter.
The problem
Suppose you run a website and want to know how many different people visited last week. Not the number of visits: the number of distinct visitors, with repeat visits counted once. This is a . The paper calls it the cardinality of the data.
The exact way is to keep a set. For every visitor ID, check whether the set already has it. If not, add it. At the end, the answer is the size of the set. It is correct, simple and fine for small data.
It stops working as the data grows, for two reasons. The set has to remember every distinct item, so memory grows with the answer. As an example, a billion IDs of 8 bytes each is 8 GB for one counter, and a real system wants many counters: one per page, per country, per day. And two sets cannot be combined without keeping both in full, which makes it hard to count across many machines.
Philippe Flajolet and his co-authors, Éric Fusy, Olivier Gandouet and Frédéric Meunier, published a different answer in 2007. Their algorithm, , gives up exact answers. In return it gets a number close to the truth from one pass over the data, in about a kilobyte or two. The paper’s own example uses 2,048 small counters and about 1.5 kB. It estimates counts beyond a billion with a typical error of about 2%.
The result is called a : a small summary that answers one kind of question about a large data set, approximately. This sketch answers “how many distinct items?” and nothing else.
HyperLogLog improves on an earlier algorithm, LogLog, from 2003. The paper’s main claim is that it matches LogLog’s accuracy with about 64% of the memory, and that no algorithm of this kind can do much better.