Skip to content

Chapter 14: Probabilistic data structures

An exact set of a billion keys costs gigabytes; an exact count of distinct visitors needs to remember every visitor. Probabilistic data structures trade exactness for massive space savings: they give approximate answers with bounded error probabilities, which is exactly right for large-scale systems where exact answers are too expensive. A Bloom filter answers membership in about ten bits per element with a 1% false-positive rate; HyperLogLog counts billions of distinct items to within about 2% in 1.5 KB.

Concepts from other sections (4)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Bloom filter: an mm-bit array with kk hash probes per item, answering membership with no false negatives. Read more: 15.8 A Bloom filter
  • Double hashing: generating probes gi=h1+i h2g_i = h_1 + i\,h_2 from two hashes. Read more: 15.8 A Bloom filter
  • Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
  • Binary search tree (BST): a binary tree in which every node’s value is greater than every value in its left subtree and less than every value in its right subtree, so a search follows one root-to-leaf path and an in-order traversal yields the values in sorted order. Read more: Chapter 7: Trees

This chapter introduces four such structures: the Bloom filter for membership, the count-min sketch for frequencies, HyperLogLog for cardinality, and the skip list as a randomized alternative to balanced trees. For each it gives the mechanism, the error bound, and where it is used, and it ends with a space comparison against an exact hash set.

Learning objectives

  • Explain why a Bloom filter has false positives but no false negatives, and compute its false-positive rate and optimal number of hash functions.
  • Describe how a count-min sketch bounds its overcount and how to size it for a given error and confidence.
  • Explain how HyperLogLog estimates cardinality from leading zeros.
  • Describe the skip list and why it achieves expected O(log⁡n)O(\log n) operations.
  • Choose between exact and probabilistic structures by space, error, and deletion support.

You need hash functions and hash sets from Arrays and hashing, linked lists from Linked lists for the skip list, and basic probability; Probability and statistics in Mathematics covers what is needed. A production Bloom filter is built in full in the Bloom filter section of the systems chapter.

A Bloom filter tests set membership with two possible answers: “definitely not in the set” or “probably in the set.” It is an mm-bit array with kk hash functions. To insert xx, set the bits at h1(x),h2(x),…,hk(x)h_1(x), h_2(x), \dots, h_k(x); to query, check all kk bits. A bit is never cleared, so an inserted element always tests positive (no false negatives), but an absent element can find all its bits set by other insertions (a false positive).

class BloomFilter:
def __init__(self, size, num_hashes):
self.bits = [False] * size
self.size = size
self.num_hashes = num_hashes
def _hashes(self, item):
# Double hashing: h(i) = h1 + i*h2
h1 = hash(item) % self.size
h2 = hash(repr(item)) % self.size
return [(h1 + i * h2) % self.size for i in range(self.num_hashes)]
def add(self, item):
for h in self._hashes(item):
self.bits[h] = True
def might_contain(self, item):
return all(self.bits[h] for h in self._hashes(item))

Double hashing derives all kk positions from two hash values, which is as good as kk independent hashes in practice. After nn insertions, the false-positive rate is

p≈(1−e−kn/m)k,p \approx \left(1 - e^{-kn/m}\right)^k,

and it is minimized by choosing k=mnln⁡2k = \frac{m}{n} \ln 2. Bloom filters show up in spell checkers, cache lookups (skip the disk read when the key is definitely absent), database query optimization, and network routers.

A count-min sketch estimates frequencies: “how many times has xx appeared?”, with a bounded overcount. It is a d×wd \times w matrix of counters with dd hash functions, one per row. An insertion increments one counter in each row; a query returns the minimum of the dd counters for xx. Collisions only ever add to a counter, so every row overestimates, and the minimum is the least-polluted estimate.

With NN total insertions, choosing w=⌈e/ε⌉w = \lceil e/\varepsilon \rceil and d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil guarantees that the estimate exceeds the true count by at most εN\varepsilon N with probability at least 1−δ1 - \delta. Network traffic monitoring, trending topics, and heavy-hitter detection all use it.

HyperLogLog estimates cardinality (the number of distinct elements) in O(log⁡log⁡n)O(\log \log n) space. Hash each element and count the leading zeros of the hash. A hash with rr leading zeros turns up about once in 2r2^r distinct elements, so the maximum number of leading zeros seen estimates log⁡2\log_2 of the cardinality. Real implementations split the hashes into many buckets and average their estimates harmonically to reduce the variance.

In practice it reaches about 2% error with 1.5 KB of memory for billions of unique elements. Unique-visitor counting, databases’ APPROX_COUNT_DISTINCT, and Redis’s PFCOUNT are all HyperLogLog.

A skip list is a probabilistic alternative to a balanced binary search tree, with expected O(log⁡n)O(\log n) search, insertion, and deletion. It is a multi-level linked list: every element is on the bottom level, and each element is promoted to the next level up with probability 1/21/2, so each level has about half the elements of the one below. A search starts at the top level and moves right until the next element is too large, then drops down a level.

Compared with balanced trees, skip lists are simpler to implement, need no rotations, and lend themselves to lock-free concurrent versions. Redis sorted sets and LevelDB’s memtable use them.

The structures differ in space, the kind of error they make, and whether they support deletion. Compared with an exact hash set:

StructureSpaceFalse positivesDeletionsUse
hash setO(n)O(n)noneyesexact membership
Bloom filterO(1)O(1) per elementyes (about 1%)noapproximate membership
counting Bloom filterO(1)O(1) per elementyesyesmembership with deletion
count-min sketchO(1εlog⁡1δ)O(\frac{1}{\varepsilon} \log \frac{1}{\delta})overcountswith negative countsfrequency estimation
HyperLogLogO(log⁡log⁡n)O(\log \log n)about ±2%nocardinality

A plain Bloom filter cannot delete, because clearing a bit could remove other elements too; a counting Bloom filter replaces bits with small counters to allow it. Cuckoo filters also support deletion and are more space-efficient at low false-positive rates.

Interviewers and production systems use these structures in different ways. As a rough guide:

CompanyFocusDifficulty
GoogleBloom filters in Bigtable, HyperLogLogMedium-Hard
Netflixstreaming cardinality estimationMedium
Databricksapproximate query processingMedium-Hard
AmazonBloom filters in DynamoDBMedium
Striperate limiting with count-min sketchMedium
  • Probabilistic data structure: a structure that answers membership, frequency, or cardinality queries approximately, with a bounded error probability, in far less space than an exact structure would need.
  • Counting Bloom filter: a Bloom filter whose bits are replaced by small counters, so an element can be deleted by decrementing its counters; it supports deletion at the cost of several times the space.
  • Count-min sketch: a d×wd \times w array of counters with one hash function per row; an insertion increments one counter in each row and a query returns the minimum of its dd counters, which never undercounts and overcounts by at most εN\varepsilon N with probability at least 1−δ1 - \delta.
  • HyperLogLog (HLL): a cardinality estimator that hashes each element and records the most leading zeros seen in each of many buckets, then combines the buckets with a harmonic mean; it counts billions of distinct items to within about 2% in about 1.5 KB.
  • Skip list: a sorted multi-level linked list in which each element is promoted to the next level up with probability 1/21/2; a search moves right, then drops down a level, giving expected O(log⁡n)O(\log n) search, insertion, and deletion without rebalancing.
  • Bloom filter event validator: an early, small program that checks a CSV catalog of event ids. A Bloom filter sized for 4,980,000 items at a 1% false-positive rate flags ids that have probably been seen before, and a running comparison flags ids that are out of order; both lists are printed at the end. It uses the third-party bloom_filter package and reads catalog_incorrect.csv from the current directory. Because the filter can report false positives, an id it flags as a duplicate is only probably one; a second exact check would confirm it.