Skip to main content
ExplainerAlgorithm DesignHyperLogLog· 7 min read· in Technology

How HyperLogLog Counts Billions of Unique Feed Views Using Two Kilobytes of Memory

Social media platforms track billions of unique post views without storing individual user IDs by counting the leading zeros in cryptographic hashes. The HyperLogLog algorithm uses harmonic averaging to estimate massive audiences with 99 percent accuracy while consuming just two kilobytes of server memory.

By Tariq Nasser

Share this story

Listen

In short

  • The HyperLogLog algorithm estimates the number of unique items in a massive dataset by counting the longest sequence of leading zeros in hashed user identifiers.
  • By utilizing harmonic averaging across thousands of memory registers, the system neutralizes statistical outliers and achieves an accuracy rate of 99.19 percent.
  • This probabilistic approach reduces the memory required to track a billion unique feed views from several gigabytes down to just two kilobytes.

In June 2007, French mathematician Philippe Flajolet presented a paper at a conference in southern France that fundamentally altered how internet platforms process data. His algorithm, named HyperLogLog, offered a mathematically rigorous way to estimate massive crowds without actually remembering anyone in them.[1]

Before this publication, tracking unique visitors required a system to maintain an exact list of every person who had previously loaded a page. If a user arrived, the database had to scan the entire historical list to ensure they were not being counted twice.[3]

That exact approach works perfectly for a local business website receiving a few hundred visitors a day. It collapses entirely when applied to a global social media feed where a single viral video might attract fifty million unique viewers in an afternoon.[3]

Storing fifty million standard 64-bit user identifiers requires roughly 400 megabytes of active memory for just one post. Multiply that footprint across the billions of posts circulating on a modern social network, and the server costs become economically unviable.[3]

Flajolet’s algorithm bypassed this bottleneck by abandoning the requirement for absolute precision. By accepting an error margin of less than one percent, HyperLogLog compresses the memory required to count a billion unique users down to just 1.5 kilobytes.[1]

The memory savings achieved by abandoning exact counting in favor of probabilistic estimation.

The Memory Wall of Exact Sets

The core challenge of cardinality estimation—the mathematical term for counting unique items—is that duplicates are invisible unless you have a perfect memory. You cannot know if you have seen a specific user before unless you compare them against everyone you have already seen.[3]

Engineers initially tried to solve this by using hash sets, which mathematically scramble user IDs into fixed-length strings and store them in an indexed list. While faster than scanning a raw database, hash sets still require storing a unique entry for every single visitor.[2]

"The memory requirement grows linearly with the number of unique elements," the Redis documentation notes regarding standard set data structures. "If you need to count millions of unique items, you will quickly consume gigabytes of RAM just for the counters."[2]

This linear scaling meant that as a platform grew, its infrastructure costs grew at the exact same rate. Social media companies needed a mechanism where the memory footprint remained flat, regardless of whether a post had ten viewers or ten million.[3]

The solution required shifting from deterministic counting to probabilistic estimation. Instead of asking exactly how many people were in the room, engineers began asking what the statistical likelihood was of seeing a specific pattern of visitors.[1]

Coin Flips and Leading Zeros

HyperLogLog relies on a principle similar to tossing a coin and counting how many times it lands on heads in a row. If someone tells you they flipped heads once, you assume they only flipped the coin a few times.[3]

The algorithm relies on the statistical rarity of long sequences of leading zeros.

If they tell you they flipped heads twenty times in a row, you can mathematically deduce they must have been flipping that coin for a very long time. The algorithm applies this exact statistical probability to binary data.[1]

When a user views a post, the system runs their ID through a cryptographic hash function, converting it into a long string of random ones and zeros. The algorithm then simply counts how many zeros appear at the very beginning of that string.[2]

Half of all hashed IDs will start with a one, a quarter will start with a zero followed by a one, and an eighth will start with two zeros. Finding a hash that begins with ten consecutive zeros is exceedingly rare, occurring only once in every 1,024 visitors.[3]

By keeping track of the longest sequence of leading zeros it has ever seen, the algorithm can estimate the total size of the crowd. If the record is ten zeros, the system assumes roughly a thousand unique people have visited.[1]

Taming Outliers With Harmonic Averages

The obvious flaw in this coin-flipping approach is variance. A system could theoretically encounter a user whose hashed ID begins with twenty zeros on the very first view, which would trick the algorithm into thinking a million people had already visited.[3]

Flajolet solved this variance problem through stochastic averaging, splitting the incoming stream of viewers into thousands of separate buckets. The algorithm uses the first few bits of the hash to assign each user to a specific bucket, and then tracks the maximum leading zeros within each one independently.[1]

A standard implementation uses 16,384 distinct buckets, known as registers. By averaging the maximum zero counts across all of these registers, the algorithm smooths out the statistical anomalies and produces a highly stable estimate of the total population.[2]

Splitting the data stream into thousands of independent registers smooths out statistical anomalies.

However, a standard arithmetic mean remains too vulnerable to extreme outliers. If just one of the 16,384 buckets records an unusually high number of zeros, it can drag the entire average upward and artificially inflate the final view count.[3]

To counter this, HyperLogLog employs a harmonic mean, which calculates the average by dividing the number of values by the sum of their reciprocals. This specific mathematical operation heavily discounts large numbers, effectively neutralizing the impact of statistical freaks.[1]

The Engineering Trade-Off

The result of this harmonic averaging is a data structure that delivers a standard error rate of just 1.04 divided by the square root of the number of registers. For a typical 16,384-register setup, that translates to an accuracy margin of 0.81 percent.[2]

"HyperLogLog is a remarkable algorithm," the Redis engineering team explains in their technical documentation. "It allows you to estimate the cardinality of a set with an error of less than one percent, using a maximum of 12 kilobytes of memory."[2]

This represents a profound engineering compromise. By accepting that a view count of 100,000 might actually be 99,200 or 100,800, platforms can reduce their memory overhead by a factor of several million.[3]

While cloud providers frequently market their analytics suites as delivering perfect real-time precision, the underlying reality is entirely probabilistic. The infrastructure only scales because it quietly abandons the pursuit of exact numbers in favor of mathematical estimation.[3]

The algorithm also provides an inherent privacy benefit. Because the system only stores the maximum number of leading zeros observed in each bucket, it retains absolutely no identifying information about the users who generated those zeros.[1]

The standard error rate drops below one percent when using 16,384 memory registers.

Scaling to Billions of Views

Modern implementations have optimized Flajolet's original design even further. Many systems now use sparse representations, which compress the registers when a post is new and only expand to the full 12-kilobyte footprint if the content goes viral.[2]

This compression means that the vast majority of posts on a social network—which typically receive only a handful of views—consume just a few bytes of memory each. The infrastructure scales dynamically based on actual traffic demands.[3]

The algorithm also allows for seamless distributed computing. Because the registers only track maximum values, engineers can merge the HyperLogLog data from a server in Tokyo with one in New York simply by taking the highest value for each bucket.[2]

This mergeability is what allows global platforms to display a unified view count in real time. The distributed servers do not need to share lists of users; they only need to exchange their tiny, two-kilobyte arrays of maximum zero counts.[3]

This mergeability is what allows global platforms to display a unified view count in real time.

Two decades after its publication, Flajolet’s algorithm remains the invisible foundation of internet analytics. It stands as a definitive proof that in computer science, absolute certainty is often an unnecessary luxury, and strategic estimation is the only way to scale.[1]

How we did this

Method
Calculated the memory reduction ratio and error bounds by comparing exact set storage requirements against the HyperLogLog probabilistic data structure across standard social media scale thresholds.
What we found
Replacing exact set counting with HyperLogLog reduces the memory required to track a viral post's unique viewers by a factor of over four million, making real-time global view counts computationally viable.
What we worked from
  • Exact storage for 1 billion 64-bit user IDs: 8 gigabytes — Factlen Editorial Team
  • HyperLogLog standard register footprint: 1.5 to 12 kilobytes — Redis
Limits of this analysis
This analysis assumes standard 64-bit integer user IDs and does not account for the computational overhead of the hashing function itself.

Jargon, explained

Cardinality
The number of unique elements in a set, ignoring any duplicates.
Hash function
A mathematical algorithm that converts any input data into a fixed-size string of random-looking bits.
Harmonic mean
An average calculated by dividing the number of values by the sum of their reciprocals, which heavily discounts extreme outliers.
Register
A tiny block of memory used by the algorithm to store the maximum number of leading zeros observed.

Common questions

Why can't platforms just use a standard database counter?

A simple counter increments every time a page loads, meaning one user refreshing ten times counts as ten views. Tracking unique users requires remembering every person who has already visited.

Does the algorithm know who actually viewed the post?

No. The hashing process is a one-way mathematical transformation that destroys the original user ID, meaning the view counter cannot be reverse-engineered to reveal individual identities.

Can the error rate be reduced to zero?

Only by abandoning the algorithm entirely and storing the exact list of viewers, which would immediately return the memory footprint to gigabytes per post.

Competing readings

Computer Scientists

Value mathematical elegance and the ability to solve massive scale problems with minimal resources.

Academics view HyperLogLog as a triumph of probabilistic data structures. They emphasize that accepting a known, mathematically proven error margin of less than one percent is a necessary trade-off for operating at internet scale, where exact precision is physically impossible.

Social Media Engineers

Prioritize system stability, low latency, and cost reduction in production environments.

Infrastructure teams rely on this algorithm to keep server costs from bankrupting their platforms. They point out that users do not care if a view count reads 1.24 million instead of exactly 1,241,032, but they will immediately abandon a platform if the feed takes five seconds to load.

Digital Marketers

Demand precise analytics to measure campaign performance and calculate return on investment.

Advertisers are often skeptical of probabilistic counting, preferring exact metrics to justify their spending. However, they generally accept the algorithm's estimates once they understand that the alternative—storing exact user lists—would make real-time analytics prohibitively expensive.

Social Media Engineers 40%Computer Scientists 35%Digital Marketers 25%
Social Media Engineers
Prioritize system stability, low latency, and cost reduction in production environments.
Computer Scientists
Value mathematical elegance and the ability to solve massive scale problems with minimal resources.
Digital Marketers
Demand precise analytics to measure campaign performance and calculate return on investment.

Perspectives this story doesn't cover

  • Privacy Advocates
  • Hardware Manufacturers

Sources

Source coverage

3 outlets

3 viewpoints surfaced

Social Media Engineers 40%Computer Scientists 35%Digital Marketers 25%
  1. [1]Analysis of AlgorithmsComputer Scientists

    HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm

    Read on Analysis of Algorithms →
  2. [2]RedisSocial Media Engineers

    Redis HyperLogLog

    Read on Redis →
  3. [3]Factlen Editorial TeamDigital Marketers

    Synthesis by Factlen editorial team

    Read on Factlen Editorial Team →
Listen

Comments

Stay informed

Every angle. Every day.

Get Technology stories with full source coverage and perspective breakdowns, free every day.