Sub topic 11
Using HyperLogLog in practice with Redis
This chapter assumes you know how a HyperLogLog sketch works: registers, rank, harmonic mean, and merge by register-wise maximum. It also assumes you can run redis-cli and basic Python. Here you use the sketch through Redis instead of writing it yourself.
What Redis gives you
Redis ships a production HyperLogLog behind three commands:
| Command | Purpose |
|---|---|
| `PFADD key item [item ...]` | Add items to the sketch at `key`. Creates the key if needed. |
| `PFCOUNT key [key ...]` | Estimate the distinct count. With several keys, estimate the union. |
| `PFMERGE dest source [source ...]` | Store the union of the sources in `dest`. |
The prefix PF honors Philippe Flajolet, who co-invented the algorithm.
The Redis implementation fixes the parameters for you. It uses 16,384 registers (precision p = 14) with 6 bits each. A dense sketch takes at most about 12 KB, and the standard error is about 0.81%, from 1.04 / sqrt(16384). Small sketches start in a compact sparse encoding and switch to the dense layout as they grow. This is the sparse idea from HyperLogLog++.
A first session
redis-cli PFADD visitors:monday alice bob carol
redis-cli PFADD visitors:tuesday bob dave
redis-cli PFCOUNT visitors:monday
redis-cli PFCOUNT visitors:monday visitors:tuesday
redis-cli PFMERGE visitors:week visitors:monday visitors:tuesday
redis-cli PFCOUNT visitors:weekYou should see 3 for Monday, 4 for the union of both days, and 4 for the merged key. Bob is counted once. At this size the estimates are normally exact, because small-range correction and the sparse encoding keep them accurate.
PFADD returns 1 if the add changed the sketch's registers and 0 if it did not. Treat that as a hint, not a way to test "is this item new". A 0 does not prove the item was seen before.
Daily and weekly unique visitors
A common pattern is one sketch per time bucket. You add events to the current bucket and combine buckets at query time.
import redis
r = redis.Redis(decode_responses=True)
def record_visit(day: str, user_id: str) -> None:
key = f"visitors:{day}"
r.pfadd(key, user_id)
r.expire(key, 60 * 60 * 24 * 35) # keep about five weeks
def unique_visitors(days: list[str]) -> int:
keys = [f"visitors:{d}" for d in days]
return r.pfcount(*keys) # estimate of the union
record_visit("2026-12-01", "alice")
record_visit("2026-12-01", "bob")
record_visit("2026-12-02", "bob")
print(unique_visitors(["2026-12-01", "2026-12-02"])) # 2PFCOUNT or PFMERGE?
Both give the union estimate. Choose by what you do next.
- Use
PFCOUNT a b cfor a one-off question. Redis merges the sketches in memory and stores nothing. It does more work than a single-key count, so avoid it in hot paths. - Use
PFMERGEwhen you will query the same union repeatedly, such as a weekly total. A single-keyPFCOUNTis fast because Redis caches the last estimate inside the key. - Merging is lossless relative to the sketches. The union of two sketches has the same accuracy as one sketch that saw every item.
Operational notes
- Memory is predictable. Each key costs at most about 12 KB, whether it holds a thousand items or a billion. A million daily keys is therefore a real cost, so decide on key granularity deliberately.
- Accuracy is fixed. You cannot pick a different precision. If you need a lower error than about 0.81%, Redis HyperLogLog is the wrong tool.
- Inputs are bytes.
"42"and"042"are different items. Normalize identifiers (case, whitespace) before callingPFADD. - Expire old buckets. Use
EXPIREso retired sketches do not accumulate. - Replication and persistence work as for any string key. Sketches survive restarts with RDB or AOF and replicate to replicas.
Exercise
You keep one HyperLogLog per day in keys such as visitors:2026-12-01. A dashboard shows unique visitors for the last 30 days and is refreshed every second by many users. Which command pattern would you use, and why? Also, if each day has 5 million distinct visitors, roughly how much memory do the 30 sketches use?
Show answer
Run PFMERGE into a rolling key (for example visitors:last30) on a schedule, such as once a minute, and have the dashboard run a single-key PFCOUNT on it. A single-key PFCOUNT is cheap and uses the cached estimate. A multi-key PFCOUNT on 30 keys would merge 30 sketches on every refresh. Memory is bounded by about 12 KB per dense sketch, so 30 sketches use roughly 360 KB, plus the merged key, regardless of the 5 million visitors per day.