Video in progress

Strong Middle 🏗️ System design

A site gets billions of views a day. How do you count the unique visitors of each page without blowing up memory?

Storing every user ID in a Set takes too much memory. HyperLogLog estimates the number of unique elements in about 12 KB of memory with ~0.8% error; Redis has it built in with PFADD/PFCOUNT, and you can merge different days with PFMERGE.

📖 Answer

For an exact count you need a set of unique userIds per page. For a popular page, 10 million unique visitors × 8 bytes = 80 MB, for just one page and one day. For a thousand pages, no Redis is big enough.

But the business needs "about 1.23 million", not "1,234,567". That's where probabilistic structures come in.

HyperLogLog idea: it estimates the size of the set from the maximum number of leading zeros in the elements' hashes. The Redis implementation takes at most ~12 KB per key and has a standard error of ~0.81%.

PFADD  uv:page:42:2026-11-03  user:1001 user:1002 user:1001
PFCOUNT uv:page:42:2026-11-03            -> 2
PFMERGE uv:page:42:week  uv:page:42:2026-11-01 uv:page:42:2026-11-02 uv:page:42:2026-11-03
PFCOUNT uv:page:42:week

The strength of PFMERGE is this: from the daily counts you get a weekly unique count, and if one person visits on two days, they aren't counted twice. You can't do that with plain counters.

When it doesn't fit:

  • you need an exact number (billing, payments, a game with prizes) — then use a real set or the DB;
  • the question "exactly who visited" — HLL doesn't store elements, it only gives the count.

At very large volumes, this is counted in a stream job that reads from Kafka (Flink and the like), and the result is written to an analytics database.