Data Structures Inside Real Systems
- Explain what question each "systems" data structure answers, its error model, its memory cost and whether it can be merged
- Size a Bloom filter from n and a target false-positive rate, and implement one in Go
- Choose between exact structures and sketches (count-min, HyperLogLog) for streams in fraud, analytics and flash-sale scenarios
- Describe how Redis sorted sets, LSM-tree databases, Dynamo-style stores and Git use skip lists, Bloom filters and Merkle trees
- Build token buckets, Merkle diffs and consistent-hash rings in Go and know when to use a library instead
TL;DR
- Bloom filter: "definitely not present / probably present" in ≈9.6 bits per item at 1% false positives. Never a false negative. Used in LSM databases to skip files and as a cheap negative cache in front of a database.
- Count-min sketch: frequency estimates that only overestimate, by at most εN with probability 1 − δ. Great for heavy hitters (hot keys, trending products), useless for rare items.
- HyperLogLog: distinct counts with ≈1.04/√m relative error; Redis uses 12 KB per key for 0.81%. Mergeable, so daily uniques roll up into weekly ones.
- Skip lists give O(log n) ordered operations with simple code — Redis sorted sets and LevelDB/RocksDB memtables. B+trees serve read-heavy indexes; LSM trees serve write-heavy storage (see Storage Engines: B-Tree vs LSM).
- Merkle trees find which of n buckets differ between two replicas by exchanging O(k log n) hashes — anti-entropy in Dynamo/Cassandra, Git, blockchains, Certificate Transparency, ledger reconciliation.
- Consistent hashing, geohash/quadtrees, tries, ring buffers, token buckets, LRU/LFU are the remaining everyday building blocks; each maps to an interview "design X" question.
- Every probabilistic structure must be paired with a fallback to the source of truth wherever a wrong answer costs money.
When to reach for it
| Requirement in a design | Structure | Typical system |
|---|---|---|
| "Have we seen this key?" over billions of keys, false positives tolerable | Bloom / cuckoo filter | LSM read path, "username taken" pre-check, CDN one-hit-wonder filtering |
| "How often has X occurred?" on an unbounded stream | Count-min sketch (+ heap for top-k) | Hot-key detection, trending products, TinyLFU cache admission |
| "How many distinct X?" in tiny memory | HyperLogLog | Unique visitors, distinct cards per merchant (card-testing detection) |
| Ordered set with rank and range queries | Skip list / balanced tree | Redis sorted sets, leaderboards, delayed-job queues |
| Durable key-value storage, write-heavy | LSM tree | RocksDB, Cassandra, ScyllaDB |
| Durable index, read-heavy, range scans | B+tree | PostgreSQL, MySQL InnoDB |
| Find divergence between replicas / ledgers cheaply | Merkle tree | Cassandra repair, Git, reconciliation |
| Spread keys over nodes with minimal movement on resize | Consistent hashing | Caches, sharded stores, load balancers |
| "Nearest ATM / store / driver" | Geohash, quadtree, S2/H3 cells | Redis GEO, ride-hailing, delivery zones |
| Prefix lookup / autocomplete | Trie / radix tree | Search suggestions, HTTP routers |
| Fixed-memory recent history, lock-light queues | Ring buffer | Go channels, io_uring, exchange pipelines |
| Throttle requests with bursts | Token bucket | API gateways, golang.org/x/time/rate |
| Bounded cache eviction | LRU / LFU / TinyLFU | Redis eviction, Caffeine, Ristretto |
Core concepts
Bloom filters
A bit array of m bits and k hash functions. Add sets the k bits chosen by the hashes; query checks them — if any bit is 0 the key was never added; if all are 1 it probably was. Bits are never cleared, so there are no false negatives, and plain Bloom filters cannot delete.
The math, for n inserted items:
- False-positive rate:
p ≈ (1 − e^(−k·n/m))^k. - Optimal number of hashes:
k = (m/n) · ln 2. - Bits needed for a target p:
m = −n · ln p / (ln 2)², i.e. ≈ 9.6 bits per item at 1%, ≈14.4 at 0.1%. Every 10× reduction in p costs ≈4.8 more bits per item.
Worked sizing: 10M redeemed voucher codes at p = 1% → m ≈ 95.9M bits ≈ 12 MB, k = 7. At 0.1% → ≈18 MB, k = 10. An exact map[string]struct{} of the same codes costs hundreds of MB (rough, depends on key length and map overhead).
Where they live:
- LSM storage engines (RocksDB, Cassandra, HBase) keep a Bloom filter per SSTable so a point read skips files that cannot contain the key.
- Negative caches: "is this coupon code / username / device fingerprint possibly known?" — answer "no" without touching the database; on "maybe", ask the database.
- CDNs have used Bloom filters to avoid caching "one-hit wonders" (objects requested once), admitting an object only on its second request.
Variants: counting Bloom filters (small counters instead of bits, supports delete), scalable Bloom filters (add layers as n grows), and cuckoo filters (support delete, often smaller at low p). The Go implementation is Problem 1 below.
Count-min sketch
A d × w table of counters with one hash function per row. Update increments one counter per row; estimate takes the minimum of the d counters for the key. Collisions only add, so estimates never undercount. With w = ⌈e/ε⌉ and d = ⌈ln(1/δ)⌉, an estimate exceeds the true count by at most εN (N = total events) with probability at least 1 − δ.
Example: ε = 0.001, δ = 0.01 → w = 2,719, d = 5 → 13,595 counters ≈ 54 KB with 32-bit counters. In a flash sale with N = 50M add-to-cart events, each estimate is within +50,000 of the truth with 99% probability — fine for spotting a product with 2M adds, meaningless for one with 300. Keep a small heap of the current top-k candidates beside the sketch to report heavy hitters (Heaps & Priority Queues). The conservative update variant (increment only the counters equal to the current minimum) reduces overestimation. TinyLFU cache admission, used by Java's Caffeine and Go's Ristretto, is built on a count-min-style frequency sketch.
HyperLogLog
Hash every item; the first p bits pick one of m = 2^p registers, and each register stores the maximum "position of the first 1-bit" seen in the remaining bits. A long run of leading zeros is rare, so its maximum reveals roughly how many distinct hashes went into the register; a bias-corrected harmonic mean across registers gives the estimate. Standard error ≈ 1.04/√m.
- Redis
PFADD/PFCOUNT/PFMERGEuse 16,384 six-bit registers — 12 KB per key, 0.81% standard error — with a sparse encoding for small cardinalities. - Mergeable: the register-wise maximum of two HLLs is the HLL of the union, so per-shard or per-day sketches combine exactly as if built together.
- Intersections are not native; inclusion–exclusion over unions produces large errors when the overlap is small.
Fraud lens: "distinct cards attempted at this merchant in the last hour" spiking is the signature of a card-testing attack; an HLL per merchant per window answers it in kilobytes (Fraud & Risk Systems).
Skip lists
A sorted linked list with express lanes. Each node is promoted to the next level with probability p (Redis uses p = 1/4), so level i holds about n·pⁱ nodes. Search starts at the top level, moves right while the next key is smaller, and drops down a level otherwise — expected O(log n) for search, insert and delete, with no rebalancing.
level 3: head ------------------------------------> 50 -------------> nil
level 2: head ------------> 20 -------------------> 50 -------------> nil
level 1: head ------> 10 -> 20 -------> 30 -------> 50 -------> 70 -> nil
level 0: head -> 5 -> 10 -> 20 -> 25 -> 30 -> 40 -> 50 -> 60 -> 70 -> nil
Searching for 40: level 3 overshoots (50), drop; level 2 reaches 20, then 50 overshoots, drop; level 1 reaches 30, drop; level 0 finds 40.
- Redis sorted sets (ZSET) combine a skip list (ordered by score, for
ZRANGE,ZRANGEBYSCORE) with a hash table (member → score, for O(1)ZSCORE). Each forward pointer stores a span (how many nodes it skips), which makesZRANKO(log n). Small sets use a compact listpack instead. This is the standard leaderboard and delayed-job structure (Real-time Gaming Leaderboard, Redis Deep Dive). - LevelDB/RocksDB memtables are skip lists: concurrent inserts and ordered iteration for flushing to sorted files.
- Why not a red-black tree? Simpler code, easy range iteration along level 0, and lock-free variants are practical.
LSM trees and B+trees: structures composed
Real storage engines are compositions of the structures on this page. An LSM-tree read path:
Writes go to a write-ahead log and the memtable, which is flushed as an immutable sorted file (SSTable); background compaction merges files (a k-way merge). B+trees instead update page-sized nodes in place. The trade-off — LSM: cheap writes, more read and space amplification; B+tree: cheap reads and ranges, random writes — is covered in Storage Engines: B-Tree vs LSM and Indexing.
Merkle trees
Hash each data block (leaf), then hash pairs of hashes up to a single root. Equal roots mean equal data (up to hash collisions). If roots differ, compare the two children and descend only into differing subtrees: with k differing leaves out of n, you exchange O(k log n) hashes instead of all the data.
- Anti-entropy: Dynamo-style stores (Cassandra repair, Riak) build Merkle trees over key ranges to find and repair divergent replicas (Replication).
- Git is a Merkle DAG: a commit hash covers the whole tree of files beneath it.
- Blockchains put a transaction Merkle root in each block header; a light client verifies one transaction with an O(log n) inclusion proof.
- Certificate Transparency (RFC 6962) logs are append-only Merkle trees with inclusion and consistency proofs — the model for tamper-evident audit logs in banking: publish or countersign the root periodically, and any later edit to history changes it.
- Reconciliation: two systems (core banking and a ledger service) bucket accounts identically, hash each bucket's canonical end-of-day balances, and compare roots; only differing buckets are shipped and diffed line by line (Reconciliation & Settlement).
Consistent hashing
Place nodes (as many virtual nodes each) on a hash ring; a key belongs to the first virtual node clockwise from its hash. Adding or removing a node moves only about 1/N of the keys. The lookup is a binary search over the sorted ring:
// HashRing maps keys to nodes; each node appears as vnodes points on the ring.
// hashString (a stable 64-bit hash) is defined in Problem 1 below.
type HashRing struct {
points []uint64 // sorted virtual-node hashes
owner map[uint64]string // virtual-node hash -> node
}
func NewHashRing(nodes []string, vnodes int) *HashRing {
r := &HashRing{owner: make(map[uint64]string)}
for _, n := range nodes {
for v := range vnodes {
h := hashString(fmt.Sprintf("%s#%d", n, v))
r.points = append(r.points, h)
r.owner[h] = n
}
}
slices.Sort(r.points)
return r
}
func (r *HashRing) Lookup(key string) string {
h := hashString(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i] >= h })
if i == len(r.points) {
i = 0 // wrap around
}
return r.owner[r.points[i]]
}
Alternatives: rendezvous (highest-random-weight) hashing (score every node per key, pick the max — no ring, O(N) per lookup) and jump consistent hash (Lamping & Veach, 2014: no memory, but nodes must be numbered 0..N−1 and removed only from the end). Full treatment: Consistent Hashing.
Geohash and quadtrees
Geohash interleaves the bits of longitude and latitude (alternately halving the world east/west and north/south) and encodes them in base-32. A shared prefix means the same cell, so "nearby" becomes a prefix or range query on an ordinary sorted index. Approximate cell sizes at the equator (they narrow toward the poles):
| Geohash length | Cell size (rough) |
|---|---|
| 4 | ≈39 km × 19.5 km |
| 5 | ≈4.9 km × 4.9 km |
| 6 | ≈1.2 km × 0.6 km |
| 7 | ≈153 m × 153 m |
| 8 | ≈38 m × 19 m |
The edge problem: two points a metre apart can sit in different cells with different prefixes, so a radius search queries the target cell and its eight neighbours, then filters by exact distance. Redis GEO stores a 52-bit interleaved geohash as the score in a sorted set and implements GEOSEARCH this way.
A quadtree recursively splits a square into four quadrants until each holds at most a few points, so it adapts to density — deep in a city centre, shallow over the ocean. Google's S2 (cells on a cube projected onto the sphere) and Uber's H3 (hexagons) are production-grade alternatives. Uses: nearest ATM or branch, store pickup and delivery-radius checks in e-commerce, and "impossible travel" fraud rules (two card-present transactions too far apart for the time between them).
Tries, ring buffers, token buckets, LRU/LFU
- Tries / radix trees: O(L) prefix lookups; autocomplete with top-k cached per node, HTTP routers, IP longest-prefix match. See Trees & BSTs and Search Autocomplete.
- Ring buffers: fixed memory, no allocation, predictable latency; Go channel buffers, io_uring, the LMAX Disruptor. See Stacks, Queues & Monotonic Stacks.
- Token buckets: capacity b (burst) and refill rate r (sustained); refill lazily on each request as
tokens = min(b, tokens + elapsed × r). Go'sgolang.org/x/time/rate.Limiteris a token bucket; the distributed version is the same arithmetic in a Redis Lua script. Problem 3 below; algorithms compared in Rate Limiting. - LRU / LFU: LRU is a map plus a doubly linked list (Linked Lists); O(1) LFU keeps a doubly linked list per frequency plus the current minimum frequency. Redis approximates both: it samples a few keys (
maxmemory-samples, default 5) and evicts the best candidate, and its LFU uses a small logarithmic counter that decays over time. W-TinyLFU (Caffeine, Ristretto) adds a frequency-sketch admission filter in front of an LRU, which resists scans that would flush a plain LRU.
Trade-offs
| Structure | Answers | Error model | Memory (rough) | Mergeable | Deletes |
|---|---|---|---|---|---|
| Hash set (exact) | Membership | None | Tens of bytes per key plus the key | Yes (union) | Yes |
| Bloom filter | Membership | False positives only | ≈9.6 bits/item at 1% | Yes (bitwise OR, same parameters) | No (counting/cuckoo variants: yes) |
| Count-min sketch | Frequency | Overestimates by ≤ εN w.p. 1−δ | ⌈e/ε⌉ × ⌈ln(1/δ)⌉ counters | Yes (add tables) | Only with signed counters (loses guarantees) |
| HyperLogLog | Distinct count | ≈1.04/√m relative | 12 KB in Redis for 0.81% | Yes (register max) | No |
| Skip list | Ordered set, rank, range | None | Several pointers per node | Merge of sorted lists | Yes |
| Merkle tree | Where do two datasets differ | Hash collisions (negligible with SHA-256) | One hash per node | Rebuild | Rebuild path, O(log n) |
| Geohash index | Proximity | Cell edges (query neighbours) | One sortable key per point | — | Yes |
In practice
Problem 1 — A Bloom filter in Go (voucher redemption pre-check)
Problem. A flash-sale checkout must reject already-redeemed voucher codes fast. The authoritative store is a database with a unique constraint; you want to avoid a database round-trip for the common case of fresh codes. Build a Bloom filter sized from (n, p).
Approach. Bit array of []uint64; k probe positions from double hashing (Kirsch–Mitzenmacher: g_i = h1 + i·h2 mod m), so you compute one 64-bit hash per key. FNV-1a is stable across processes (unlike hash/maphash, which is seeded per process), so the filter can be persisted or shipped to other replicas; a MurmurHash3 finalizer fixes FNV's weak mixing on short, similar keys.
// hashString returns a stable 64-bit hash: FNV-1a followed by a finalizer.
func hashString(key string) uint64 {
f := fnv.New64a()
f.Write([]byte(key))
return mix64(f.Sum64())
}
// mix64 is the MurmurHash3 64-bit finalizer.
func mix64(h uint64) uint64 {
h ^= h >> 33
h *= 0xff51afd7ed558ccd
h ^= h >> 33
h *= 0xc4ceb9fe1a85ec53
h ^= h >> 33
return h
}
// Bloom is a Bloom filter. It is not safe for concurrent Add; guard it with a
// mutex or set bits with atomic.OrUint64 (Go 1.23+).
type Bloom struct {
bits []uint64
m uint64 // number of bits
k uint64 // number of probes
}
// NewBloom sizes a filter for n expected items at false-positive rate p.
func NewBloom(n int, p float64) *Bloom {
m := math.Ceil(-float64(n) * math.Log(p) / (math.Ln2 * math.Ln2))
k := max(1, math.Round(m/float64(n)*math.Ln2))
words := (uint64(m) + 63) / 64
return &Bloom{bits: make([]uint64, words), m: words * 64, k: uint64(k)}
}
func (b *Bloom) probes(key string) (h1, h2 uint64) {
h1 = hashString(key)
return h1, mix64(h1) | 1 // odd step so successive probes differ
}
func (b *Bloom) Add(key string) {
h1, h2 := b.probes(key)
for i := range b.k {
bit := (h1 + i*h2) % b.m
b.bits[bit/64] |= 1 << (bit % 64)
}
}
// MayContain is false if key was never added, and true if it probably was.
func (b *Bloom) MayContain(key string) bool {
h1, h2 := b.probes(key)
for i := range b.k {
bit := (h1 + i*h2) % b.m
if b.bits[bit/64]&(1<<(bit%64)) == 0 {
return false
}
}
return true
}
func main() {
const n = 1_000_000
bf := NewBloom(n, 0.01)
for i := range n {
bf.Add(fmt.Sprintf("VOUCHER-%08d", i))
}
fp := 0
for i := range n {
if bf.MayContain(fmt.Sprintf("FRESH-%08d", i)) {
fp++
}
}
fmt.Printf("m=%d bits (%.2f MB), k=%d, observed FP rate=%.4f\n",
bf.m, float64(bf.m)/8/1e6, bf.k, float64(fp)/n)
}
Running it prints roughly m=9585088 bits (1.20 MB), k=7, observed FP rate≈0.010 — the observed rate matches the formula. How it is used: on "definitely not redeemed", proceed to redeem (the database unique constraint still guards the race); on "maybe", ask the database. The filter never decides alone that a customer's voucher is invalid.
Complexity. O(k) per operation, m bits of memory. Rebuild or add a layer when the item count exceeds n — the false-positive rate grows quickly past the design size, with no error to warn you.
Problem 2 — Count-min sketch for hot products
Problem. During a flash sale, find products receiving a disproportionate share of add-to-cart events, in fixed memory, across a stream of tens of millions of events.
Approach. A d × w sketch sized from (ε, δ), one seeded hash per row derived from the same base hash. Pair it with a small top-k heap fed by Estimate after each Add.
// CountMin estimates frequencies; estimates never undercount and exceed the
// truth by at most eps*N with probability at least 1-delta.
type CountMin struct {
width uint64
rows [][]uint32
seeds []uint64
}
func NewCountMin(eps, delta float64) *CountMin {
w := uint64(math.Ceil(math.E / eps))
d := int(math.Ceil(math.Log(1 / delta)))
cm := &CountMin{width: w, rows: make([][]uint32, d), seeds: make([]uint64, d)}
for i := range d {
cm.rows[i] = make([]uint32, w)
cm.seeds[i] = mix64(uint64(i) + 1)
}
return cm
}
func (cm *CountMin) col(row int, h uint64) uint64 { return mix64(h^cm.seeds[row]) % cm.width }
func (cm *CountMin) Add(key string, count uint32) {
h := hashString(key)
for r := range cm.rows {
cm.rows[r][cm.col(r, h)] += count
}
}
func (cm *CountMin) Estimate(key string) uint32 {
h := hashString(key)
est := uint32(math.MaxUint32)
for r := range cm.rows {
est = min(est, cm.rows[r][cm.col(r, h)])
}
return est
}
Complexity. O(d) per update and query; O(d·w) memory independent of the number of distinct products. Two sketches with the same dimensions and seeds merge by adding their tables — per-pod sketches roll up to a global view.
Problem 3 — Token bucket per merchant
Problem. Limit each merchant's payment API calls to a sustained 50 requests/s with bursts up to 100.
Approach. Lazy refill on each call; no background goroutine. Use the monotonic clock (time.Now() carries a monotonic reading, so Sub is immune to wall-clock jumps).
// TokenBucket allows bursts up to capacity and a sustained rate in tokens/second.
type TokenBucket struct {
mu sync.Mutex
capacity float64
tokens float64
rate float64
last time.Time
}
func NewTokenBucket(capacity, ratePerSec float64, now time.Time) *TokenBucket {
return &TokenBucket{capacity: capacity, tokens: capacity, rate: ratePerSec, last: now}
}
// Allow consumes one token if one is available at time now.
func (b *TokenBucket) Allow(now time.Time) bool {
b.mu.Lock()
defer b.mu.Unlock()
if elapsed := now.Sub(b.last).Seconds(); elapsed > 0 {
b.tokens = min(b.capacity, b.tokens+elapsed*b.rate)
b.last = now
}
if b.tokens >= 1 {
b.tokens--
return true
}
return false
}
Complexity. O(1) per call, O(1) memory per merchant. In production use rate.NewLimiter(50, 100) from golang.org/x/time/rate per process, and a Redis script (server-side time, atomic read-modify-write) when the limit must hold across replicas.
Problem 4 — Merkle diff of two ledgers
Problem. Core banking and the ledger service each hold end-of-day balances for 1M accounts. Find which account buckets disagree without shipping all balances.
Approach. Both sides assign accounts to the same B buckets (e.g. by account-ID range), serialize each bucket canonically (sorted by account ID — never map iteration order), and build a Merkle tree over bucket hashes. Leaves and internal nodes use different prefixes (as RFC 6962 does) so a leaf can never be passed off as an internal node. Compare top-down and descend only where hashes differ.
func leafHash(data []byte) [32]byte {
return sha256.Sum256(append([]byte{0x00}, data...))
}
func nodeHash(left, right [32]byte) [32]byte {
var buf [65]byte
buf[0] = 0x01
copy(buf[1:33], left[:])
copy(buf[33:], right[:])
return sha256.Sum256(buf[:])
}
// merkleLevels returns every level bottom-up: levels[0] are the leaves and the
// last level holds the root. An odd last node is promoted unchanged.
func merkleLevels(leaves [][32]byte) [][][32]byte {
if len(leaves) == 0 {
return nil
}
levels := [][][32]byte{leaves}
for cur := leaves; len(cur) > 1; {
next := make([][32]byte, 0, (len(cur)+1)/2)
for i := 0; i < len(cur); i += 2 {
if i+1 == len(cur) {
next = append(next, cur[i])
continue
}
next = append(next, nodeHash(cur[i], cur[i+1]))
}
levels = append(levels, next)
cur = next
}
return levels
}
// diffLeaves returns the indexes of leaves that differ between two trees built
// over the same number of buckets, skipping identical subtrees.
func diffLeaves(a, b [][][32]byte) []int {
var out []int
var walk func(level, i int)
walk = func(level, i int) {
if a[level][i] == b[level][i] {
return
}
if level == 0 {
out = append(out, i)
return
}
for _, child := range []int{2 * i, 2*i + 1} {
if child < len(a[level-1]) {
walk(level-1, child)
}
}
}
walk(len(a)-1, 0)
return out
}
Complexity. Building: O(B) hashes. Diffing k differing buckets: O(k log B) comparisons — and across a network, O(k log B) hashes exchanged level by level instead of 1M balances. With B = 4,096 buckets and 3 bad buckets, that is a few dozen hashes, then three buckets of detail.
Practice list
- Easy: Design HashSet (705), Design HashMap (706), Moving Average from Data Stream (346)
- Medium: LRU Cache (146), Implement Trie (208), Design Circular Queue (622), Design Hit Counter (362), Insert Delete GetRandom O(1) (380), Time Based Key-Value Store (981), Design Browser History (1472)
- Hard: LFU Cache (460), Design Skiplist (1206), Design Search Autocomplete System (642), All O'one Data Structure (432)
Common pitfalls
- Letting a probabilistic answer decide money. A Bloom "maybe" that rejects a valid voucher, or an HLL-based limit that blocks a legitimate customer. Use sketches as filters and signals; confirm against the source of truth.
- Outgrowing the design size. A Bloom filter sized for 10M items holding 50M has a false-positive rate near 50%, silently. Monitor insert counts (or the fraction of set bits) and rebuild.
- Per-process hash seeds for shared structures.
hash/maphashand Go map hashing are randomly seeded per process; a filter or sketch built with them cannot be persisted, shipped to another replica, or merged. - Non-canonical serialization in Merkle leaves (map iteration order, float formatting, time zones) produces spurious differences on identical data.
- Count-min for rare items or for exact limits — the error is absolute (εN) and grows with traffic.
- HLL intersections via inclusion–exclusion for small overlaps — error can exceed the answer.
- Consistent hashing without virtual nodes → uneven load and hot shards; too many virtual nodes → large rings and slow rebuilds.
- Geohash radius search on one cell only — misses neighbours across a cell edge.
- Token buckets on wall-clock time — NTP jumps refill or freeze buckets; distributed buckets need a single time source.
Interview angle
- For any structure, answer four questions: what question does it answer, what is its error model, how much memory, can it be merged? That framing signals senior judgment.
- Size things on the spot: "10M keys at 1% is about 12 MB of Bloom filter with 7 hashes" (Back-of-the-Envelope Estimation).
- Expect "design" prompts that hide these structures: leaderboard (sorted set / skip list), unique visitors (HLL), rate limiter (token bucket), nearby stores (geohash), replica repair (Merkle), cache eviction (LRU/TinyLFU), typeahead (trie), flash-sale hot items (count-min + heap) — see Flash Sale System.
- Strong candidates say where exactness is mandatory (balances, idempotency, inventory decrements) and keep sketches out of those paths.
- Red flags: claiming a Bloom filter can have false negatives (or can delete), "HyperLogLog is exact", or adopting a probabilistic structure without a fallback.
Self-check
1. Size a Bloom filter for 50M device fingerprints at a 0.1% false-positive rate.
Bits per item = −ln(0.001) / (ln 2)² ≈ 14.4, so m ≈ 50M × 14.4 ≈ 720M bits ≈ 90 MB, and k = 14.4 × ln 2 ≈ 10 hashes. At 1% it would be ≈9.6 bits per item ≈ 60 MB with k = 7.
2. Why can a Bloom filter return false positives but never false negatives?
Adding a key sets its k bits to 1 and nothing ever clears them, so a key that was added always finds all its bits set. A key that was never added can also find all its bits set if other keys happened to set them — a false positive. Deletion would require clearing bits that other keys share, which could create false negatives; that is why plain Bloom filters do not support it.
3. What do a count-min sketch's width and depth control?
Width w controls the error magnitude: collisions per row shrink as w grows, giving an overestimate of at most εN with ε = e/w. Depth d controls the confidence: each extra independent row multiplies the chance that every row is badly overestimated by about 1/e, so δ = e^(−d). Memory is w × d counters, independent of the number of distinct keys.
4. How do Redis sorted sets support both ZSCORE in O(1) and ZRANK in O(log n)?
A ZSET stores a hash table from member to score (O(1) ZSCORE) alongside a skip list ordered by (score, member). Each skip-list forward pointer records its span — the number of level-0 nodes it jumps over — so summing spans along the search path yields the rank in O(log n). Small sets use a compact listpack instead.
5. Two replicas hold 10M keys and differ in about 20 keys. How does a Merkle tree reduce the repair cost?
Both build trees over the same key ranges and compare roots. Where hashes differ they compare children, descending only into differing subtrees. With 20 differing leaves the comparison touches about 20 × log₂(leaves) nodes instead of 10M keys, and only the differing ranges are streamed for repair.
6. Why does a geohash radius search query nine cells?
Geohash cells have hard edges: a point just across a boundary has a different prefix even if it is a metre away. Querying the target cell and its eight neighbours covers every point within one cell width of the target, after which an exact distance filter removes points outside the radius.
7. Scenario: the fraud team wants, per merchant, the number of distinct cards used in the last hour, for 2M merchants, updated in real time. Exact or approximate?
Exact sets would hold every card per merchant per window — potentially gigabytes in hot periods. An HLL per merchant per time bucket (e.g. 5-minute buckets merged for the hour) costs kilobytes each with ≈1% error, which is ample for a spike signal (card testing shows 10× jumps). Keep exact state only where a rule blocks payments outright, or use the HLL as a trigger for an exact secondary check.
Exercise
Build a flash-sale analytics sidecar and measure it against exact structures:
- Generate a synthetic stream of 20M add-to-cart events over 100k products with a Zipf distribution (
math/rand/v2has a Zipf generator) and 2M distinct users. - Maintain (a) a
CountMinplus a top-20 heap and (b) an exactmap[string]int; compare the top-20 lists and the memory used (runtime.ReadMemStats). - Estimate distinct users with Redis
PFADD/PFCOUNT(or a small HLL you write) and compare with an exact set. - Add the
Bloomfilter in front of a fake "redeemed vouchers" store and report how many store lookups it avoided and its observed false-positive rate.
Done when you have a table of memory, error and throughput for each pair, and a short recommendation of which ones you would ship in production and why.
Further reading
- Burton Bloom, "Space/Time Trade-offs in Hash Coding with Allowable Errors" (CACM, 1970); Kirsch & Mitzenmacher, "Less Hashing, Same Performance: Building a Better Bloom Filter" (2006)
- Graham Cormode & S. Muthukrishnan, "An Improved Data Stream Summary: The Count-Min Sketch and its Applications" (2005)
- Flajolet, Fusy, Gandouet, Meunier, "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm" (2007); Heule, Nunkesser, Hall, "HyperLogLog in Practice" (2013)
- William Pugh, "Skip Lists: A Probabilistic Alternative to Balanced Trees" (CACM, 1990)
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store" (SOSP 2007) — consistent hashing, Merkle anti-entropy
- RFC 6962, "Certificate Transparency" — Merkle tree logs and proofs
- Einziger, Friedman, Manes, "TinyLFU: A Highly Efficient Cache Admission Policy" (2017)
- Redis documentation: probabilistic data types, sorted sets, geospatial indexes, key eviction
- Martin Kleppmann, Designing Data-Intensive Applications — chapter 3 (storage and retrieval)
Related
- Storage Engines: B-Tree vs LSM — how these structures compose into databases.
- Redis Deep Dive — sorted sets, HyperLogLog, GEO and eviction in practice.
- Consistent Hashing — rings, virtual nodes and alternatives.
- Rate Limiting — token bucket vs leaky bucket vs windows.
- Replication — anti-entropy and read repair.
- Caching — eviction and admission policies.
- Batch & Stream Processing — sketches in streaming pipelines.
- Flash Sale System — hot items, vouchers and limits under peak load.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).