Bloom Filters and HyperLogLog in Go: Trading a Little Error for a Lot of Memory
December 5, 2026 · 10 min read · Lire en français
Contents
Some answers get dramatically cheaper if you let them be slightly wrong, provided you decide in advance how wrong.
Take a million 64-bit IDs. Storing them exactly takes at least 8 MB. Answering "have I seen this one before?" about them takes 1.2 MB, at the price of a false "yes" about one time in 120. Answering "how many distinct IDs are there?" takes 12 KB, at the price of an error under 1%. Neither number is a guess: each comes from a formula you can derive, and that derivation is what this article is about.
It is the fifth in a series on the math inside distributed systems, after gossip protocols. The two structures here, the Bloom filter and HyperLogLog, both start from the same move: hash the input into something that looks uniformly random, then reason about it with probability. The code is Go, and every number comes from running it.
Bloom filter: remember without storing
A Bloom filter answers one question, "is this item in the set?", using an array of m bits (all zero at first) and k hash functions.
- Add: hash the item
ktimes, givingkpositions, and set those bits to 1. - Has: hash the item
ktimes and check those positions. If any bit is 0, the item is definitely not in the set. If all are 1, it is probably in the set.
The answer is lopsided by design. A "no" is certain. A "yes" can be wrong, because other items may have set exactly those bits by coincidence. That is a false positive.
type Bloom struct {
bits []uint64
m uint64
k int
}
// Double hashing: position i is h1 + i*h2, so two hashes give k positions.
func (b *Bloom) idx(x uint64, i int) uint64 {
h1, h2 := mix(x), mix(x^0xdeadbeefcafef00d)|1
return (h1 + uint64(i)*h2) % b.m
}
func (b *Bloom) Add(x uint64) {
for i := 0; i < b.k; i++ {
p := b.idx(x, i)
b.bits[p/64] |= 1 << (p % 64)
}
}
func (b *Bloom) Has(x uint64) bool {
for i := 0; i < b.k; i++ {
p := b.idx(x, i)
if b.bits[p/64]&(1<<(p%64)) == 0 {
return false // one zero bit proves the item was never added
}
}
return true
}
Computing k independent hashes is costly, so the code derives all k positions from two hashes (h1 + i·h2), a standard trick with the same error rate in practice. mix is a fast 64-bit mixing function, and as in the consistent hashing article, a weak hash would break the math below.
There are no false negatives. Add only ever turns bits from 0 to 1 and nothing turns them back, so an item that was added always finds all its bits set. In my runs, out of 100,000 added items, zero were reported missing.
The math: where the false positive rate comes from
Insert n items into m bits with k hashes. That is kn bit-settings in total. After one setting, a given bit is still 0 with probability 1 − 1/m. After all kn settings:
P(bit is still 0) = (1 − 1/m)^(kn) ≈ e^(−kn/m)
(The approximation is the classic limit (1 − 1/m)^m → 1/e.) So the fraction of bits that are 1 is about 1 − e^(−kn/m). A non-member is a false positive if all its k probed bits happen to be 1:
p ≈ (1 − e^(−kn/m))^k
How many hashes should you use? More hashes mean more bits to match (fewer false positives), but also more bits set (more collisions). Setting the derivative to zero gives the best value:
k = (m/n) · ln 2
At that k, exactly half the bits are 1, and the rate becomes p = 2^(−k). Solving for the size gives the formula worth remembering:
m/n = −ln p / (ln 2)² ≈ 1.44 · log₂(1/p) bits per item
For a 1% false positive rate that is about 9.6 bits per item, whatever the size of the items. A URL of 100 bytes and an ID of 8 bytes cost the same in the filter.
Checking the formula
I inserted 100,000 items and probed 2 million items that were never added, at several sizes with the optimal k:
| Bits per item | k | Predicted false positives | Measured |
|---|---|---|---|
| 5 | 3 | 9.18% | 9.17% |
| 10 | 7 | 0.82% | 0.83% |
| 15 | 10 | 0.074% | 0.077% |
| 20 | 14 | 0.0067% | 0.0065% |
The prediction holds to the second digit. Each extra 5 bits per item divides the error by about 10. The same test at 10 bits per item with other values of k shows the optimum is real:
k | 1 | 2 | 4 | 7 | 10 | 14 |
|---|---|---|---|---|---|---|
| Predicted | 9.52% | 3.29% | 1.18% | 0.82% | 1.02% | 1.90% |
| Measured | 9.53% | 3.30% | 1.19% | 0.83% | 1.02% | 1.90% |
Too few hashes fail to discriminate. Too many fill the array. The minimum is at k = 7, as (m/n) · ln 2 = 6.9 predicts.
The formula also warns you about overfilling. A filter sized for 100,000 items (10 bits each, k = 7) but fed more:
| Items inserted | 1x capacity | 1.5x | 2x | 3x |
|---|---|---|---|---|
| Predicted false positives | 0.82% | 4.91% | 13.78% | 40.08% |
| Measured | 0.83% | 4.92% | 13.87% | 40.27% |
The filter does not fail loudly. It quietly becomes useless. Size it for the largest n you expect.
HyperLogLog: count without remembering
The second question is different: not "have I seen this?" but "how many distinct items have I seen?". Counting exactly needs a set of everything seen. HyperLogLog (HLL) needs a few kilobytes.
The idea comes from coin flips. If someone tells you the longest streak of heads they ever saw was 10 in a row, you would guess they flipped the coin on the order of a thousand times: a streak of 10 has probability 1/2^10, about 1 in 1,000, so it takes roughly that many tries to see one. The longest streak of luck is a clue to how many attempts there were.
Do the same with hashes. A good hash makes every bit a fair coin flip. For each item, count the position of the first 1-bit (its rank). Then:
P(rank ≥ r) = 2^(−(r−1))
If the highest rank you have seen is R, a good guess for the number of distinct items is about 2^R. Repeated items give the same hash, so duplicates change nothing, which is exactly what "distinct" requires.
The math: from one lucky run to 1.04/√m
A single maximum is a terrible estimator: it can only be a power of two, and one unlucky or lucky item swings it by a factor of two. The fix has three steps.
- Split into
m = 2^pregisters. Use the firstpbits of the hash to pick a register, and the remaining bits to compute the rank. Each register keeps the maximum rank it has seen. Each register sees aboutn/mitems. - Average the estimates. Each register gives its own estimate
2^(M_j)ofn/m. An ordinary average is dominated by one lucky register with a huge rank. The harmonic mean damps outliers, because it averages the inverses2^(−M_j)and a large rank contributes almost nothing:E = α_m · m² / Σ 2^(−M_j)α_mis a constant (about 0.7213 for largem) that corrects a small systematic bias. - Error shrinks as
1/√m. Averagingmroughly independent estimates cuts the random error by√m, the same law as the1/√Vin the consistent hashing article. For HLL the constant is 1.04:standard error ≈ 1.04 / √m
For very small counts, many registers are still empty, and the formula switches to linear counting, m · ln(m/V) with V the number of empty registers.
func (h *HLL) Add(x uint64) {
v := mix(x)
j := v >> (64 - h.p) // first p bits choose the register
w := v<<h.p | (1 << (h.p - 1)) // remaining bits, with a sentinel
rank := uint8(bits.LeadingZeros64(w)) + 1 // position of the first 1-bit
if rank > h.reg[j] {
h.reg[j] = rank
}
}
func (h *HLL) Count() float64 {
m := float64(len(h.reg))
var sum float64
zeros := 0
for _, r := range h.reg {
sum += math.Pow(2, -float64(r))
if r == 0 {
zeros++
}
}
e := 0.7213 / (1 + 1.079/m) * m * m / sum
if e <= 2.5*m && zeros > 0 { // small range: linear counting
return m * math.Log(m/float64(zeros))
}
return e
}
Checking the formula
I counted 100,000 distinct items, 200 times per setting, and measured the spread of the relative error:
Registers m | Memory (6 bits each) | Predicted 1.04/√m | Measured |
|---|---|---|---|
| 64 | 48 B | 13.0% | 14.9% |
| 256 | 192 B | 6.5% | 6.9% |
| 1,024 | 768 B | 3.25% | 3.1% |
| 4,096 | 3 KB | 1.62% | 1.47% |
| 16,384 | 12 KB | 0.81% | 0.77% |
The formula tracks the measurements, with the largest gap at the tiny m = 64, where the asymptotic constants are least accurate. Multiplying the memory by 4 halves the error, as 1/√m says. Twelve kilobytes count to under 1%. A rank never exceeds 64, which fits in 6 bits, so 6 bits per register is enough (my code uses a whole byte for simplicity).
It also does not care how large the count is. At m = 16,384, over 100 runs each, the standard error was 0.73% at 100,000 distinct items and 0.79% at 1,000,000, with no measurable bias. Note that 0.81% is a standard deviation, not a limit. In one single run on 1,000,000 items my estimate was off by +2.3%, nearly three standard errors, a draw you will see once in a few hundred runs.
Merging: the join again
Two sketches built over different data can be combined by taking the maximum of each register:
func (h *HLL) Merge(o *HLL) {
for i, r := range o.reg {
if r > h.reg[i] {
h.reg[i] = r
}
}
}
That is a join, as in the CRDT article: commutative, associative and idempotent. I built one sketch over items 0 to 59,999 and one over 40,000 to 99,999, merged them, and compared with a sketch built directly on the union. The registers were identical. Overlap is handled for free (the 20,000 shared items count once), and sketches from many servers can be merged in any order, which is why HLL fits distributed counting.
Where they are used
- Bloom filters guard slow lookups. Cassandra, HBase and RocksDB keep one per on-disk file: before reading a file for a key, ask its filter. A "no" skips the disk read entirely, and a false "yes" only costs one wasted read.
- HyperLogLog counts distinct things at scale: unique visitors, distinct queries, distinct IPs. Redis exposes it as
PFADD,PFCOUNTandPFMERGE, using 12 KB per key for a 0.81% error, the same settings as the last row above.
Limits
- No deletion from a Bloom filter. Clearing a bit could erase other items sharing it. Counting Bloom filters (counters instead of bits) and cuckoo filters support deletion, at more memory.
- You cannot list or resize. A Bloom filter stores no items, so you cannot enumerate it or grow it without the original data. Size it for the maximum
n, as the overfill table showed. - The error is a statistic, not a guarantee. The Bloom rate is an average over non-members, and HLL's 0.81% is a standard deviation. Individual runs can stray.
- HLL counts, it does not remember. It cannot tell you whether a given item was seen. For that, use the Bloom filter.
- Both depend on the hash. The formulas assume bits that behave like fair coin flips. A weak hash breaks them silently.
- Idealized test. My inputs were sequential integers, mixed by a strong hash. Real keys are strings and are skewed, which makes the choice of hash matter even more.
Takeaways
- Some questions are far cheaper to answer approximately, if the error is bounded by a formula you can compute in advance.
- A Bloom filter uses
mbits andkhashes. Its false positive rate is(1 − e^(−kn/m))^k, minimized atk = (m/n) ln 2, which costs about1.44 · log₂(1/p)bits per item: 9.6 bits for 1%. - It never gives a false negative, and it degrades quietly when overfilled: 13.9% false positives at twice its capacity in my test.
- HyperLogLog counts distinct items from the longest run of leading zeros, split across
mregisters and combined with a harmonic mean. Its standard error is1.04/√m: 12 KB for 0.81%. - HLL sketches merge by register-wise maximum, a join, so unions and distributed counts come for free.
Next in the series: erasure coding, and how algebra over finite fields rebuilds lost data from fragments.
Subscribe to future posts
Get future posts in your inbox. No spam, unsubscribe any time.
Related posts
Gossip Protocols in Go: Why a Rumor Reaches Every Node in Logarithmic Time
One node learns something and no one is in charge. Each round, every node talks to one random peer. The news reaches 100,000 nodes in about 29 rounds, or 14 with a better exchange rule. We derive why with a few lines of math (doubling, then a tail that behaves very differently for push and pull), then check every formula against a Go simulation.
November 23, 2026
CRDTs in Go: Merging Replicas Without Conflicts
Two replicas receive updates in different orders, some twice, and must still end up identical, with no leader and no locks. Three equations about a merge function make that possible. We explain them with a counterexample for each, then build four CRDTs in Go (G-Counter, PN-Counter, LWW-Register, OR-Set) and check convergence on 1.5 million random merges.
November 19, 2026
Lamport and Vector Clocks in Go: Ordering Events Without a Shared Clock
Two servers write the same key and your logs say one came 3 ms before the other. Can you trust that? Not without a shared clock. We build Lamport and vector clocks in Go, explain the small amount of math behind them (partial orders, the happened-before relation, component-wise comparison), and test both against 6.7 million event pairs to see exactly what each one can and cannot tell you.
November 14, 2026