Algorithms · Counting & data
HyperLogLog
How Reddit counts views without remembering every viewer. Counting millions of unique visitors in about 12 kilobytes, using coin flips.
The problem
Reddit wants to show how many unique people viewed each post. If you refresh a post five times, that's still one view. So the counter has to know whether it has seen you before, and it has to do that for every post at once.
Reddit's 2017 post "View Counting at Reddit" describes solving this with HyperLogLog (HLL), stored in Redis. The surprise is that it never stores who the viewers were.
The obvious way
Keep a set of every viewer id per post. Adding an id twice changes nothing, so len(set) is the exact unique count. The catch is memory: the set grows in proportion to the number of unique viewers. A hugely popular post needs a hugely big set, and every post needs its own.
The clever idea
Imagine flipping a coin until you get heads, and bragging about your longest streak of tails. If someone says "I once got 10 tails in a row," you'd guess they flipped a lot of times. A long streak is rare, so it hints at lots of attempts.
HLL does this with numbers. It turns each viewer id into a random-looking number with a hash function, then splits the hashes across a few buckets. Each bucket remembers only one thing: its longest run of leading zeros. Seeing the same viewer twice gives the same hash, so repeats change nothing.
How the code does it
Look at the add method. The hash is split in two: the top 6 bits choose one of 64 buckets, and the remaining bits are checked for leading zeros. The register only ever goes up, via max, so a viewer who returns just recomputes the same value.
Then the formula turns 64 small numbers into one estimate. Run it: the bar chart shows exact and estimated counts landing close together. The last chart, from the memory line, compares a set that grew with every viewer to 64 registers that never grew. The set size is approximate, since getsizeof doesn't count the strings inside it.
Trade-offs
You pay with accuracy: the answer is an estimate, not the truth, and you can't ask "did user X view this?" or list the viewers. Our 64 registers are rough. Redis HLLs use about 12 KB with a standard error around 0.81%. Don't use HLL when you need exact numbers, such as billing, or when you need to look up individuals.
Where else you’ll see it
Any "how many distinct X?" question at scale, such as unique visitors or distinct search queries, is a candidate. Redis ships HLL as a built-in feature, which is how Reddit used it.
A viewer opens the same post 50 times. What happens to the HLL registers after the first visit?
- Nothing changes, since the same hash gives the same values
- The estimate goes up 50 times
- The viewer is removed from the buckets
Show the answer
Nothing changes, since the same hash gives the same values. The same id always hashes to the same bucket and zero-run, and a register only keeps its maximum, so repeats can't change it.
- Change B = 6 to 8
- Change B = 6 to 4
- Change n * 3 to n * 10
- Add 100000 to the loop
The code
Python, with what each line means beside it. It compares the clever way with a set of every viewer id.
import hashlib, math, sysBring in hashing, math and size tools B = 6 # 6 bits pick the bucketUse 6 bits to choose a bucketM = 2 ** B # 64 registersThat gives 64 buckets def h(item):Define a hash helper d = hashlib.sha256(str(item).encode()).digest()Scramble the item into fixed bytes return int.from_bytes(d[:8], "big") # a 64-bit numberTurn the first 8 bytes into a number class HLL:Define the counter class def __init__(self):Set up the counter self.regs = [0] * MStart all 64 registers at zero def add(self, item):Define how to add a viewer x = h(item)Hash the viewer bucket = x >> (64 - B) # top bits choose the bucketTop bits pick which bucket rest = x & ((1 << (64 - B)) - 1) # the remaining bitsKeep the other bits zeros = (64 - B) - rest.bit_length() # leading zeros in restCount the zeros at their start self.regs[bucket] = max(self.regs[bucket], zeros + 1)Remember the longest zero-run per bucket def count(self):Define how to get the estimate z = sum(2.0 ** -r for r in self.regs)Add up a score from every register est = 0.709 * M * M / zTurn that score into an estimate empty = self.regs.count(0)Count the buckets never touched if est <= 2.5 * M and empty: # small-count correctionIf the count is small, use a fix est = M * math.log(M / empty)Use the empty buckets instead return round(est)Return the rounded estimate for n in (100, 1000, 10000):For each audience size seen, hll = set(), HLL()Make an exact set and an HLL for i in range(n * 3): # every viewer shows up 3 timesReplay each viewer three times viewer = "user" + str(i % n)Build a viewer id seen.add(viewer)Add it to the set hll.add(viewer)Add it to the HLL show([len(seen), hll.count()], f"{n} viewers: exact vs HLL")Chart exact versus estimated count show([sys.getsizeof(seen), sys.getsizeof(hll.regs)], "bytes: set vs 64 registers")Chart memory used by each approach- the whole trick lines 16–19Top bits pick a bucket. The rest are checked for leading zeros. The register keeps only the biggest, so repeat viewers change nothing.
- averaging buckets lines 22–23Rare long runs make one bucket noisy, so the formula blends all 64 registers into one estimate.
- small counts lines 25–26With few viewers, many registers are still empty. Counting empty buckets is more accurate than the main formula.
- repeats lines 31–34Each viewer is added three times. The set ignores duplicates by design, and HLL does too, because equal ids hash equally.
Read more
- redditinc.com: HyperLogLog
- Ask Bento: Why does more registers mean better accuracy?
- Ask Bento: How does Redis store HLLs?
- Ask Bento: What is a Bloom filter?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.