· 7 min read
HyperLogLog: how to count unique items at scale
HyperLogLog counts millions of unique visitors in 12 KB with under 1% error. How it works, how to size it, and why merging makes it scale.

HyperLogLog is a probabilistic data structure that estimates how many distinct items you have seen, using a fixed few kilobytes of memory no matter how many items there are. With 16,384 small registers it counts unique visitors, IPs or search terms to within about 0.81% typical error, where an exact count would need to store every item. It also merges cleanly, so per-server or per-hour counts combine into a total without any rescanning.
That makes it the standard answer to "how many unique X?" once X gets large.
Why is counting unique items expensive at scale?
Counting distinct values, often called cardinality estimation, sounds trivial: put every item in a set and read its size. The problem is that the set has to remember every item it has ever seen. A million unique user IDs as strings is tens of megabytes before hash table overhead. Ten million per day, per page, per country, kept for a year, is no longer a counter. It's a second database.
It gets worse in distributed systems. If ten servers each count their own unique visitors, you can't add the numbers, because the same visitor may have hit several servers. To get the true total you have to ship all the raw IDs to one place and deduplicate them.
COUNT(DISTINCT user_id) in SQL has the same shape. The database has to sort or hash every value, and the work grows with the data.
HyperLogLog trades exactness for a fixed memory cost and a known error bar. For dashboards, analytics and rate signals, "about 1.2 million, give or take 1%" is usually all anyone needs.
How does HyperLogLog work?
The core idea comes from coin flips. If someone tells you the longest run of heads they flipped in a row was 10, you can guess they flipped roughly 2¹⁰ times. Long runs are rare, so seeing one tells you a lot about how many tries happened.
HyperLogLog applies this to hashes. A good hash turns each item into bits that look random, so the number of leading zeros behaves like a run of coin flips. Hash every item, track the most leading zeros you have seen, and that maximum hints at how many distinct items went in. Duplicates hash to the same value, so they never change the answer. That's what makes it count distinct items rather than total items.
One maximum on its own is very noisy. HyperLogLog fixes that with registers, small counters that each track their own maximum:
- Hash the item to 64 bits.
- Use the first
pbits to pick one ofm = 2^pregisters. - Count the leading zeros in the remaining bits, plus one. Call that the rank.
- If the rank is bigger than the register's current value, store it.
To estimate the count, combine all registers with a harmonic mean, an average that is less sensitive to a few unusually large values. A correction constant fixes the bias, and a separate formula handles small counts where many registers are still empty.
Here's a complete working version:
import hashlib, math
class HLL:
def __init__(self, p=14):
self.p = p
self.m = 1 << p
self.reg = bytearray(self.m)
self.alpha = 0.7213 / (1 + 1.079 / self.m)
def add(self, item):
x = int.from_bytes(hashlib.sha256(item.encode()).digest()[:8], "big")
idx = x >> (64 - self.p) # first p bits pick a register
rest = x & ((1 << (64 - self.p)) - 1) # remaining bits
rank = (64 - self.p) - rest.bit_length() + 1 # leading zeros + 1
if rank > self.reg[idx]:
self.reg[idx] = rank
def count(self):
z = sum(2.0 ** -r for r in self.reg)
est = self.alpha * self.m * self.m / z
zeros = self.reg.count(0)
if est <= 2.5 * self.m and zeros: # small-range correction
est = self.m * math.log(self.m / zeros)
return round(est)
def merge(self, other):
self.reg = bytearray(max(a, b) for a, b in zip(self.reg, other.reg))
With p=14, adding 1,000 IDs gives an estimate of 992. Adding 100,000 gives 99,727, and 1,000,000 gives 1,003,079. Adding every ID a second time leaves each estimate unchanged. All three land well inside the expected error.
How accurate is HyperLogLog, and how much memory does it use?
The standard error is about 1.04 / √m. You only choose p, and that sets both memory and accuracy. Registers rarely need more than 6 bits, which is how production versions pack them:
| p | Registers (m) | Memory at 6 bits each | Standard error |
|---|---|---|---|
| 10 | 1,024 | 768 bytes | ~3.25% |
| 12 | 4,096 | 3 KB | ~1.63% |
| 14 | 16,384 | 12 KB | ~0.81% |
| 16 | 65,536 | 48 KB | ~0.41% |
Each step of 2 in p quadruples memory and halves the error. Note that the memory does not depend on how many items you count. 12 KB covers a thousand items or a billion.
"Standard error" is a statistical promise, not a cap. Roughly two thirds of estimates land within one standard error, and about 95% within two. At p=14 that means most counts are within 1.6%, and occasionally one is a bit further off.
Redis ships this as a built-in type. PFADD adds items, PFCOUNT returns the estimate, and PFMERGE combines keys. It uses the p=14 setup, so each key costs up to 12 KB with a 0.81% standard error. It also stores small counts in a compact sparse form until they grow.
PFADD visitors:2026-11-27 user:81 user:93 user:81
PFCOUNT visitors:2026-11-27 -> 2
PFMERGE visitors:week visitors:2026-11-21 visitors:2026-11-22 ...
PFCOUNT visitors:week
Many analytics databases expose the same idea as an approximate distinct count function, usually a HyperLogLog variant under the hood.
Why does merging matter?
Merging is the feature that makes HyperLogLog fit distributed systems. Two sketches built with the same p and the same hash merge by taking the maximum of each register pair. The result is exactly the sketch you would have gotten by adding both streams to one counter.
In the test above, one sketch got users 0 to 599,999 and another got users 400,000 to 999,999. The 200,000 users in the overlap were counted by both. The merged sketch estimated 1,003,079, the same as adding all million users to a single sketch, because the registers came out identical.
That unlocks a few patterns:
- Count per node, merge centrally. Each server keeps its own sketch and ships 12 KB instead of a list of IDs.
- Count per time bucket, merge for ranges. Keep one sketch per hour. Uniques for any day or week is a merge of the right buckets, with no reprocessing. Old buckets expire on their own.
- Count per dimension, merge for rollups. One sketch per country or per page, merged when someone asks for the total.
You can't do any of that with plain counters, since adding unique counts double-counts overlaps.
When should you use HyperLogLog?
Use it when you need distinct counts over large or unbounded streams and a small, known error is fine: unique visitors, active users, distinct IPs hitting an endpoint, distinct search queries, unique devices per account.
Don't use it when:
- You need exact numbers. Billing, quotas and anything legal or financial should count exactly.
- You need to know whether a specific item was seen. HyperLogLog only gives a count. Membership is what a Bloom filter is for.
- You need to remove items. Registers only ever grow, so there's no delete. Time buckets that expire are the usual workaround.
- You need intersections. "Users in both A and B" can be computed from merges with inclusion-exclusion, but the error grows fast when the overlap is small compared to the sets.
- Counts are small. Below a few thousand items, an exact set is cheap and has no error.
Key takeaways
- HyperLogLog estimates distinct counts in fixed memory, typically 12 KB for 0.81% standard error.
- It works by hashing items and tracking the longest run of leading zeros across many registers.
- Duplicates never change the estimate, and memory doesn't grow with the number of items.
- Sketches merge losslessly, so per-server and per-hour counts roll up into totals.
- Use it for analytics and monitoring, not for exact counts, membership checks or deletes.
FAQ
Is HyperLogLog accurate enough for analytics dashboards?
Usually yes. At the common 12 KB setting, most estimates are within about 1.6% of the true count, which is less than the noise from bots, retries and timezone choices in most metrics.
Can HyperLogLog count more than a few billion items?
Yes. With 64-bit hashes it handles cardinalities far beyond what most systems ever see, and the memory stays the same.
What's the difference between HyperLogLog and a Bloom filter?
A Bloom filter answers "have I seen this item?" A HyperLogLog answers "how many different items have I seen?" Neither stores the items themselves.