Video in progress

Strong Middle ⚡ Redis and caching

How do you count how many unique users visited a page per day in Redis, and why HyperLogLog and not a Set?

You add each visiting user with PFADD, and PFCOUNT gives the approximate unique count. A HyperLogLog takes at most about 12 KB per key with an error of about 0.81%, while a Set eats hundreds of MB for millions of IDs.

📖 Answer

A Set works too: SADD visitors:2026-11-03 user:42, then SCARD. The problem is size: 10 million unique IDs per day is several hundred MB for a single day. If you keep a year of them, do the math.

A HyperLogLog doesn't store an exact list, only a probabilistic "trace":

PFADD visitors:2026-11-03 user:42 user:77
PFCOUNT visitors:2026-11-03                     # ~ the unique count
PFMERGE visitors:2026-w45 visitors:2026-11-03 visitors:2026-11-04
PFCOUNT visitors:2026-11-03 visitors:2026-11-04 # both days together, without duplicates

In Spring:

redis.opsForHyperLogLog().add("visitors:" + LocalDate.now(), "user:" + userId);
Long unique = redis.opsForHyperLogLog().size("visitors:" + LocalDate.now());

You get weekly and monthly counts by merging the daily keys; there's no need to recount each one.

Limitations:

  • the result is approximate. Getting 1,008,000 instead of 1,000,000 is normal. It's enough for a report or a dashboard, not for billing;
  • you can't see the members inside (it can't answer "who visited?");
  • you can't remove a member.

If you need an exact count or a list, use a Set or a Bitmap (if the IDs are sequential numbers), otherwise a HyperLogLog.