SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Bloom Filters
  • Cuckoo Filter
  • Skip Lists
  • Count-Min Sketch
  • HyperLogLog
  • Merkle Trees
  • MinHash
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Probabilistic and Other Structures

HyperLogLog

Count the number of different items in a huge set with just a few kilobytes.

โฑ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

HyperLogLog (HLL) estimates how many different items are in a huge set (the "cardinality"), using only a few kilobytes, with an error of about one or two percent.

  • Counting different users exactly means remembering every user. For a billion users that is gigabytes.
  • HLL hashes each item into random-looking bits and only remembers, in each of a few registers, the longest run of leading zeros it has seen.
  • A rare long run of zeros means "I have probably seen a lot of different items". Combining many registers turns that into a good estimate.

02Concept: What is it?

Suppose you flip a fair coin and write down the longest run of heads in a row. If the longest run you ever saw was 3, you probably flipped only a few times. If you saw a run of 20 heads, you must have flipped millions of times, because a run that long is very rare. The length of the longest run tells you roughly how many tries there were.

HyperLogLog does exactly this with hash bits. A good hash turns every item into a random-looking string of bits, and the same item always gives the same bits. The chance that a hash starts with k zeros is 1 in 2k. So if the longest run of leading zeros you have seen is k, you have probably seen around 2k different items.

One lucky hash could fool you, so HLL uses many registers (say 1,024) to even out the luck:

  • Use the first p bits of the hash to choose a register. With p = 10 there are 210 = 1,024 registers.
  • In the remaining bits, count the leading zeros and add 1. This is the rank.
  • The register keeps the maximum rank it has seen.
  • To estimate, combine all registers with a harmonic mean and a correction constant, and multiply by the number of registers.
One item going into HyperLogLog
๐Ÿ‘คuser-8421
โ†’โ†“hash
๐Ÿ”ข0110 | 0001 0110โ€ฆfirst bits | the rest
โ†’โ†“split
Registerfrom the first bits
Rankleading zeros + 1
โ†’โ†“keep the max
๐Ÿ—„๏ธUpdate register
The same item always lands in the same register with the same rank, so repeats change nothing.
๐Ÿง Duplicates are free
Adding the same user 1 time or 1,000 times gives the same hash, so the same register and the same rank. The registers do not change, and the answer stays the same. This is exactly why it counts different items and not visits.

03Real-Life Example

๐ŸตThe Coin-Flip Contest
A school holds a contest where each student flips a coin until it lands tails, and reports how many heads came first. Nobody knows how many students entered. The teacher only asks for the best result in each classroom (there are 16 classrooms). In a small contest the best run is 2 or 3. In a huge contest someone will have a run of 12. By looking at the best run in each classroom and combining those 16 numbers, the teacher can guess how many students took part, without a list of names and without counting anyone twice. If one student enters again, they do the same flips (their hash is the same), so nothing changes.
Coin-flip contest
HyperLogLog
A student
An item (a user ID, an IP address)
The flips of that student
The hash bits of the item
Heads before the first tails
Leading zeros before the first 1
A classroom
A register
Best run in that classroom
The maximum rank in the register
Combining the 16 best runs
Harmonic mean across registers
A student who enters twice
A repeated item, which changes nothing
From registers to an estimate
๐Ÿ—„๏ธm registersranks like 3, 1, 5, 2, 4โ€ฆ
โ†’โ†“2^(โˆ’rank)
โž—Harmonic meanand constant ฮฑ
โ†’โ†“ร— mยฒ
๐ŸŽฏEstimatedifferent items

04Why Do We Need It?

๐Ÿง Tiny memory
A sketch of a few KB counts billions of different items. An exact set needs memory for every item.
๐ŸŽฏPredictable error
The typical error is about 1.04 / โˆšm. More registers means a smaller error.
โšกConstant time
Adding an item is one hash and one compare. Reading the answer is a pass over the registers.
๐Ÿ”€Mergeable
To get the union of two sketches, take the maximum of each register pair. Great for combining servers or days.
๐ŸŒŠOne pass
It works on a stream. You never need to store or sort the items.
๐Ÿ“ŠMany counters at once
Because it is so small, you can keep one per page, per day or per country.
Exact distinct counting needs memory for every distinct item. If an answer within a percent or two is good enough, HyperLogLog gives it in a few kilobytes.

05Where Do We Use It?

๐Ÿ‘ฅUnique visitors
Daily or monthly active users, and unique viewers of a page or video.
๐ŸŒUnique IP addresses
How many different clients hit a service, or a possible attack.
๐Ÿ”ŽUnique search terms
How many different queries were seen in an hour.
๐Ÿ—ƒ๏ธDatabase statistics
Query planners estimate how many different values a column has.
๐Ÿ“ŠAnalytics engines
Approximate distinct counts are built into systems like Redis, BigQuery, Presto and Druid.
๐ŸงฉSet size across shards
Merge partial sketches from many partitions into one answer.

06Types / Parts / How It Works

The algorithm in steps

Add and estimate
Add(item)
1๏ธโƒฃh = hash(item)
โ†“
2๏ธโƒฃindex = first p bits of h
โ†“
3๏ธโƒฃrank = leading zeros of the rest + 1
โ†“
4๏ธโƒฃregister[index] = max(old, rank)
Estimate()
1๏ธโƒฃZ = sum of 2^(โˆ’register)
โ†“
2๏ธโƒฃE = ฮฑ ร— mยฒ / Z
โ†“
3๏ธโƒฃFix small and huge countslinear counting for small
Everything depends on a hash with well-spread bits.

Registers and accuracy

Bits pRegisters m = 2^pTypical error (1.04 / โˆšm)Memory at 6 bits per register
416About 26%12 bytes
8256About 6.5%192 bytes
101,024About 3.3%768 bytes
124,096About 1.6%3 KB
1416,384About 0.8%12 KB

Distinct counting options

MethodAccuracyMemoryCan merge?
Hash set of all itemsExactGrows with every different itemYes, but expensive
Bitmap / bit array (one bit per ID)ExactGrows with the ID rangeYes (OR)
HyperLogLogAbout 1 to 3%Fixed, a few KBYes (max per register)
Bloom filterNot a countFixedYes (OR)
Count-Min SketchCounts each item, not distinctFixedYes (add)
๐Ÿ“Small and large corrections
For very small sets many registers are still 0, and the main formula is off. HLL then switches to linear counting (m ร— ln(m / zeros)). Improved versions such as HyperLogLog++ also fix the bias for mid-size counts and for 64-bit hashes.
VisualizerEstimate the number of different usersRaise the number of different users and watch the registers fill. Then lower the register bits to save memory and see the error grow. Change the visits per user: the answer does not change.
How often does each user come back?
The first 3 users, as 32-bit hashes. Cyan = the first 6 bits pick the register. Amber = the leading zeros. Green = the first 1. Rank = zeros + 1.
user 000010001111111010000001011101011register 4, rank 2
user 110111011001010101010111111011110register 46, rank 1
user 211010110101000111101111011101100register 53, rank 1
Registers after 1,000 different users (each keeps the biggest rank it has seen; brighter = bigger):
4
8
5
9
4
9
5
6
7
3
3
5
4
6
5
6
5
9
5
6
4
9
4
5
5
5
6
4
4
3
5
5
5
6
6
5
5
7
3
6
4
6
6
3
6
7
9
4
6
7
4
3
6
3
4
3
4
4
6
9
5
5
6
6
Estimate
1,113
different users
Real number
1,000
1,000 visits in total
Error
+11.3%
typical ยฑ13.0%
Memory
48 B
exact list: 7.8 KB
The estimate is 1113 for 1000 real items: +11.3%. That is inside the typical error of about ยฑ13.0%.

Repeat visits do not change the registers at all: the same user always gives the same hash, so the estimate is the same for 1, 5 or 20 visits each. A plain counter would say 1,000. Memory assumes 6 bits per register and 8 bytes per user ID in the exact list. Typical error is 1.04 / โˆšregisters.

07How to Use It / Steps / Implementation

Using HyperLogLog well

  1. 1
    Pick the precision
    Choose p from your error budget. p = 14 gives about 0.8% error with 12 KB, which is a common default.
  2. 2
    Use a strong hash
    A 64-bit hash with well-spread bits (such as MurmurHash or xxHash). A weak hash ruins the estimate.
  3. 3
    Add every item
    Hash it, split the bits, and update one register with the maximum rank. Repeats do no harm.
  4. 4
    Read the estimate when needed
    Use the library function. Do not write the bias corrections by hand unless you have to.
  5. 5
    Merge with max
    To count distinct items across servers or days, take the maximum of each register pair. Both sketches must use the same p and the same hash.
  6. 6
    One sketch per question
    Keep one sketch per page per day, say. Merge them later for a week, a month, or all pages.
  7. 7
    Store the sketch, not the items
    Save the registers (a few KB) in your database or cache. You can estimate again later and merge new data in.
๐Ÿ’กUnion is easy, intersection is not
Merging gives you the number of different items in A or B. For items in A and B you can estimate from the identity |A โˆฉ B| = |A| + |B| โˆ’ |A โˆช B|, but the error can be large when the overlap is small. Use MinHash or exact methods when overlaps matter.
โš ๏ธYou cannot remove items
Registers only keep a maximum, so there is no way to take an item out. Use time windows (one sketch per day) when you need "the last 7 days".

08Key Terms to Know

TermMeaning in easy words
CardinalityThe number of different items in a set (not the total number of events)
Distinct countAnother name for cardinality, as in COUNT(DISTINCT user_id)
HyperLogLog (HLL)A sketch that estimates cardinality using a few KB of registers
RegisterA small counter that stores the largest rank seen for its share of the items
RankThe number of leading zero bits in the hash remainder, plus 1
Precision (p)The number of hash bits used to choose a register. There are 2^p registers
Harmonic meanA way of averaging that is not thrown off by one very big value
Standard errorThe typical size of the error. For HLL it is about 1.04 divided by โˆš(number of registers)
Linear countingA better formula for small sets, based on how many registers are still 0
HyperLogLog++An improved version with a 64-bit hash, bias correction and a compact form for small sets
Merge (union)Combine two sketches by taking the maximum of each register pair

09Pros, Cons and Trade-offs

โœ… Pros
  • A few KB for billions of items
  • Constant time per item
  • Typical error of 1 to 2% is easy to reach
  • Mergeable across servers and time
  • Duplicates have no effect
โš ๏ธ Cons
  • The answer is approximate
  • Cannot delete items
  • Cannot list or look up items
  • Intersection estimates are weak
  • Needs a good hash, and details such as bias correction are tricky

Trade-offs

ChoiceWe gainWe lose
More registers (higher p)Smaller errorMore memory per sketch
Fewer registersTiny sketches, so you can keep millions of themA bigger error
HyperLogLog instead of a setFixed, small memoryExactness and the ability to list items
Sketch per time windowEasy โ€œlast N daysโ€ questions by mergingMore sketches to store
64-bit hashWorks for very large countsSlightly more work per item
Sparse form for small setsVery small memory when few itemsMore complex code and a switch to the dense form later

10Common Problems and Mistakes

Common mistakes

  1. Treating it as exact. Reports that need an exact number (billing, legal) must not use an estimate.
  2. A weak hash. Bits that are not random-looking break the maths and give a biased answer.
  3. Using it to count events. HLL counts different items. Use a plain counter for the number of events.
  4. Merging sketches with different settings. They must share the same p and the same hash.
  5. Trying to subtract. Subtracting two sketches does not work. Plan for time windows instead.
  6. Trusting a tiny sketch. With p = 4 the error is about a quarter of the answer.
  7. Estimating overlaps from small ones. An intersection computed from two big sketches can be wildly off.

Things to watch

๐Ÿ“Error is relative
A 1% error on a billion is 10 million. Make sure that is acceptable for the use.
๐ŸŽฒSingle-run luck
The error is typical, not a promise. A given sketch can be off by 2 or 3 times the typical error.
๐Ÿ”‘Hash choice
Keep the same hash across all sketches that you want to merge, forever.
๐Ÿ›ก๏ธPrivacy
Sketches hold no raw IDs, which helps, but treat them as derived user data and follow your policy.

11Real-World Examples

๐ŸŸฅRedis PFADD / PFCOUNT
Redis has HyperLogLog built in. Each key uses a small, fixed amount of memory (around 12 KB at most).
๐Ÿ”Google BigQuery
APPROX_COUNT_DISTINCT uses a HyperLogLog-type sketch to make distinct counts fast and cheap.
๐Ÿ“ˆPresto, Trino and Spark
approx_distinct and approx_count_distinct are standard HLL-based functions.
๐ŸงฎDruid and Pinot
Real-time analytics stores keep sketches per segment and merge them at query time.
๐Ÿ“บUnique viewers
Counting unique viewers per video or per ad without storing every ID.
๐Ÿ•ธ๏ธWeb scale research
The original idea came from the Flajolet and Martin line of work and was refined into HyperLogLog by Flajolet and colleagues.
๐Ÿ“Note
Function names, limits and accuracy settings differ by product and version. Check your tool's documentation.
Mini case: unique visitors per day, then per week
๐Ÿ“…Mon โ€ฆ Sunone sketch per day
โ†’โ†“max of registers
๐ŸงฌMerged sketch
โ†’โ†“estimate
๐Ÿ‘ฅUnique visitorsthis week
Daily data Merge Answer
Store one tiny sketch per day. A week is just the merge of seven sketches.
Exact: 8 bytes per ID ร— 1 billion users (idea)gigabytes
HyperLogLog with p = 14about 12 KB

12Related Topics to Read Next

Bloom Filtersโ†’

Another tiny-memory structure, but it answers whether an item was seen.

Count-Min Sketchโ†’

Counts how often each item appeared, while HLL counts how many different items.

MinHashโ†’

Estimates how much two sets overlap, which HLL cannot do well.

Key-Value Databasesโ†’

Redis offers HyperLogLog as a built-in type.

Streaming Enginesโ†’

Where approximate distinct counts are often computed on live streams.

Checksumsโ†’

Hashing is the common tool behind both ideas.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: estimates the number of different items, in a few KB.
  • โœ”Add: hash, first p bits choose the register, store the max of (leading zeros + 1).
  • โœ”Estimate: ฮฑ ร— mยฒ / ฮฃ 2^(โˆ’register). Use linear counting when the set is small.
  • โœ”Error: about 1.04 / โˆšm. For p = 14 that is about 0.8%.
  • โœ”Duplicates: do nothing. It counts different items, not events.
  • โœ”Merge: maximum per register. Same p and same hash needed.
  • โœ”No: deleting, listing items, exact counts, or good intersections.
  • โœ”One line: โ€œThe longest run of zeros you have seen tells you how many you have probably seen.โ€
โ† Previous
Count-Min Sketch
Next โ†’
Merkle Trees