How HyperLogLog estimates a cardinality

Short answer: HyperLogLog estimates the number of distinct items in a stream from the position of the first 1-bit in each item’s hash. Items are bucketed by the first p bits of the hash, into m = 2^p registers. Each register stores the maximum number of leading zeros, plus one, seen in that bucket. The estimate is a harmonic mean of 2 raised to those registers, multiplied by a bias constant near 0.7213 / (1 + 1.111/m), times m². The relative error is about 1.04 / sqrt(m). The sketch does not store the items.


What the problem actually asks

An exact cardinality stores every distinct key. A stream that is larger than memory cannot. Leading zeros of a uniform hash are a geometric random variable: the chance the first 1 appears at bit k is 2^{−k}. The maximum of many such variables encodes how many hashes were observed, and the harmonic mean across buckets reduces the variance of that very noisy maximum.

The raw estimate is biased for small cardinalities and saturates in a known way for huge ones. Practical implementations switch to a linear counting regime when many registers are still zero, and they correct the large-cardinality end. The paper’s raw formula is the middle regime.


What the algorithm guarantees

With m registers the standard error is about 1.04/sqrt(m), so m = 2^14 gives roughly one percent. Memory is m bytes if each register holds a small integer, which it does, because a leading-zero count fits in a few bits. The estimate is not an integer count of a stored set. Merging two sketches is a register-wise maximum, which is associative, so partial streams combine.

The hashes must be uniform and independent of the item structure. A weak hash that never sets high bits collapses the leading-zero statistic. The algorithm estimates cardinality. It does not estimate frequencies. A heavy-hitter sketch is count-min.


The working steps

  1. Choose p and set m = 2^p. Allocate m registers, initially zero.
  2. For each item, hash it to a wide integer. Use the top p bits as the bucket index. Count the leading zeros in the remaining bits and add one. Store the maximum of that value and the register.
  3. At query time, compute the harmonic raw estimate α_m · m² · (sum over registers of 2^{−register})^{−1}, with α_m the usual bias constant.
  4. If many registers are zero, or the estimate is huge relative to 2^{32} or the hash width, apply the small-range or large-range correction the implementation documents.
  5. To merge two sketches, take the maximum of each register pair.

The relative-error formula is for the raw estimator in its intended range, with uniform hashes. It is not an exact distinct count, and it is not a frequency. Small-range correction is part of a correct library implementation. Quoting 1.04/sqrt(m) for a sketch that skipped that correction misstates the error on a tiny set.


Approaches that look simpler and fail

Approach Why it fails when the registers are averaged arithmetically
Take the arithmetic mean of the registers The statistic is a maximum of geometric variables. The harmonic mean of the powers of two is the estimator that has the stated variance. An arithmetic mean is a different, biased formula.
Store the items and also keep the registers, then report the register estimate as exact The registers never become exact. If the items are stored, report the set size and skip the sketch.
Merge by adding registers The maximum leading-zero count of a union is the max of the counts, not the sum. Adding double-counts the same hash range.
Use a 32-bit hash for a cardinality near 2^32 The leading-zero statistic saturates. The hash width has to exceed the range where the large-cardinality correction would dominate.

Membership is a Bloom filter. Frequencies are a count-min sketch. Exact distinct counting is a hash set. HyperLogLog is the cardinality sketch.


A working example

This Python fragment hashes each item into one of 64 registers and keeps the longest run of leading zeros. The harmonic estimate, with the small-range correction when many registers are still zero, is the cardinality. One hundred distinct items, hashed into 1024 registers, estimate as 102 after the small-range correction.

import math
p = 10
m = 1 << p
registers = [0] * m

def hash32(item):
    x = (item + 0x9E3779B9) & 0xFFFFFFFF
    x = ((x ^ (x >> 16)) * 0x85EBCA6B) & 0xFFFFFFFF
    x = ((x ^ (x >> 13)) * 0xC2B2AE35) & 0xFFFFFFFF
    return (x ^ (x >> 16)) & 0xFFFFFFFF

for item in range(100):
    hashed = hash32(item)
    bucket = hashed >> (32 - p)
    rest = hashed & ((1 << (32 - p)) - 1)
    rank = (32 - p + 1) if rest == 0 else ((32 - p) - rest.bit_length() + 1)
    registers[bucket] = max(registers[bucket], rank)
alpha = 0.7213 / (1 + 1.079 / m)
raw = alpha * m * m / sum(2.0 ** (-rank) for rank in registers)
zeros = registers.count(0)
estimate = m * math.log(m / zeros) if zeros and raw <= 2.5 * m else raw
assert zeros and abs(estimate - 100) < 5
print(round(estimate))

Where it is used

Redis PFCOUNT and the approximate distinct-counts in warehouse engines are HyperLogLog. A dashboard of unique visitors uses it so the counter stays a few kilobytes. An exact set is the replacement when the error bar is unacceptable.


When you can drop this algorithm

Drop the sketch when the set fits in memory and an exact count is required. Keep it when a relative error near 1/sqrt(m) is acceptable and the stream of distinct items does not fit, and merge sketches by the register-wise maximum.


Why this stays published

We publish this so a search for HyperLogLog returns the leading-zero registers, the harmonic estimate, and the relative error 1.04/sqrt(m). HyperLogLog estimates set cardinality from the maximum leading-zero count in each hash bucket, with relative error about 1.04 over the square root of the number of buckets.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *