Beyond Maps: 5 Probabilistic Data Structures Every Go Engineer Should Master
This article introduces five probabilistic data structures—Bloom Filter, HyperLogLog, Count-Min Sketch, T-Digest, and Top-K Sketch—explaining their principles, error models, Go implementations using the unsure library, and real-world applications in databases, monitoring, and streaming systems.
Reading font

In software development we often insist on exact answers: using maps to record every element, counters for every event, sorted arrays for precise percentiles. But at tens or hundreds of millions of items — or unbounded streams — exact computation incurs huge memory and CPU costs. Probabilistic data structures trade a tiny, well‑defined loss of certainty for orders‑of‑magnitude smaller memory footprints.
Three Core Error Models
False Positive – element reported as present when it is not (e.g., Bloom Filter).
False Negative – element reported as absent when it is present (classic Bloom Filter never does this).
Estimation Error – a numeric approximation with a bounded deviation (e.g., HyperLogLog, Count‑Min Sketch, T‑Digest). Count‑Min Sketch’s error is one‑sided: estimate ≥ true count, with error ≤ ε·N at probability 1‑δ.
These guarantees come from mathematical analysis of hash behavior, not from random runtime fluctuations; fixed seeds yield deterministic results.
Sketch Family Common Traits
Memory far smaller than raw data.
Updates suit continuous streams.
Many support merging summaries for distributed computation.
Bloom Filter: Membership Test
Proposed by Burton Bloom (1970). A bit array of length m; k hash functions set bits on insert. Query checks all k bits: any 0 ⇒ definitely absent; all 1 ⇒ possibly present. False‑positive rate p ≈ (1 - e^(-kn/m))^k. For 1M items at 1% false positives, m ≈ 9.6M bits ≈ 1.2 MB.
Go Example (github.com/nalgeon/unsure/bloom)
filter := bloom.New(1000, 0.01) // 1000 items, 1% FPR
filter.Add([]byte("alice"))
filter.Add([]byte("bob"))
fmt.Println(filter.Contains([]byte("alice"))) // true
fmt.Println(filter.Contains([]byte("carol"))) // falseUse cases: cache‑penetration protection, LSM‑Tree SSTable lookups, search‑engine block pruning, distributed storage cross‑node reduction. VictoriaLogs uses Bloom Filters to skip log blocks that cannot contain a search term.
Engineering Notes
Classic Bloom Filter doesn’t support deletion (shared bits). Counting Bloom Filter or Binary Fuse Filter (for static sets) are alternatives.
Exceeding designed capacity raises false‑positive rate.
HyperLogLog: Cardinality Estimation
Estimates distinct elements (UV, unique IPs, distinct column values) using leading‑zero distribution of hashed values. Registers store max rank per bucket; final estimate combines registers. Standard error ≈ 1.04/√m where m = 2^p (p = precision). At p=14, error ~0.81% with fixed ~16 KB memory regardless of cardinality.
Go Example (github.com/nalgeon/unsure/hll)
visitors := hll.New()
visitors.Add([]byte("alice"))
visitors.Add([]byte("bob"))
visitors.Add([]byte("alice"))
visitors.Add([]byte("carol"))
fmt.Println(visitors.Count()) // ~3Merge: independent sketches can be merged for global distinct count.
home.Merge(docs)
fmt.Println(home.Count()) // 3 (alice, bob, carol)Use cases: website UV, COUNT DISTINCT in data warehouses, log deduplication, distributed analytics. Apache DataFusion’s approx_distinct() uses HyperLogLog.
Count‑Min Sketch: Frequency Estimation
2D counter matrix (d rows × w columns) with independent hash per row. Insert increments all d counters; query takes minimum across rows. Error guarantee: true ≤ estimate ≤ true + ε·N with probability ≥ 1‑δ. Overestimation only; low‑frequency items suffer larger relative error.
Go Example (github.com/nalgeon/unsure/countmin)
sketch := countmin.New(0.001, 0.01) // ε=0.1%, δ=1%
sketch.Add([]byte("/api/users"))
sketch.Add([]byte("/api/orders"))
sketch.AddN([]byte("/api/users"), 2)
fmt.Println(sketch.Count([]byte("/api/users"))) // 3
fmt.Println(sketch.Count([]byte("/api/orders"))) // 1
fmt.Println(sketch.Total()) // 4Use cases: API frequency, IP request counts, real‑time traffic monitoring, cache eviction heuristics, network flow analysis. Often paired with Top‑K for heavy hitters.
T‑Digest: Quantile Approximation
Compresses values into weighted centroids (mean, weight). Centroid size varies: finer granularity at tails (for P95/P99), coarser in middle. Enables P99 latency calculation without storing all samples. Supports merging for distributed percentiles.
Go Example (github.com/nalgeon/unsure/tdigest)
digest := tdigest.New()
latencies := []float64{12.5, 8.1, 130.0, 20.3, 15.2, 18.7, 9.8, 200.0}
for _, l := range latencies { digest.Add(l) }
fmt.Println("P50:", digest.Quantile(0.50)) // 18.7
fmt.Println("P99:", digest.Quantile(0.99)) // 200Use cases: Prometheus‑style monitoring, service P95/P99/P999, sensor data distributions, real‑time price quantiles. Note: T‑Digest is an approximate structure, not strictly probabilistic via randomization.
Top‑K Sketch: Heavy Hitters
Finds the K most frequent items in a skewed stream. Uses HeavyKeeper: fixed bucket array with fingerprints and counts; on collision, existing count probabilistically decays, freeing space for new items. Maintains a min‑heap of K candidates. Returns approximate top‑K with estimated counts.
Go Example (github.com/nalgeon/unsure/topk)
sketch := topk.New(2)
sketch.Add([]byte("alice"))
sketch.Add([]byte("bob"))
sketch.Add([]byte("carol"))
sketch.AddN([]byte("alice"), 4)
sketch.AddN([]byte("carol"), 2)
fmt.Println(sketch.Top()) // [{alice 5} {carol 3}]Use cases: hot URLs, frequent IPs, search keyword rankings, elephant flows, real‑time anomaly detection.
Go Engineering Practice: the unsure Library
All examples use Anton Zhiyanov’s unsure ( go get github.com/nalgeon/unsure). Sub‑packages: bloom, countmin, hll, tdigest, topk, plus binaryfuse, ultraloglog, loglinearhistogram. The library optimizes for CPU cache (e.g., Blocked Bloom Filter fits queries in a 64‑byte cache line). Benchmark on your own data/hardware before production.
Selection Guide
Need: Element may exist? → Structure: Bloom Filter → Main Limitation: No direct deletion.
Need: Distinct count? → Structure: HyperLogLog → Main Limitation: Cannot query specific element.
Need: Element frequency? → Structure: Count‑Min Sketch → Main Limitation: Cannot enumerate all elements.
Need: P99/P999 latency? → Structure: T‑Digest → Main Limitation: Merge may reduce precision.
Need: Top‑K hot items? → Structure: Top‑K Sketch → Main Limitation: Results are approximate.
Need: Static set membership? → Structure: Binary Fuse Filter → Main Limitation: Immutable after creation.
Production Considerations
Error tolerance: financial/inventory counts need exactness.
Capacity planning: estimate data scale; handle overflow.
Deletion & time windows: most sketches don’t delete; use sharded sketches per window.
Distributed merge: ensure parameter consistency, watch error accumulation.
Adversarial inputs: hash collisions can be exploited; use keyed hashes, capacity limits.
Real‑World Adoption
VictoriaLogs: Bloom Filters skip irrelevant log blocks.
Apache DataFusion: approx_distinct() via HyperLogLog.
Streaming engines: Count‑Min Sketch & Top‑K track frequencies/hot keys in unbounded streams.
Monitoring systems: T‑Digest maintains latency percentiles with bounded memory.
Probabilistic data structures are not academic curiosities — they are standard components in modern databases, search engines, caches, and stream processors. The design principle: not every business question requires storing all data, nor does every result need exact precision. When you reach for a growing map[string]uint64, ask: Do I really need to keep every element exactly? A few‑KB sketch may suffice.
About this article
For attribution, corrections or content rights, contact