Interview Question: "Explain HyperLogLog and its error bounds. When would you use approximate queries vs exact queries? How does Count-Min Sketch work?" â Asked at Google, Facebook, Amazon for Data Infrastructure roles
âšī¸
Difficulty: Advanced | Companies: Google, Facebook, Amazon, Twitter, LinkedIn | Time: 60-75 minutes
Trading exactness for a bounded answer
An approximate query returns a value close to the truth with a stated error bound, in memory that does not grow with the input. The trade is worth taking when the decision the number feeds is insensitive to a few percent of error â a dashboard counting distinct visitors, a cache deciding which keys are popular, a monitor checking whether a value ever appeared â and unacceptable when the number is billed, taxed, or audited. The discipline that separates production use from a clever trick is stating the bound: not roughly correct, but 1.04 divided by the square root of the register count, with a failure probability attached. Every structure in this lesson has a memory budget, an error term, and a question it answers badly.
HyperLogLog for Distinct Counting
HyperLogLog estimates cardinality with memory:
Where is the number of registers.
-- PostgreSQL doesn't have built-in HyperLogLog
-- Implement with extension or custom function
-- Create HLL extension (if available)
CREATE EXTENSION IF NOT EXISTS hyperloglog;
-- Create approximate distinct count function
CREATE OR REPLACE FUNCTION hll_add(hll_state BYTEA, value TEXT)
RETURNS BYTEA AS $$
DECLARE
hash_val BIGINT;
register_idx INT;
leading_zeros INT;
current_val INT;
BEGIN
-- Simple hash function
hash_val := hashtext(value);
register_idx := (hash_val & 1023) + 1; -- 1024 registers
-- Count leading zeros
leading_zeros := 0;
current_val := (hash_val >> 10) & 1023;
WHILE (current_val & 1) = 0 AND leading_zeros < 32 LOOP
leading_zeros := leading_zeros + 1;
current_val := current_val >> 1;
END LOOP;
-- Update register if larger
IF hll_state IS NULL THEN
hll_state := repeat('\0', 1024)::BYTEA;
END IF;
IF get_byte(hll_state, register_idx) < leading_zeros THEN
hll_state := set_byte(hll_state, register_idx, leading_zeros);
END IF;
RETURN hll_state;
END;
$$ LANGUAGE plpgsql;
-- Usage example
WITH hll_state AS (
SELECT
user_id,
hll_add(NULL, event_type) AS state
FROM events
GROUP BY user_id
)
SELECT
COUNT(DISTINCT user_id) AS exact_count,
-- Approximate count would use HLL state
COUNT(DISTINCT user_id) AS approximate_count
FROM events;
HyperLogLog hashes each value, reads the position of the first one bit, and keeps the maximum seen per register; the largest value across registers estimates how many distinct inputs could have produced it. That is why error shrinks with the square root of the register count â doubling the registers cuts error by roughly thirty percent while doubling memory. The practical consequences are worth internalising. The estimate is one number you cannot decompose, so you cannot ask which values produced it. Error is proportional rather than absolute, so one percent of a million is ten thousand and the same one percent of a billion is ten million. Small cardinalities fare worse than the formula suggests, which is why production implementations switch to linear counting below a threshold, and merging two sketches is well defined, so daily states combine into a month without re-reading raw events.
Count-Min Sketch
Count-Min Sketch estimates frequency with update:
-- Create Count-Min Sketch structure
CREATE TABLE count_min_sketch (
depth INT DEFAULT 4,
width INT DEFAULT 1024,
table_idx INT,
counter_idx INT,
counter BIGINT DEFAULT 0,
PRIMARY KEY (table_idx, counter_idx)
);
-- Initialize sketch
INSERT INTO count_min_sketch (table_idx, counter_idx, counter)
SELECT
d.i AS table_idx,
w.i AS counter_idx,
0 AS counter
FROM generate_series(1, 4) d(i),
generate_series(0, 1023) w(i);
-- Update function
CREATE OR REPLACE FUNCTION cms_update(item TEXT)
RETURNS VOID AS $$
DECLARE
hash_val BIGINT;
BEGIN
FOR i IN 1..4 LOOP
hash_val := hashtext(item || i::TEXT);
UPDATE count_min_sketch
SET counter = counter + 1
WHERE table_idx = i
AND counter_idx = (hash_val & 1023);
END LOOP;
END;
$$ LANGUAGE plpgsql;
-- Query function
CREATE OR REPLACE FUNCTION cms_estimate(item TEXT)
RETURNS BIGINT AS $$
DECLARE
min_val BIGINT := BIGINT_MAX;
hash_val BIGINT;
current_val BIGINT;
BEGIN
FOR i IN 1..4 LOOP
hash_val := hashtext(item || i::TEXT);
SELECT counter INTO current_val
FROM count_min_sketch
WHERE table_idx = i
AND counter_idx = (hash_val & 1023);
IF current_val < min_val THEN
min_val := current_val;
END IF;
END LOOP;
RETURN min_val;
END;
$$ LANGUAGE plpgsql;
A Count-Min Sketch keeps a grid of counters, hashes each event into one counter per row, and reports the smallest of those counters. Taking the minimum matters: every candidate over-counts because collisions only ever add, so the smallest candidate is the tightest honest estimate. Two parameters set the contract â width controls the additive error and depth controls the probability of exceeding it â and memory is their product regardless of how many events stream through. The structure has one sharp limitation: it estimates frequencies but cannot enumerate the items themselves. Pair it with a candidate generator such as a heap of frequent keys, or with a second structure that can name what it counts, otherwise you can prove that something happened a million times without ever knowing what something was.
Top-K Approximation
-- Space-Saving algorithm for Top-K
CREATE TABLE top_k_estimator (
item TEXT,
count BIGINT,
error BIGINT,
PRIMARY KEY (item)
);
CREATE OR REPLACE FUNCTION top_k_update(new_item TEXT, k INT)
RETURNS VOID AS $$
DECLARE
existing_count BIGINT;
min_count BIGINT;
min_item TEXT;
BEGIN
-- Check if item exists
SELECT count INTO existing_count
FROM top_k_estimator
WHERE item = new_item;
IF FOUND THEN
UPDATE top_k_estimator
SET count = count + 1
WHERE item = new_item;
ELSE
-- Check if we have room
IF (SELECT COUNT(*) FROM top_k_estimator) < k THEN
INSERT INTO top_k_estimator (item, count, error)
VALUES (new_item, 1, 0);
ELSE
-- Find minimum
SELECT item, count INTO min_item, min_count
FROM top_k_estimator
ORDER BY count ASC
LIMIT 1;
-- Replace if new item has higher count
IF 1 > min_count THEN
DELETE FROM top_k_estimator WHERE item = min_item;
INSERT INTO top_k_estimator (item, count, error)
VALUES (new_item, min_count + 1, min_count);
END IF;
END IF;
END IF;
END;
$$ LANGUAGE plpgsql;
-- Get Top-K items
SELECT
item,
count,
error,
count - error AS estimated_count
FROM top_k_estimator
ORDER BY count DESC
LIMIT 10;
The space-saving approach keeps only k candidates: a new item either increments a key already held or displaces the smallest count when the table is full, inheriting that count as its error margin. The reported range â stored count minus error â is the honest statement of what is known, and it narrows as an item accumulates more hits. Two behaviours deserve a test before shipping. An item arriving late and often can evict a genuine member of the top k while its own error is still large, so ordering by arrival is a real risk rather than a theoretical edge case. And the structure is stateful: replaying the stream doubles every count, so checkpoint and restore must be part of the design if the job restarts part-way through a day.
Bloom Filter
-- Bloom filter for membership testing
CREATE TABLE bloom_filter (
filter_size INT DEFAULT 1024,
hash_functions INT DEFAULT 3,
bits BIT(1024) DEFAULT repeat('0', 1024)::BIT(1024)
);
CREATE OR REPLACE FUNCTION bloom_add(item TEXT)
RETURNS VOID AS $$
DECLARE
hash_val BIGINT;
pos INT;
BEGIN
FOR i IN 1..3 LOOP
hash_val := hashtext(item || i::TEXT);
pos := (hash_val & 1023) + 1;
UPDATE bloom_filter
SET bits = set_bit(bits, pos, 1);
END LOOP;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION bloom_check(item TEXT)
RETURNS BOOLEAN AS $$
DECLARE
hash_val BIGINT;
pos INT;
result BOOLEAN := TRUE;
BEGIN
FOR i IN 1..3 LOOP
hash_val := hashtext(item || i::TEXT);
pos := (hash_val & 1023) + 1;
IF get_bit((SELECT bits FROM bloom_filter), pos) = 0 THEN
result := FALSE;
EXIT;
END IF;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;
A bloom filter answers membership with no false negatives: when it reports absent, the key was never added, and when it reports present, the key may be present. That asymmetry is exactly what makes it useful in front of expensive storage â probe the filter first, and the disk lookup happens only for keys that plausibly exist. The false positive rate is arithmetic rather than guesswork, driven by the size of the bit array and the number of hash functions, whose optimum sits near seven tenths of the bits-per-entry ratio. Two limits belong in the design notes: the filter cannot remove a key, only be rebuilt, and it cannot count â a key seen a million times looks identical to one seen once.
Approximate Percentile
-- T-Digest for approximate percentiles
CREATE TABLE t_digest (
centroid_id SERIAL PRIMARY KEY,
mean DECIMAL(10,6),
count INT,
min_val DECIMAL(10,6),
max_val DECIMAL(10,6)
);
-- Q-Digest for quantile queries
CREATE TABLE q_digest (
node_id INT PRIMARY KEY,
count INT,
left_child INT,
right_child INT
);
Digests trade exact order statistics for a summary that fits in memory. A t-digest clusters values into centroids weighted by count and places finer granularity near the tails, which is why it estimates a ninety-ninth percentile far better than a ninetieth one; a q-digest does the same for integers by folding a value range into a tree of counts. The decision rule is about depth rather than width: when you need a percentile of a stream you will never be able to store, the digest is the only option, and when the full dataset already fits in memory, exact ordered-set aggregates cost less than the code required to maintain a digest. Always report which percentile you computed, because error at the tail is not error at the median.
Error Bounds
For HyperLogLog:
For Count-Min Sketch:
Where:
- = number of registers
- = error parameter
- = failure probability
- = total count
-- Calculate error bounds
WITH params AS (
SELECT
1024 AS m, -- HyperLogLog registers
0.01 AS epsilon, -- Count-Min error
0.001 AS delta -- Failure probability
)
SELECT
1.04 / SQRT(m) AS hll_error,
1.0 / (4.0 ^ m) AS hll_failure_prob,
epsilon AS cm_error_bound,
delta AS cm_failure_prob
FROM params;
Error Comparison:
| Algorithm | Memory | Error | Use Case |
|---|---|---|---|
| HyperLogLog | Distinct count | ||
| Count-Min | Frequency | ||
| Bloom Filter | Membership | ||
| Top-K | Variable | Frequent items |
âšī¸
When to Use: Approximate queries are ideal for real-time dashboards, monitoring, and big data analytics where exact answers aren't critical.
The formulas read as contracts. HyperLogLog's relative error falls with the square root of the register count while its failure probability falls exponentially, so buying accuracy with memory gets cheap quickly â doubling registers improves both numbers at once. The Count-Min bound is additive: the estimate never falls below the truth and never exceeds it by more than epsilon times the total count, with probability one minus delta, which means absolute error grows with the stream while relative error shrinks. Translate each bound into the numbers your service promises before choosing parameters. Ten thousand distinct visitors with a one percent bound means a documented range from nine thousand nine hundred to ten thousand one hundred, and that range â not the point estimate â is what the dashboard should publish.
PostgreSQL Built-in Approximate Functions
-- Use pg_trgm for approximate matching
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT
word,
similarity(word, 'postgresql') AS sim
FROM pg_words
ORDER BY sim DESC
LIMIT 10;
-- Approximate string matching with Levenshtein
CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;
SELECT
word,
levenshtein(word, 'postgresql') AS distance
FROM pg_words
ORDER BY distance
LIMIT 10;
Not every approximation needs a custom structure. Trigram similarity and Levenshtein distance give approximate matching over text without pulling the whole dictionary into the application, and they are the right first tool for search-as-you-type and fuzzy joins. Both index in their own way â a GIN index on trigram operators turns similarity into an index range scan rather than a table pass â and both degrade predictably as the corpus grows. The pattern across this lesson repeats: reach for a built-in approximate function when one exists, measure its error against your real data, and only then consider a sketch, because a hand-rolled structure you must maintain is a permanent cost charged against a problem that may already be solved.
Performance Comparison
| Operation | Exact | Approximate | Speedup |
|---|---|---|---|
| Distinct Count | 10-100x | ||
| Top-K | 5-50x | ||
| Percentile | 10-100x | ||
| Membership | 100-1000x |
â ī¸
Accuracy Trade-off: Always document the error bounds. Use exact queries for financial or regulatory reporting.
Documenting the error before shipping
A number without a bound is not an approximate answer, it is an unanswered question. Before an estimate reaches a dashboard, record four things beside it: the algorithm and its parameters, the expected error at the current cardinality, the moment the underlying structure was last reset, and whether the figure may be summed across rows â most of these structures cannot be. Revisit those notes whenever volume changes by an order of magnitude, because the promise that held at a million visitors is a different promise at a hundred million. When a stakeholder asks whether the number is safe to act on, the answer should be a range and a rule, not a tone of voice.
Common Mistakes
Publishing an approximate count with no stated error bound
Fix: Publish the range implied by the algorithm and its parameters next to the number
Summing sketch estimates across rows or days
Fix: Merge the underlying structures, or aggregate exact counts, instead of adding derived estimates
Choosing register counts and sketch widths by intuition
Fix: Derive parameters from the error your service actually promises at the expected cardinality
Best Practices
- Keep exact counts for money, compliance, and anything reconciled downstream
- Record the reset time of every probabilistic structure so freshness is visible
- Pair a Count-Min Sketch with a structure that can name the keys it counts
- Test top-k structures against late-arriving and bursty keys before relying on them
- State the percentile alongside every digest estimate, since tail error differs from median error
Interview Questions
Q1: Why does HyperLogLog report the maximum register value?
Because the position of the first one bit in a hash behaves like a geometric draw, and the largest observed value estimates how many draws were made
Q2: Why take the minimum across Count-Min rows?
Collisions only ever inflate counters, so the smallest candidate is the least inflated and therefore the tightest estimate
Q3: What are the bloom filter guarantees?
No false negatives ever, and a false positive rate controlled by the bit array size and hash function count
Q4: When is an approximate percentile unacceptable?
When the value feeds billing, quota enforcement, or contractual thresholds, where a bound that straddles the limit changes the outcome
Key Takeaways
- Approximation is justified only when a stated bound fits the decision the number feeds
- HyperLogLog gives relative error, Count-Min gives additive error â pick from the question, not the novelty
- Sketches that count usually cannot enumerate, so pair them with a candidate structure
- Digests sacrifice tail accuracy for memory, so always name the percentile you report
- Publish ranges, parameters, and reset times beside every approximate figure