Probabilistic data structures and sketches
Answer questions about huge data in a few kilobytes: Bloom filters for membership, HyperLogLog for distinct counts, Count-Min for frequencies, quantile sketches for percentiles, reservoir sampling and MinHash, with error bounds.
ConceptCore30 min readUpdated
- 11 code samples
- 8 interviewer follow-ups
- 4 self-checks
On this page13 sectionsHLDLLDSenior depth
- Match a question (membership, distinct count, frequency, quantile, similarity, sample) to the sketch that answers it, and say which way its error points.
- Size a Bloom filter, a HyperLogLog and a Count-Min sketch from the error you can accept, using the standard formulas.
- Explain why percentiles cannot be averaged across servers and how a mergeable quantile sketch fixes it.
- Name the failure modes (an overfull filter, mixed hash functions, rare items in a Count-Min sketch, adversarial input) and when to use exact structures instead.
10 code samples (372 lines), collapsed so the explanation stays in focus.
Some questions are too big to answer exactly. How many different people visited the site today, out of eight billion events? Have we crawled this URL before, among a hundred billion? Which search terms are most frequent right now? What is the 99th-percentile latency across ten thousand servers? An exact answer needs memory in proportion to the data, or a trip to a database for every event. Probabilistic data structures, or sketches, answer approximately, in a small and fixed amount of memory, with an error you can compute in advance and choose.
| Question | Sketch | Memory in the examples below | The error |
|---|---|---|---|
| Have I seen this item? | Bloom filter | 117 KB for 100,000 items | Only false positives (1% chosen), never false negatives |
| How many distinct items? | HyperLogLog | 4 KB, for any number | About 1.6% typical error |
| How often did this item occur? | Count-Min sketch | 106 KB | Never an under-count; over-count at most ε × total |
| Which items are most frequent? | Count-Min with a small candidate list | 106 KB | Reliable for frequent items, noisy for rare ones |
| What is the median or p99? | Quantile sketch | About 500 buckets | A relative error you choose (1% here) |
| How similar are two sets? | MinHash | 128 numbers per set | About 4% at medium similarity |
| A fair sample of a stream | Reservoir sampling | k items | Exactly uniform |
Four things are true of all of them.
- They depend on a good hash function. The guarantees assume hashes behave like random numbers. Use a well-mixed 64-bit hash, and make it stable: the same input must hash the same way in every process and every version, or sketches built on different machines will not merge. (.NET's
string.GetHashCodeis randomised per process, so it is wrong here.) - Their error bounds are statements about probability, over the randomness of the hash, not promises about a particular item.
- Most merge. Two sketches of the same kind and size combine into the sketch of the union of the data, by taking the maximum of registers or adding counters.
- The basic forms do not delete. If you need to remove items, you need a variant, or a rebuild.
All the samples share one hash function: FNV-1a over the bytes, then a finalizer that scrambles the bits (splitmix64).
A Bloom filter answers "have I seen this?" with one-sided error: "definitely not" is always right and "probably yes" is sometimes wrong. It is an array of m bits and k hash functions. To add an item, set the k bits its hashes point to. To check an item, look at the same k bits: if any is zero the item was never added; if all are one it probably was, because other items might have set those bits.
If n items have been added, the false-positive rate is about (1 − e^(−kn/m))^k. For a target rate p the best sizes are:
bits: m = -n ln(p) / (ln 2)^2 (1.44 log2(1/p) bits per item)
hashes: k = (m / n) ln 2
p = 1% 9.6 bits per item, k = 7
p = 0.1% 14.4 bits per item, k = 10
p = 0.01% 19.2 bits per item, k = 13C# · One 64-bit hash function for everything below. Mixing the bits well matters: a sketch is…
using System;
using System.Text;
// One 64-bit hash function for everything below. Mixing the bits well matters: a sketch is only as good as its hash.
public static class Hash
{
public static ulong Mix(ulong x) // splitmix64's finalizer
{
x += 0x9E3779B97F4A7C15UL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9UL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBUL;
return x ^ (x >> 31);
}
public static ulong Of(string text) // FNV-1a over the UTF-8 bytes, then mixed
{
ulong h = 14695981039346656037UL;
foreach (byte b in Encoding.UTF8.GetBytes(text)) h = (h ^ b) * 1099511628211UL;
return Mix(h);
}
}
// A set that can say "definitely not present" or "probably present", in a few bits per item.
public sealed class BloomFilter
{
private readonly ulong[] bits;
private readonly int size, hashes;
public int Items { get; private set; }
public BloomFilter(int expectedItems, double falsePositiveRate)
{
size = (int)Math.Ceiling(-expectedItems * Math.Log(falsePositiveRate) / (Math.Log(2) * Math.Log(2))); // m = -n ln p / (ln 2)^2
hashes = Math.Max(1, (int)Math.Round((double)size / expectedItems * Math.Log(2))); // k = (m / n) ln 2
bits = new ulong[(size + 63) / 64];
}
public int Bits => size;
public int Hashes => hashes;
private ulong Position(ulong h1, ulong h2, int i) => (h1 + (ulong)i * h2) % (ulong)size; // k positions from two hashes
public void Add(string item)
{
ulong h1 = Hash.Of(item), h2 = Hash.Mix(h1) | 1;
for (int i = 0; i < hashes; i++) { ulong p = Position(h1, h2, i); bits[p >> 6] |= 1UL << (int)(p & 63); }
Items++;
}
public bool MightContain(string item)
{
ulong h1 = Hash.Of(item), h2 = Hash.Mix(h1) | 1;
for (int i = 0; i < hashes; i++) { ulong p = Position(h1, h2, i); if ((bits[p >> 6] & (1UL << (int)(p & 63))) == 0) return false; }
return true;
}
// What the false-positive rate is after `Items` insertions: (1 - e^(-k n / m))^k.
public double ExpectedFalsePositiveRate => Math.Pow(1 - Math.Exp(-(double)hashes * Items / size), hashes);
}C#
using System;
using System.Diagnostics;
using System.Linq;
var filter = new BloomFilter(100_000, 0.01);
for (int i = 0; i < 100_000; i++) filter.Add("user-" + i);
Debug.Assert(Enumerable.Range(0, 100_000).All(i => filter.MightContain("user-" + i))); // never a false negative
int falsePositives = Enumerable.Range(0, 200_000).Count(i => filter.MightContain("never-seen-" + i));
double measured = falsePositives / 200_000.0;
Debug.Assert(measured > 0.007 && measured < 0.013); // about 1%, as designed
Debug.Assert(filter.Bits / 8 < 125_000 && filter.Hashes == 7); // 117 KB and 7 hash functions
// A filter built for 100,000 items and given 300,000 degrades fast: it is full of ones.
var overfull = new BloomFilter(100_000, 0.01);
for (int i = 0; i < 300_000; i++) overfull.Add("user-" + i);
double overfullRate = Enumerable.Range(0, 100_000).Count(i => overfull.MightContain("never-seen-" + i)) / 100_000.0;
Debug.Assert(overfullRate > 0.35);For 100,000 items at a 1% target, the filter used 119,813 bytes (about 117 KB) and 7 hash functions. It had no false negatives, and with 200,000 items that were never added it said "maybe" for 1.01% of them, against 1.00% predicted. A HashSet<string> of the same items would take several megabytes. The last test shows the main hazard: when the same filter was given 300,000 items instead of 100,000, its false-positive rate rose to 43%. A Bloom filter must be sized for the number of items it will hold. If the count is unknown, use a scalable Bloom filter (a chain of filters) or rebuild it.
Where it is used. In an LSM tree each file has a Bloom filter, so a read skips files that cannot contain the key (see storage engines and indexes). In front of a cache or database, a filter of all existing keys stops requests for keys that do not exist ("cache penetration") from reaching the database: a false positive costs one wasted lookup. Crawlers use one to avoid fetching a URL twice, and distributed joins use one to avoid shipping rows that cannot match.
Variants and traps. A counting Bloom filter uses small counters instead of bits so that it can delete. A cuckoo filter also supports deletion and uses less space at low error rates. You cannot list the contents of a Bloom filter, and you cannot delete from a plain one: clearing the bits of one item may erase another. If attackers can choose inputs, they can pick items that all hash to the same positions to raise the false-positive rate, so use a secret seed for the hash. Design so that a false positive is cheap and a human or a database confirms the rest.
HyperLogLog (HLL) counts distinct items in a few kilobytes. The intuition: hash each item to random bits. In a set of n different items, the longest run of leading zeros among the hashes is about log₂ n, because you need roughly 2^z items before one of them starts with z zeros. One such maximum is a noisy estimate, so HLL splits the items into m groups by the first bits of the hash, keeps a maximum per group (a register, one small byte) and combines them with a harmonic mean. The typical error, the standard error, is 1.04 / √m. With 4,096 registers (4 KB) that is 1.6%. Redis uses 16,384 registers (12 KB) for 0.81%.
Adding an item that is already counted changes nothing, because the same hash always gives the same register and rank, so duplicates are free. Two sketches merge by taking the larger value in each register, which gives the sketch of the union. That is the property that makes HLL so useful: every server, or every hour, keeps its own sketch, and a dashboard merges them to count distinct users across servers, days or countries. A metrics system uses the same idea to count the distinct series of each metric and catch a runaway label early (see the metrics monitoring case study).
C# · Counts distinct items in a fixed 4 KB, whatever the number of items, with a typical…
using System;
using System.Numerics;
// Counts distinct items in a fixed 4 KB, whatever the number of items, with a typical error near 1.6%.
public sealed class HyperLogLog
{
private readonly int p, m;
private readonly byte[] registers;
public HyperLogLog(int precision = 12) { p = precision; m = 1 << p; registers = new byte[m]; }
public int Bytes => m;
public double StandardError => 1.04 / Math.Sqrt(m);
public void Add(ulong hash) // the caller hashes the item; duplicates change nothing
{
int register = (int)(hash >> (64 - p)); // the first p bits choose a register...
int leadingZeros = BitOperations.LeadingZeroCount(hash << p); // ...the rest are scanned for a run of leading zeros
byte rank = (byte)(Math.Min(leadingZeros, 64 - p) + 1);
if (rank > registers[register]) registers[register] = rank;
}
public double Estimate()
{
double alpha = 0.7213 / (1 + 1.079 / m);
double sum = 0;
int empty = 0;
foreach (byte r in registers) { sum += Math.Pow(2, -r); if (r == 0) empty++; }
double estimate = alpha * m * m / sum; // a harmonic mean of 2^rank, which is rare-event evidence
if (estimate <= 2.5 * m && empty > 0) estimate = m * Math.Log((double)m / empty); // few items: count the empty registers instead
return estimate;
}
public void Merge(HyperLogLog other) // the union of two sets: each register keeps the larger rank
{
for (int i = 0; i < m; i++) registers[i] = Math.Max(registers[i], other.registers[i]);
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
foreach (int distinct in new[] { 100, 10_000, 1_000_000, 5_000_000 })
{
var hll = new HyperLogLog();
for (int i = 0; i < distinct; i++) { ulong h = Hash.Mix((ulong)i); hll.Add(h); hll.Add(h); hll.Add(h); } // every item three times
double error = Math.Abs(hll.Estimate() - distinct) / distinct;
Debug.Assert(error < 4 * hll.StandardError);
}
// Error over many independent runs: about 0.8 of the standard error on average.
double totalError = 0; double worst = 0;
for (int run = 0; run < 50; run++)
{
var hll = new HyperLogLog();
for (int i = 0; i < 200_000; i++) hll.Add(Hash.Mix((ulong)(run * 1_000_000_000L + i)));
double e = Math.Abs(hll.Estimate() - 200_000) / 200_000;
totalError += e; worst = Math.Max(worst, e);
}
Debug.Assert(totalError / 50 < 0.02 && worst < 0.065);
// Sketches merge: the servers each count their own visitors, and the union is the register-wise maximum.
var east = new HyperLogLog(); var west = new HyperLogLog();
for (int i = 0; i < 300_000; i++) east.Add(Hash.Mix((ulong)i)); // visitors 0 .. 299,999
for (int i = 200_000; i < 500_000; i++) west.Add(Hash.Mix((ulong)i)); // visitors 200,000 .. 499,999, 100,000 in common
double beforeMerge = east.Estimate();
east.Merge(west);
Debug.Assert(Math.Abs(east.Estimate() - 500_000) / 500_000 < 4 * east.StandardError);The estimates for 100, 10,000, 1,000,000 and 5,000,000 distinct items (each added three times) were off by 2.9%, 1.0%, 2.1% and 2.6%. Over 50 independent runs on 200,000 items the mean error was 1.17% and the worst 3.47%, in line with a 1.6% standard error, and the two merged sketches with 100,000 visitors in common gave the union to within the expected error. The cost is 4 KB, where an exact set of five million 64-bit ids takes over 100 MB. Several databases expose it as an approximate distinct count (BigQuery's APPROX_COUNT_DISTINCT, Trino's approx_distinct, Redis's PFCOUNT). Its weakness is set operations other than union: an intersection computed by inclusion and exclusion can have a huge relative error.
A Count-Min sketch estimates how often each item occurred. It is a table with d rows and w columns of counters and one hash function per row. To add an item, increment one counter in each row. To estimate an item, take the minimum of its d counters. Other items collide into the same counters, so each counter is at least the true count, and the minimum over several rows is the least inflated: the estimate never under-counts. With width w = ⌈e / ε⌉ and depth d = ⌈ln(1 / δ)⌉, the over-count is at most ε × N (N is the total number of events) with probability at least 1 − δ. Width buys accuracy and depth buys confidence. Sketches merge by adding their tables.
The error is absolute, so it is small for items that occur often and may be larger than the count itself for rare ones. That makes it the tool for heavy hitters, the most frequent items: keep a small list of the k best candidates while the stream goes by, and update it with each item's estimate. The search autocomplete lesson uses the Space-Saving algorithm for the same job, which keeps exact counters for a bounded set of candidates; Count-Min is the better choice when you also need the count of an arbitrary item.
C# · Approximate counts for a huge number of different items in a small table. It can only…
using System;
using System.Collections.Generic;
using System.Linq;
// Approximate counts for a huge number of different items in a small table. It can only over-count, never under-count.
public sealed class CountMinSketch
{
private readonly long[,] table;
private readonly int width, depth;
public long Total { get; private set; }
// The error is at most epsilon * Total, with probability at least 1 - delta.
public CountMinSketch(double epsilon, double delta)
{
width = (int)Math.Ceiling(Math.E / epsilon);
depth = (int)Math.Ceiling(Math.Log(1 / delta));
table = new long[depth, width];
}
public int Cells => width * depth;
private int Column(ulong h1, ulong h2, int row) => (int)((h1 + (ulong)row * h2) % (ulong)width);
public void Add(string item, long count = 1)
{
ulong h1 = Hash.Of(item), h2 = Hash.Mix(h1) | 1;
for (int row = 0; row < depth; row++) table[row, Column(h1, h2, row)] += count;
Total += count;
}
public long Estimate(string item) // the smallest of the counters this item shares
{
ulong h1 = Hash.Of(item), h2 = Hash.Mix(h1) | 1;
long best = long.MaxValue;
for (int row = 0; row < depth; row++) best = Math.Min(best, table[row, Column(h1, h2, row)]);
return best;
}
}
// The k items with the highest estimates so far, kept while the stream goes by.
public sealed class HeavyHitters
{
private readonly CountMinSketch sketch;
private readonly int k;
private readonly Dictionary<string, long> candidates = new Dictionary<string, long>();
public HeavyHitters(CountMinSketch sketch, int k) { this.sketch = sketch; this.k = k; }
public void Add(string item)
{
sketch.Add(item);
long estimate = sketch.Estimate(item);
if (candidates.ContainsKey(item) || candidates.Count < k) { candidates[item] = estimate; return; }
var weakest = candidates.OrderBy(c => c.Value).First();
if (estimate > weakest.Value) { candidates.Remove(weakest.Key); candidates[item] = estimate; }
}
public List<string> Top() => candidates.OrderByDescending(c => c.Value).Select(c => c.Key).ToList();
}C# · A million events over 100,000 different items with a Zipf distribution: a few items are…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// A million events over 100,000 different items with a Zipf distribution: a few items are very popular.
var zipfRandom = new Random(4);
const int Items = 100_000;
var cumulative = new double[Items];
double running = 0;
for (int rank = 1; rank <= Items; rank++) { running += 1.0 / Math.Pow(rank, 1.1); cumulative[rank - 1] = running; }
string Draw()
{
int index = Array.BinarySearch(cumulative, zipfRandom.NextDouble() * running);
return "item-" + ((index < 0 ? ~index : index) + 1);
}
var sketch = new CountMinSketch(epsilon: 0.001, delta: 0.01); // 2,719 columns and 5 rows
var heavy = new HeavyHitters(sketch, 10);
var truth = new Dictionary<string, long>();
for (int i = 0; i < 1_000_000; i++)
{
string item = Draw();
heavy.Add(item);
truth[item] = truth.GetValueOrDefault(item) + 1;
}
Debug.Assert(truth.All(t => sketch.Estimate(t.Key) >= t.Value)); // never an under-count
long bound = (long)(0.001 * sketch.Total); // epsilon * N = 1,000
double withinBound = truth.Count(t => sketch.Estimate(t.Key) - t.Value <= bound) / (double)truth.Count;
Debug.Assert(withinBound > 0.99); // true for at least 99% of items, as promised
var exactTop = truth.OrderByDescending(t => t.Value).Take(10).Select(t => t.Key).ToList();
Debug.Assert(heavy.Top().SequenceEqual(exactTop)); // the same ten most popular items, in the same orderThe stream had a million events over 64,867 distinct items, drawn from a Zipf distribution, so a few items are very popular. With ε = 0.001 and δ = 0.01 the sketch is 2,719 columns by 5 rows of 8-byte counters, 108,760 bytes. Every estimate was at least the true count, every item was within the bound of ε × N = 1,000, and the heavy-hitter list was identical to the exact top ten, in the same order. The sketch size does not depend on how many different items there are, which is the point.
Percentiles cannot be averaged. If three servers report their 99th-percentile latency, the average of those three numbers is not the 99th percentile of all requests, because the servers carry different amounts of traffic and have different distributions (the latency lesson makes the same point). To get the true percentile you need the data, or something that summarises the whole distribution and can be merged.
A fixed-bucket histogram does that, but its accuracy depends on where you put the bucket boundaries. A quantile sketch chooses buckets automatically to keep the error bounded. DDSketch uses logarithmic buckets: bucket i holds the values in (γ^(i−1), γ^i], with γ = (1 + α) / (1 − α), and any value in the bucket is reported as 2γ^i / (γ + 1), which is within α of every value in the bucket. That is a guaranteed relative error, and memory depends on the range of values (how many orders of magnitude), not on how many there are. Merging is adding bucket counts. t-digest and KLL are other popular sketches with different error guarantees (t-digest is especially accurate in the tails). HDR histograms do much the same with fixed precision over a configured range.
C# · Quantiles (the median, p99) of a huge stream in a few kilobytes, with a guaranteed…
using System;
using System.Collections.Generic;
using System.Linq;
// Quantiles (the median, p99) of a huge stream in a few kilobytes, with a guaranteed relative error, and mergeable.
// Values go into logarithmic buckets: bucket i holds values in (gamma^(i-1), gamma^i], and any value in it is reported as
// 2 * gamma^i / (gamma + 1), which is within `relativeError` of every value in the bucket.
public sealed class QuantileSketch
{
private readonly double gamma, logGamma;
private readonly SortedDictionary<int, long> buckets = new SortedDictionary<int, long>();
public long Count { get; private set; }
public QuantileSketch(double relativeError)
{
gamma = (1 + relativeError) / (1 - relativeError);
logGamma = Math.Log(gamma);
}
public int BucketCount => buckets.Count;
public void Add(double value) // positive values, such as latencies
{
int bucket = (int)Math.Ceiling(Math.Log(value) / logGamma);
buckets[bucket] = buckets.GetValueOrDefault(bucket) + 1;
Count++;
}
public double Quantile(double q)
{
long rank = (long)Math.Floor(q * (Count - 1)); // the position this quantile has in the sorted data
long seen = 0;
foreach (var bucket in buckets)
{
seen += bucket.Value;
if (seen > rank) return 2 * Math.Pow(gamma, bucket.Key) / (gamma + 1);
}
throw new InvalidOperationException("empty sketch");
}
public void Merge(QuantileSketch other) // adding the bucket counts is all it takes
{
foreach (var bucket in other.buckets) buckets[bucket.Key] = buckets.GetValueOrDefault(bucket.Key) + bucket.Value;
Count += other.Count;
}
}C# · Three servers handle 70%, 25% and 5% of the traffic, and the slow server is the one with…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// Three servers handle 70%, 25% and 5% of the traffic, and the slow server is the one with the least.
var latencyRandom = new Random(17);
double LogNormal(double mu) { double u1 = 1 - latencyRandom.NextDouble(), u2 = latencyRandom.NextDouble(); return Math.Exp(mu + Math.Sqrt(-2 * Math.Log(u1)) * Math.Cos(2 * Math.PI * u2)); }
double[] mus = { 3.0, 3.5, 5.0 }; // median latency of 20 ms, 33 ms and 148 ms
var perServer = Enumerable.Range(0, 3).Select(_ => new List<double>()).ToArray();
for (int i = 0; i < 1_000_000; i++)
{
double roll = latencyRandom.NextDouble();
int server = roll < 0.70 ? 0 : roll < 0.95 ? 1 : 2;
perServer[server].Add(LogNormal(mus[server]));
}
double Exact(IEnumerable<double> values, double q) { var sorted = values.OrderBy(v => v).ToArray(); return sorted[(long)Math.Floor(q * (sorted.Length - 1))]; }
var everything = perServer.SelectMany(s => s).ToList();
var sketches = perServer.Select(values => { var s = new QuantileSketch(0.01); foreach (double v in values) s.Add(v); return s; }).ToList();
var merged = new QuantileSketch(0.01);
foreach (var s in sketches) merged.Merge(s);
foreach (double q in new[] { 0.5, 0.9, 0.99, 0.999 })
{
double exact = Exact(everything, q);
Debug.Assert(Math.Abs(merged.Quantile(q) - exact) / exact <= 0.0101); // within 1% of the true value
}
double averageOfP99s = perServer.Select(v => Exact(v, 0.99)).Average();
double trueP99 = Exact(everything, 0.99);
Debug.Assert(Math.Abs(averageOfP99s - trueP99) / trueP99 > 0.25); // averaging percentiles is badly wrong
Debug.Assert(merged.BucketCount < 1_000); // a few kilobytes, whatever the number of valuesThe test splits a million latencies over three servers carrying 70%, 25% and 5% of the traffic, with the least busy being the slowest (median latencies of 20, 33 and 148 ms). The true 99th percentile of everything was 413 ms. The merged sketch said 416 ms, within the 1% guarantee, for every quantile tested (p50, p90, p99, p99.9), using 499 buckets. The average of the three per-server p99s was 699 ms, 69% too high. This is why a metrics system should store histograms or sketches, and not pre-computed percentiles, if it will ever aggregate across hosts or time (see the latency lesson, and the observability lesson for what a metrics pipeline stores).
Reservoir sampling keeps a uniform random sample of k items from a stream whose length you do not know, in memory for k items. Keep the first k items. For each later item, number i (counting from one), keep it with probability k / i, replacing a random item already in the sample. By induction every item seen so far has the same probability, k / i, of being in the sample. Use it to keep a fair sample of log lines or requests for debugging, or to estimate averages from a stream. If you want the same users sampled on every service, sample by a hash of the user id instead (keep the user if the hash is below the rate), so the decision is consistent.
C# · Reservoir sampling: keep a uniform random sample of k items from a stream of unknown…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// Reservoir sampling: keep a uniform random sample of k items from a stream of unknown length, in O(k) memory.
int[] Reservoir(IEnumerable<int> stream, int k, Random random)
{
var sample = new int[k];
int seen = 0;
foreach (int item in stream)
{
if (seen < k) sample[seen] = item; // the first k items fill the reservoir
else
{
int slot = random.Next(seen + 1); // item number seen+1 is kept with probability k / (seen+1)
if (slot < k) sample[slot] = item;
}
seen++;
}
return sample;
}
var sampler = new Random(31);
var picked = new int[100];
for (int trial = 0; trial < 20_000; trial++)
foreach (int item in Reservoir(Enumerable.Range(0, 100), 10, sampler)) picked[item]++;
// Each of the 100 items should be chosen in 10% of the trials, whether it came first or last.
Debug.Assert(picked.All(count => Math.Abs(count - 2_000) < 200));Across 20,000 runs on a stream of 100 items with a reservoir of 10, every item was selected within 10% of the expected 2,000 times, whether it came first or last.
MinHash estimates how similar two sets are, measured by the Jaccard similarity: the size of the intersection divided by the size of the union. For a random hash function, the probability that two sets have the same minimum hash value is exactly their Jaccard similarity. Keep the minimum under each of 128 different hash functions as the signature of a set, and the share of positions where two signatures agree estimates the similarity, with a standard error of √(J(1 − J) / 128), about 4% at J = 0.43. To find near-duplicates among millions of documents without comparing all pairs, split each signature into bands and treat documents that agree on a whole band as candidates (locality-sensitive hashing). Uses include near-duplicate web pages, plagiarism detection and de-duplicating records or text chunks.
C# · MinHash: estimate how similar two sets are (their Jaccard similarity) from a small…
using System;
using System.Collections.Generic;
using System.Linq;
// MinHash: estimate how similar two sets are (their Jaccard similarity) from a small signature of each.
public sealed class MinHasher
{
private readonly ulong[] seeds;
public MinHasher(int signatureSize, int seed)
{
var random = new Random(seed);
seeds = Enumerable.Range(0, signatureSize).Select(_ => (ulong)random.NextInt64()).ToArray();
}
public ulong[] Signature(IEnumerable<string> set)
{
var signature = Enumerable.Repeat(ulong.MaxValue, seeds.Length).ToArray();
foreach (string item in set)
{
ulong h = Hash.Of(item);
for (int i = 0; i < seeds.Length; i++) signature[i] = Math.Min(signature[i], Hash.Mix(h ^ seeds[i])); // one hash function per slot
}
return signature;
}
// The chance that two sets have the same minimum under a random hash is exactly their Jaccard similarity.
public static double Similarity(ulong[] a, ulong[] b) => a.Zip(b, (x, y) => x == y ? 1.0 : 0.0).Average();
}using System;
using System.Diagnostics;
using System.Linq;
var hasher = new MinHasher(128, 3);
var documentA = Enumerable.Range(0, 1_000).Select(i => "shingle-" + i).ToList(); // two documents that share 600 of
var documentB = Enumerable.Range(400, 1_000).Select(i => "shingle-" + i).ToList(); // 1,400 different shingles: 0.43
double jaccard = 600.0 / 1_400.0;
double estimate = MinHasher.Similarity(hasher.Signature(documentA), hasher.Signature(documentB));
Debug.Assert(Math.Abs(estimate - jaccard) < 0.13); // within 3 standard errors for 128 slotsTwo sets of 1,000 shingles sharing 600 of 1,400 distinct ones have a true similarity of 0.429. The estimate from two 128-number signatures was 0.453.
| Structure | The knob | Rule of thumb |
|---|---|---|
| Bloom filter | bits per item, hash count | 9.6 bits for 1%, 14.4 for 0.1%; size for the final item count |
| HyperLogLog | registers m = 2^p | Error 1.04 / √m: p = 12 gives 1.6%, p = 14 gives 0.81% |
| Count-Min | width ε and depth δ | Width ⌈e / ε⌉, depth ⌈ln(1 / δ)⌉; the error is εN, so it needs a heavy tail |
| Quantile sketch | relative error α | Memory grows with log(range) / α, not with the number of values |
| MinHash | signature size | Error about 0.5 / √size |
| Reservoir | sample size k | Standard error of estimates falls as 1 / √k |
Practices that matter in production:
- Test against exact answers on a sample of real data before you trust a sketch.
- Version and fix the hash function and the sketch parameters, and refuse to merge sketches that differ.
- Store sketches, not only totals. A HyperLogLog per hour and per dimension merges into any day, week or country without reading the raw events again.
- Say which way the error points to the people who use the number. "At most 1.6% off" is an acceptable dashboard; a billing system needs exact counts.
| Situation | What happens | Defence |
|---|---|---|
| A Bloom filter holds more than it was sized for | The false-positive rate climbs (43% at three times the size) | Size for the final count; scalable filter or rebuild; alert on the fill ratio |
| Deleting from a plain Bloom filter | False negatives appear | Counting or cuckoo filter, or periodic rebuild |
| Sketches built with different hashes or sizes are merged | Silent garbage | Fix and version the hash and parameters; reject mismatches |
| A process-randomised or weak hash | Different answers on different machines | A stable, well-mixed 64-bit hash with the same seed everywhere |
| Adversarial input | An attacker raises false positives or collisions | A secret seed for the hash |
| Count-Min for rare items | The estimate is dominated by the error | Use it for heavy hitters; compare an estimate with ε × N |
| Averaging percentiles | Wrong by large factors (69% in the test) | Merge sketches or histograms |
| HyperLogLog intersections | The relative error explodes | Use MinHash or theta sketches for set operations |
| Acting on "probably in the set" as if it were certain | A wrong action on a false positive | Make a false positive cost only an extra lookup |
Interviewer follow-upL5How would you count unique visitors per day on a site with billions of events?How to answer
Exactly would need a set of every visitor id, hundreds of megabytes to gigabytes. Use a HyperLogLog: about 4 to 12 KB for a 1% to 2% error, duplicates are free, and every server keeps its own sketch that is merged by taking register maximums. Keep one per day and dimension so any range or segment can be answered by merging. Say the error and that exact counts are for billing, not dashboards.
Interviewer follow-upL5What is a Bloom filter, and what can go wrong?How to answer
A bit array with several hash functions: adding sets bits, checking tests them, so "no" is certain and "yes" is probable. It has false positives and never false negatives. It goes wrong when overfilled (the false-positive rate climbs fast), when you try to delete, when hashes differ between builders, and when attackers choose inputs. Design so that a false positive is only an extra lookup.
Interviewer follow-upL6Design "have we seen this URL" for a crawler with 100 billion URLs.How to answer
A Bloom filter at 1% needs about 9.6 bits per URL, roughly 120 GB, which can be sharded by URL hash across machines. A hit means "probably seen", so the crawler skips the page: that costs about 1% of new pages missed, so use a lower rate or confirm hits against an exact store (a sorted store of 8-byte fingerprints, or an LSM database that has its own filters). Size for the final count, partition by host so politeness and dedupe line up (the web crawler case study builds the rest of that design), and rebuild or add filters as the set grows.
Interviewer follow-upL6How do you compute the top-K trending hashtags over the last hour across many servers?How to answer
Each server keeps a Count-Min sketch (or Space-Saving counters) per short time bucket, say one minute, plus a small list of candidates. A central job merges the sketches of the last sixty buckets by adding them (or merges the candidate lists), then takes the top K by estimated count. Expiring a bucket removes its contribution. The error is absolute (εN), so it is accurate for the trending items by definition. Say that sliding windows come from merging buckets.
Interviewer follow-upL6Why can't you average the p99 of several servers, and what do you do instead?How to answer
A percentile depends on the whole distribution and on how much traffic each server carries, so the mean of percentiles has no meaning: in the test it was 69% too high. Store histograms or mergeable quantile sketches per host and interval, merge them by adding bucket counts, and read the percentile from the merged sketch. That also lets you re-aggregate across time and across label combinations later.
Interviewer follow-upL7Design a metrics system that serves p99 for any time range and label combination.How to answer
Ingest latency measurements into per-series, per-interval sketches (a relative-error quantile sketch or a histogram with exponential buckets), written to a time-series store with rollups: the minute sketches merge into hours and days without rereading the raw data. A query merges the sketches that match the labels and range. Control cardinality, because each label combination is a series, and keep the sketch parameters and hash fixed so merges stay valid. The accuracy is the relative error you chose.
Interviewer follow-upL7Two teams count unique users with HyperLogLog, and their sketches do not combine. Why?How to answer
A merge is only meaningful if the sketches were built with the same hash function, seed and precision. Different hash functions, a different number of registers, or a hash that varies by process or runtime version produce registers that do not line up, so the union is garbage with no error raised. Standardise and version the hash and precision, store them with each sketch, and reject mismatches when merging.
Interviewer follow-upL7When would you not use a sketch?How to answer
When the data is small enough to hold exactly, when the number must be exact (billing, compliance, inventory), when you need to delete items or enumerate them, when an error in one direction is unacceptable and the sketch's direction is the wrong one, and when adversarial inputs could exploit the structure and a secret seed is not possible. A sketch is a good tool at the aggregation layer, where the cost of exactness is large and the decision tolerates a small known error.
Whenever a design needs a count, a lookup or a percentile over very large data, ask whether an exact answer is needed. If not, say which sketch fits the question, give its memory and its error from the formula, and say how it merges across servers: "HyperLogLog per server per hour, merged for the dashboard, 12 KB each, about 1% error".
Sketches answer questions about huge data in small, fixed memory with a known, chosen error. A Bloom filter answers membership with false positives only and must be sized for its final count. HyperLogLog counts distinct items in a few kilobytes with error about 1.04 / √m and merges by register maximum. A Count-Min sketch never under-counts, over-counts by at most ε × N, and finds heavy hitters. Quantile sketches such as DDSketch give percentiles with a relative error and merge by adding buckets, which is why percentiles must be stored as sketches and not averaged. Reservoir sampling gives a uniform sample of a stream, and MinHash estimates the similarity of sets. All depend on a stable, well-mixed hash and on matching parameters when merging, and all are wrong in a direction you should know and design for.
Try answering out loud before you reveal each answer.
QuestionA Bloom filter says an item is not present. Can you trust that? What if it says the item is present?Reveal answer
You can trust "not present": every bit the item sets stays set, so a zero bit proves the item was never added. A "present" answer is only probable, because other items may have set all the same bits. So the filter has false positives and no false negatives, and the design should make a false positive cost only a cheap extra check.
QuestionYou have 2 KB for each of 10,000 counters of distinct users, one per page. Which structure do you use, and how do you get the total for the whole site?Reveal answer
A HyperLogLog per page (a few hundred registers fits in 2 KB, for an error of a few percent). To get the site total, merge the 10,000 sketches by taking the maximum of each register, which counts a user once however many pages they visited. Adding the 10,000 individual counts would count users many times.
QuestionWhat does a Count-Min sketch guarantee about an estimate, and why is it unreliable for rare items?Reveal answer
It never under-counts, and with width ⌈e/ε⌉ and depth ⌈ln(1/δ)⌉ the over-count is at most ε × N with probability at least 1 − δ. The error is a fixed amount proportional to the total, so for an item that occurs a handful of times it can be far larger than the true count, while for items that occur thousands of times it is small. Use it for heavy hitters.
QuestionWhy is the average of per-server p99 latencies wrong, and how would you compute the fleet-wide p99?Reveal answer
A percentile depends on the full distribution and on the traffic each server carries, so averaging percentiles loses both (it was 69% too high in the test). Keep a mergeable histogram or quantile sketch per server and interval, add the bucket counts to get the fleet's distribution, and read the p99 from it, within the sketch's relative error.
- Burton Bloom, Space/Time Trade-offs in Hash Coding with Allowable Errors (opens in a new tab) (Communications of the ACM, 1970), and Bin Fan et al., Cuckoo Filter: Practically Better Than Bloom (opens in a new tab) (CoNEXT 2014).
- Philippe Flajolet et al., HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm (opens in a new tab) (2007), and Stefan Heule et al., HyperLogLog in Practice (opens in a new tab) (EDBT 2013), the engineering behind HyperLogLog++.
- Graham Cormode and S. Muthukrishnan, An improved data stream summary: the count-min sketch and its applications (opens in a new tab) (Journal of Algorithms, 2005).
- Charles Masson, Jee Rim and Homin Lee, DDSketch (opens in a new tab) (VLDB 2019), and Ted Dunning and Otmar Ertl, Computing Extremely Accurate Quantiles Using t-Digests (opens in a new tab).
- Jeffrey Vitter, Random sampling with a reservoir (opens in a new tab) (ACM Transactions on Mathematical Software, 1985).
- Jure Leskovec, Anand Rajaraman and Jeff Ullman, Mining of Massive Datasets (opens in a new tab), the chapter on finding similar items (MinHash and locality-sensitive hashing).
- Martin Kleppmann, Designing Data-Intensive Applications (opens in a new tab), for where these structures sit in real storage and stream systems.