← Building blocks

Count big things with small memory

Data processing & searchsenior

Unique visitors, top-k items or membership checks over billions of events.

Say it like this

Unique visitors per link over billions of clicks do not need to be exact, so I keep a HyperLogLog per alias at about 12 KB regardless of cardinality and accept a 1 percent error instead of storing every visitor id.

Basic solution

Use probabilistic structures: HyperLogLog for cardinality, Bloom filters for membership, Count-Min Sketch for frequencies.

Redis PFADD / PFCOUNTBloom filterCount-Min Sketchtop-k sketches

Three sketches, one hash

Every item is hashed once; the hash feeds registers (HyperLogLog), bit positions (Bloom filter) or counters (Count-Min). Each structure is a fixed size and merges across shards and time windows.

How it works

  1. Hash each incoming item (a visitor id, an event id) with a good hash function into a fixed-width value. Everything below works on that hash, never on the raw item, which is what makes the memory cost independent of the item's size.
  2. HyperLogLog, for counting distinct items: take the first p bits of the hash to choose one of 2^p registers, and in that register record the longest run of leading zeros seen in the remaining bits. A long run of zeros is rare, so seeing one implies many distinct inputs passed through; the estimate combines all registers with a harmonic mean. The error is about 1.04 / sqrt(2^p), so p = 14 gives 16,384 registers, 12 KB of memory, and roughly 0.8 percent error.
  3. Bloom filter, for membership: keep an array of m bits, all zero. To insert an item, compute k hashes and set the k bits they point to. To check an item, compute the same k positions: if any bit is zero the item was definitely never inserted; if all are one it probably was, with a false-positive rate you choose when sizing m for the expected number of items n.
  4. Count-Min sketch, for frequencies: keep d rows of w counters. To record an item, each of d hash functions picks one counter in its row and increments it. To estimate an item's count, read its d counters and take the minimum; collisions can only inflate a counter, so the estimate is never too low.
  5. Top-k: feed the stream through a Count-Min sketch and keep a small heap of the current leaders, updating the heap when an item's estimate exceeds the smallest leader; or use a Space-Saving summary that tracks k candidates with explicit error bounds.
  6. All of these merge: the union of two HyperLogLogs is the maximum per register, two Bloom filters combine with a bitwise OR, two sketches add counter by counter. That is what lets you keep one per shard and per time window and combine them later.

Why not a set

  • An exact distinct count needs every id stored at least once; for 100M visitors that is gigabytes per metric per window. The sketch is kilobytes and merges across partitions for free.

Worked example

Unique visitors per short link, URL shortener

  • 345M clicks per day across 100M aliases, of which about 2M are active on any day. Need unique visitors per alias per day and per month, plus daily uniques overall.
  • Exact: store each (alias, day, visitor_hash). 345M rows per day at 24 bytes each is about 8 GB per day, 240 GB per month, plus the index, and a monthly unique count per alias is a distinct over 30 days of rows.
  • HyperLogLog with p = 14: 12 KB per alias per day. 2M active aliases x 12 KB = 24 GB per day, which is worse than exact for the long tail because most aliases have a handful of visitors. Use the sparse representation: Redis stores small HLLs in a few hundred bytes and only promotes to the dense 12 KB above a few thousand items, so the real footprint is closer to 2M x 400 B = 800 MB per day.
  • Monthly uniques per alias: merge the 30 daily HLLs with PFMERGE in microseconds; no rescans. Daily uniques overall: PFMERGE across all active aliases, one command.
  • Error: at p = 14 the standard error is 0.81 percent; a link with 1,000,000 true uniques reports somewhere between 992,000 and 1,008,000 most of the time. A link with 10 visitors is counted almost exactly: with 16,384 registers and so few items, each item lands in its own register and the estimator falls back to linear counting, whose error at that size is negligible.
  • Bloom filter for "has this visitor clicked this alias before" to flag repeat visits: 1M visitors at a 1 percent false-positive rate needs m = 9.6M bits = 1.2 MB with k = 7 hashes; an exact set of 1M 8-byte hashes is 8 MB before overhead.
  • Count-Min for the top referrers per alias: width 2,000 x depth 5 = 10,000 counters = 40 KB per alias; the error on any count is at most about 0.14 percent of total clicks (e divided by the width) with 99 percent confidence.

Variants and when each wins

HyperLogLog

  • A fixed array of small registers that estimates how many distinct items it has seen, in about 12 KB with roughly 1 percent error, and merges by taking the maximum per register. It wins for any distinct count shown as a round number: unique users, unique IPs, unique sessions.

Bloom filter and cuckoo filter

  • A bit array that answers "have I seen this?" with no false negatives and a tunable false-positive rate; a cuckoo filter is the variant that also supports deleting items. They win for skipping work on a hot path, such as checking whether an id was already processed or whether a key might be in an LSM file.

Count-Min Sketch

  • A small grid of counters that estimates how often each item appeared and can only over-count. It wins for finding heavy hitters and top-k over an unbounded key space in a few kilobytes.

Reservoir sampling and t-digest

  • Reservoir sampling keeps a bounded random sample of a stream; a t-digest keeps a compact summary of the value distribution for percentiles. They win for latency percentiles and samples over streams, and merge like the others.

Recommendation: HyperLogLog for any distinct count the product shows as a round number, Bloom filters for pre-checks on a hot path, Count-Min plus a heap for top-k; keep exact counting for anything billed or audited.

Failure modes

Error presented as exact

  • A customer complains that their unique-visitor count moved from 1,002 to 998 overnight. It happens because the number is an estimate from a dense HyperLogLog and the UI showed it as if it were exact. Show rounded numbers, label them approximate in the interface, and for small sets keep an exact set of ids alongside the sketch until it grows past a few thousand, then switch to the estimate.

Sketch sized for the wrong n

  • Bloom filter false positives climb to 30 percent and the pre-check stops saving any work. It happens because the filter was sized for 1M items and now holds 10M, so most bits are set. Size it from the expected maximum, monitor the fraction of bits set, and rebuild it or switch to a scalable Bloom filter when the fill crosses the target.

Hash collisions from a weak hash

  • Estimates are biased low for certain id formats. It happens because the hash does not spread inputs evenly, for example CRC over sequential ids, so many items land in the same registers. Use MurmurHash3 or xxHash with a seed, and never truncate a structured id and call it a hash.

Merging sketches with different parameters

  • PFMERGE returns an error, or a merged count is nonsense. It happens because shards built their sketches with different precision (p) or different hash seeds, and registers from one do not correspond to registers of the other. Fix p and the hash seed in shared configuration, version the sketch format, and validate parameters on merge.

Using a sketch where exactness is required

  • A billing dispute over 0.5 percent of a count. It happens because an invoice line was computed from a HyperLogLog estimate. Use exact counts for anything involving money or compliance, and reserve sketches for dashboards and ranking.

Interviewer follow-ups

Answer out loud before you open each one.

How does HyperLogLog get a count from the longest run of leading zeros?

If hashes are uniform, a run of r leading zeros appears about once in 2^r items, so the longest run seen hints at how many items there were. One register is very noisy, so the hash is split across thousands of registers and their estimates are averaged with a harmonic mean, which is what pushes the error down to about 1 percent.

Why can a Bloom filter never give a false negative?

Inserting an item sets its k bits and bits are never cleared, so every item that was inserted still has all its bits set at lookup time. False positives happen only because other items may have set the same bits.

How do you count uniques per hour, per day and per month without three pipelines?

Keep one HLL per alias per hour. Merge 24 of them for the day and 720 for the month with a register-wise max, which is exact with respect to the sketch, so coarser windows are a cheap merge rather than a recount.

When would you choose Count-Min over just counting in Redis?

When the key space is unbounded, such as referrer URLs or search terms, and you only need the top few hundred. A Redis counter per key grows without limit; a 40 KB sketch bounds memory and still identifies the heavy hitters, with a small heap to hold the current leaders.

Connections

Built on
Heap / priority queue · Bloom filter · HyperLogLog · Count-Min sketch · CRDT
Pairs with
Compute over events as they arrive · Process large data offline · Drop duplicate events · Analytics without hurting production · Write-optimised vs read-optimised storage
Pulls against
Do read-modify-write atomically
Used in
URL Shortener (TinyURL / bit.ly) · Video Streaming Platform (YouTube / Netflix)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingStats APICompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad