Probabilistic data structures
Trade a small, bounded error for huge memory savings: a Bloom filter answers "seen it?" with no false negatives, HyperLogLog counts distinct items, and Count-Min estimates frequencies, in kilobytes instead of gigabytes.
Analogy: A bouncer with a smudged guest list: if your name isn't on it, you're definitely not invited; if it seems to be, he double-checks your ID.
How it works
- Bloom filter: a negative is certain, a positive is "maybe"; ~9.6 bits per key gives 1% false positives.
- HyperLogLog counts distinct items in fixed memory: Redis uses 12 KB for 0.81% standard error.
- Count-Min sketch estimates frequencies and never underestimates; pair it with a heap for top-k.
- All three merge across shards or time windows: OR the bits, max the registers, sum the counters.
- Use them as a cheap first filter; confirm positives against the real store when errors matter.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your signup form checks a Bloom filter of taken usernames (1% false positives) and rejects a name whenever the filter says "present". Users complain that free names get rejected. Best fix?
Go deeper
Full explanation
Each structure answers one question approximately, in small fixed memory, and merges across shards and time windows.
- Bloom filter, "is x in the set?": an array of m bits and k hash functions. Adding x sets k bits; a lookup checks them. Any 0 means definitely absent; all 1s means probably present. No false negatives, tunable false positives: ~9.6 bits per key gives 1%. LSM engines keep one per file to skip disk reads (Storage engines: LSM-tree vs B-tree).
- HyperLogLog, "how many distinct?": hash each item and keep, per register, the longest run of leading zeros seen; rare patterns imply many items. Standard error ≈ 1.04/√m for m registers; Redis uses 12 KB for 0.81%. Merging is a per-register max, so it loses nothing.
- Count-Min sketch, "how often?": d rows of w counters; each item bumps one counter per row, and the estimate is the row minimum. It never underestimates; the error is at most ε·N with probability 1−δ. Pair it with a heap for top-k.
Use them as a cheap first filter, and confirm against the real data when an error matters.
Code A Bloom filter for crawler URL dedup
import hashlib, math
class BloomFilter:
def __init__(self, n: int, fp_rate: float):
# Optimal sizing for n items at the target false-positive rate
self.m = math.ceil(-n * math.log(fp_rate) / math.log(2) ** 2)
self.k = max(1, round(self.m / n * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item: str) -> list[int]:
d = hashlib.sha256(item.encode()).digest()
h1 = int.from_bytes(d[:8], "big")
h2 = int.from_bytes(d[8:16], "big") | 1
# Double hashing: k positions from two hashes
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item: str) -> None:
for p in self._positions(item):
self.bits[p // 8] |= 1 << (p % 8)
def might_contain(self, item: str) -> bool:
# Any 0 bit: definitely absent. All 1s: probably present.
return all(self.bits[p // 8] >> (p % 8) & 1 for p in self._positions(item))
seen = BloomFilter(n=1_000_000, fp_rate=0.01) # ~1.2 MB, k = 7
if not seen.might_contain(url):
seen.add(url)
crawl(url) # ~1% of new URLs are wrongly skippedReal example
Assume a web crawler must skip URLs it already fetched, out of 1B. An exact set at ~100 bytes per URL needs ~100 GB of RAM. A Bloom filter at 1% false positives needs ~9.6 bits per URL: ~1.2 GB. The price: ~1% of genuinely new URLs get skipped, acceptable for a crawl. The analytics team counts unique visitors per page per day with one HyperLogLog each: 12 KB per page instead of a set of every user id, merged weekly with PFMERGE.
Trade-offs +3 · −3
+ You gain
- Orders of magnitude less memory: ~1.2 GB instead of ~100 GB for 1B URLs.
- Constant-time updates and queries, a natural fit for streams.
- Mergeable: build per shard or per hour and combine without the raw data.
− You pay
- Approximate: you must design for false positives or overcounts.
- A plain Bloom filter can't delete (a cuckoo filter can) or list members; HyperLogLog can't name its items.
- Sized up front: past its planned capacity, a Bloom filter's false-positive rate climbs.
Use it when
Huge sets or streams where an approximate answer is fine: skipping disk reads in LSM stores, crawl dedup, unique-user counts, heavy hitters and hot keys.
Avoid it when
When an error is unacceptable and you can't verify it (billing, access control), or when the data is small enough to count exactly in memory.
Numbers to know 5
- Bloom: 1% false positives → ~9.6 bits/key and 7 hashes; 0.1% → ~14.4 bits/key and 10 hashes.
- Bloom sizing: m = −n·ln p / (ln 2)² bits; optimal k = (m/n)·ln 2.
- HyperLogLog standard error ≈ 1.04/√m; the paper counts beyond 10⁹ items at ~2% with 1.5 KB.
- Redis HyperLogLog: up to 12 KB, 0.81% standard error, up to 2^64 items.
- Count-Min: width w = ⌈e/ε⌉, depth d = ⌈ln(1/δ)⌉; overcount ≤ ε·N with probability 1−δ.
Common pitfalls 4
- Undersizing a Bloom filter: false positives climb as it fills past its planned capacity.
- Acting on a Bloom "yes" without checking the real store where a wrong yes matters.
- Trusting Count-Min estimates for rare items: collisions dominate them; only heavy hitters are reliable.
- Intersecting HyperLogLogs (users in A and B) by inclusion–exclusion: the error explodes for small overlaps.
Interview questions 3
Answer out loud first, then reveal.
Count unique viewers per video across 100 servers, in near real time.Show answer
Exact sets per video would hold every viewer id: too much memory at scale. I'd keep one HyperLogLog per video per time bucket on each server, 12 KB at 0.81% error in Redis, and merge with a per-register max. Merging is lossless, so hourly sketches roll up into days and shards combine freely. If finance needs exact numbers, a batch job computes them later from the event log.
Find the top 100 hashtags in a live stream of billions of posts.Show answer
A Count-Min sketch for counts plus a min-heap of 100. For each hashtag I increment the sketch, read its estimate and push it into the heap if it beats the heap's minimum. Memory stays fixed however many distinct tags appear. Estimates only overcount, so heavy hitters are reliable while rare tags are noisy, which is fine for top-k. One sketch per time window makes it "trending".
Why does an LSM store keep a Bloom filter per SSTable?Show answer
A point lookup may have to check many SSTables, and most don't hold the key. An in-memory Bloom filter answers "definitely not here" for those, so the engine skips their disk reads. At ~10 bits per key, only ~1% of those files still cost a wasted read. It doesn't help range scans, because the filter only knows exact keys.