Data Structures for Big Data
Approximate data structures trade a stated error for lower memory or communication.
What, why, when and how
What is it?
These structures summarize large datasets with bounded memory, often trading exact answers for an explicit approximation guarantee.
Why is it needed?
Exact membership, distinct counts or frequency tables can require more memory than a workload can afford.
When should I use it?
Use Bloom filters, cardinality sketches or frequency sketches when their error behavior is acceptable and measured.
When should I choose something else?
Do not use an approximate positive result to authorize access or confirm payment. Exact business decisions require an authoritative check.
How do I use it?
Choose the question first, select the structure and error budget, account for updates and merging, and validate estimates against known samples.
Can you show a concrete example?
A Bloom filter says a document may exist, so the application still queries the authoritative store. In a correctly maintained ordinary filter, a negative can avoid that lookup; the memory saving comes with possible false positives.
Read the diagram
Bloom filter answers membership query; Positive means MAY exist: verify exact store; Maintained filter negative can avoid the lookup
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
Approximate data structures trade a stated error for lower memory or communication. They are useful for cardinality, membership checks, frequency estimates, quantiles, and heavy hitters. They are not interchangeable: a Bloom filter answers likely membership, a HyperLogLog estimates distinct count, and a Count-Min Sketch estimates frequency with collision overcount.
Make approximation visible in a tiny dataset
A teaching Bloom filter has eight bits and two deterministic hash positions per key. A sets {1,4}; B sets {2,6}. An absent C hashes to {1,6}, so both bits are set and the filter returns “possibly present.” A key hashing to {0,3} is definitely absent under this unchanged filter. The exact set {A,B} rejects C. This fixture illustrates collisions; its size is not a production sizing recommendation.
bits after A,B: 0 1 1 0 1 0 1 0
C -> positions 1,6 -> possible hit -> exact lookup says absentRead the diagram
bits after A,B: 0 1 1 0 1 0 1 0; C -> positions 1,6 -> possible hit -> exact lookup says absent
Clearing a shared bit to delete A can make another existing key falsely appear absent; use a deletion-capable design or rebuild under its assumptions. A crawler that skips work on every positive Bloom result may omit pages. A Bloom filter can safely avoid definite misses or reduce expensive exact lookups when positive results are verified.
A count-min sketch increments one counter per hash row and estimates the minimum; collisions overestimate frequency in the ordinary nonnegative update model. It does not retain exact item identities or solve exact top-k alone. HyperLogLog summarizes hashed leading-zero patterns for approximate distinct counts with a configured error/memory tradeoff; merge compatible sketches, not arbitrary incompatible seeds/parameters. Histograms/sketches estimate quantiles under their representation's error contract; bucket counts can merge, independent p99 values cannot.
Show answer and explanation
Answer: Use exact state for billing, access or exclusive ownership. For telemetry or candidate pruning, define acceptable error, test against a reference sample and record parameters so distributed merges remain meaningful.
Step-by-step reasoning
1. 1 · Frame
Start with the decision the estimate drives, the error tolerance, update/query ratio, and whether false positives or false negatives are acceptable. A Bloom filter can say “possibly present” or “definitely absent”; it cannot count. For an estimate used to charge money or enforce a hard cap, approximation may be unacceptable.
2. 2 · Model
Bloom filters use bit arrays and hashes; false positives rise as occupancy grows. HyperLogLog uses hashed leading-zero patterns and register maxima to estimate unique values. Count-Min Sketch uses several counter rows and returns a minimum across hashed positions. Heavy-hitter summaries retain likely leaders; quantile sketches summarize distribution rank. Parameters determine memory and expected error.
3. 3 · Scale
Merge summaries only when their hash seeds, dimensions, and semantics match. Partitioned sketches can be combined for distributed aggregation; version and namespace them. Use exact small-set storage when the expected set fits. For deletion, ordinary Bloom filters cannot remove a key safely; counting Bloom filters add cost and introduce counter saturation concerns.
4. 4 · Recover
Compare estimates against a sampled exact reference and monitor error over time. Rebuild when dimensions or hash versions change. Treat sketch loss as recoverable only if raw events can replay it. Never turn “probably absent” into an irreversible denial without accounting for false negatives in the full pipeline.
Contracts and state
The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.
Bloom(m bits, k hashes): mayContain(key) -> maybe / definitely absent
HLL(registers): add(hash(key)); estimate() -> approximate distinct count
CMS(rows, width): add(key, n); estimate(key) -> upper-biased frequency
All sketches: algorithm + parameters + hash_version + windowWorked example
A crawler uses a Bloom filter to avoid fetching a URL it has already seen. If the filter returns “definitely absent,” enqueue it. If “maybe present,” check the exact durable URL table for important work. A false positive may skip a new URL, so the team measures that risk and periodically reconciles sampled crawl results against exact storage.
Failure walkthrough
A Count-Min Sketch is reused after changing its hash seed; merged counters no longer refer to the same buckets and the result is meaningless. Store algorithm and hash metadata with each shard, reject incompatible merges, and rebuild from retained events. A growing false-positive rate in a Bloom filter often signals capacity assumptions were exceeded.
Read the diagram
Events update versioned sketches → Workers emit compatible summaries → Merge estimates across partitions → Sampled exact counts measure error → Consumer applies stated tolerance
Decisions and trade-offs
| Structure | Question | Main caveat |
|---|---|---|
| Bloom filter | Could this key be present? | False positives; no safe deletion |
| HyperLogLog | How many distinct keys? | Approximate estimate, not identities |
| Count-Min Sketch | How frequent is this key? | Collision overestimation |
| Quantile sketch | What is a distribution percentile? | Merge rules and rank error |
Check your understanding
Choose a structure for URL deduplication, unique visitor estimation, and approximate top queries. State where exact storage remains necessary.
Show answer and explanation
Answer: Use a Bloom filter to identify definitely absent keys; verify possibly present keys against exact state before treating them as repeats, with exact durable lookup where skipping a newly discovered URL is costly. Use HyperLogLog for distinct visitors when an estimate is acceptable. Use Count-Min plus a candidate/heavy-hitter mechanism for approximate frequencies, then verify leaders against exact counters if the product needs a trustworthy final ranking.
Primary documentation
Read the first-party engineering account or official technical reference. Company engineering posts describe the scope and date of that publication; the interview reconstruction and scenarios here are original teaching examples.
Continue the connection
Study YouTube Top K and explain which guarantee from this lesson carries into that topic.
Choose the error contract explicitly
A Bloom filter answers membership with definitely absent or possibly present. A positive can be a false positive, so it must not prove a duplicate where dropping new data is unacceptable. Standard insertion-only Bloom filters do not have false negatives for inserted keys under correct operation; deletion requires another design, such as a counting variant, and its own constraints.
A Count-Min Sketch maintains several hashed counter rows and estimates an item count from their minimum. Collisions overestimate counts for the basic nonnegative-update construction. It does not enumerate heavy hitters by itself; retain candidate identities separately. HyperLogLog estimates distinct cardinality using hashed observations and mergeable registers, but cannot list the distinct items. A reservoir sample supports a representative bounded sample, not exact frequency accounting.
For n expected items and desired false-positive probability p, a Bloom filter needs approximately -n ln(p)/(ln 2)^2 bits, with about (m/n) ln 2 hash functions. For one million items at 1%, this is about 9.6 million bits, or 1.2 MB decimal, and roughly seven hashes. Actual implementation overhead and growth strategy still matter.
Read the diagram
Structure / Question / Main caveat; Bloom filter / Could this key be present? / False positives; no safe deletion; HyperLogLog / How many distinct keys? / Approximate estimate, not identities; Count-Min Sketch / How frequent is this key? / Collision overestimation; Quantile sketch / What is a distribution percentile? / Merge rules and rank error
Operational sketch
insert A -> set bit positions {1,4,7}
query B -> positions {1,4,7} all set -> possibly present
query C -> positions {2,4,7}; bit 2 clear -> definitely absent
positive membership hint -> exact lookup if correctness requires itA tempting mistake
Approximate structures are unsafe when their error direction contradicts the business rule. A false positive in a cache hint may add a lookup; a false positive used to discard a payment can lose legitimate work.
Transfer exercise
Can a Bloom filter alone deduplicate financial events?
Show answer and explanation
Answer: No. A positive needs exact verification before discarding an event. Use authoritative event identity for the financial effect, with the filter only as an optional optimization.
Read the diagram
A sets bits 1,4,7. B hashes to the same set and may be a false positive. C includes clear bit 2 and is definitely absent.
Choose a structure for URL deduplication, unique visitor estimation, and approximate top queries. State where exact storage remains necessary.
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.