Real-Time Engagement Counters with Redis HyperLogLog

Architecture

Estimate unique visitors with Redis HyperLogLog. Learn PFADD, PFCOUNT, merges, rolling windows, error bounds, memory planning, and when exact counts matter.

TL;DR

  • Redis HyperLogLog estimates distinct-item cardinality using a compact probabilistic sketch. It is useful when approximate unique counts are enough and storing every identifier would be expensive.
  • Redis exposes the sketch through PFADD, PFCOUNT, and PFMERGE. A single sketch uses about 12 KB in its dense representation, though small sketches can use a sparse representation.
  • Redis documents a 0.81% standard error for its estimate. This is not a hard maximum error or a 95% confidence interval.
  • HyperLogLog cannot answer membership queries or delete one observed item. Use exact sets or a database when correctness for billing, authorization, deduplication, or legal records matters.
  • For time windows, store sketches by bucket and merge the buckets included in the window. Plan for merge cost, expiration, and Redis Cluster hash-slot rules.

When an exact unique count costs too much

Many product metrics ask how many distinct entities appeared in a period: unique visitors today, distinct search terms this week, active devices by region, or unique accounts that triggered a feature. An exact count requires retaining enough information to know whether each identifier has already appeared. A set is a straightforward solution, but its memory grows with the number of unique identifiers and the representation overhead.

HyperLogLog is a probabilistic data structure for estimating the cardinality of a set, meaning the number of distinct values. It compresses evidence about the identifiers rather than storing the identifiers themselves. Redis provides it as a native data structure with commands for adding identifiers, estimating a count, and merging sketches. Its memory use stays bounded as the observed set grows, which makes it useful for high-cardinality dashboards and aggregate analytics. Redis probabilistic data structures

The trade is deliberate uncertainty. A unique visitor card on an internal dashboard may tolerate an estimate. A subscription invoice, fraud decision, access-control rule, or financial settlement usually cannot. Choose the data structure based on what the number controls, not only on how much memory it saves.

How HyperLogLog estimates distinct values

At a high level, a HyperLogLog hashes each input, uses part of the hash to select a register, then uses a property of the remaining bits to record evidence about how many distinct inputs have appeared. Many registers combine to produce an estimate. Repeated values do not need to be retained as separate rows, and sketches built from different subsets can be merged to estimate the union.

The original analysis describes a one-pass cardinality estimator whose typical relative standard error is approximately 1.04 / √m, where m is the number of registers. Redis implements a tuned variant with a documented standard error of 0.81%. Redis uses a sparse encoding for small cardinalities and switches to a dense representation that occupies 12,288 bytes, plus the Redis key and object overhead. Flajolet et al., HyperLogLog analysis · Redis PFCOUNT reference and representation

“0.81% standard error” describes the estimator’s statistical behavior across inputs under its assumptions. It does not mean every estimate is guaranteed to be within 0.81% of the truth. It is not an absolute error value and not a stated 95% confidence interval. At a true count near one million, 0.81% corresponds to roughly 8,100 as one standard-error scale. If a product displays an estimate, label or document it as approximate and decide how much fluctuation is acceptable.

Hashes matter. Inputs should be canonicalized consistently before they reach the sketch. If one request adds user@example.com and another adds User@example.com, the sketch sees different byte strings unless the application normalizes them. Hashing or tokenizing identifiers upstream can reduce exposure of raw personal data, but deterministic pseudonyms can still be correlated and may remain sensitive. Use access controls, retention limits, and a deliberate privacy review.

Use Redis commands for a running unique-count sketch

The core commands are small. This example counts unique search queries in a day. The key includes a UTC date so the application can expire old buckets according to its retention policy.

PFADD metrics:searches:{tenant-42}:2026-11-20 query-hash-1
PFADD metrics:searches:{tenant-42}:2026-11-20 query-hash-2 query-hash-1
PFCOUNT metrics:searches:{tenant-42}:2026-11-20

PFADD returns 1 if at least one internal register changed, or 0 if none changed. It does not tell the caller whether a particular input was previously present. Do not use its return value as an exact duplicate detector. Redis documents the command’s constant-time complexity per added element. Redis PFADD reference

To estimate the union of two buckets without creating a materialized key, call PFCOUNT with multiple keys. To persist a merged sketch, use PFMERGE. A destination supplied to PFMERGE is included in the merge if it already exists, so delete or choose a fresh destination when rebuilding a rollup that should contain only its stated source buckets. Redis PFMERGE reference

PFCOUNT metrics:searches:{tenant-42}:2026-11-19 metrics:searches:{tenant-42}:2026-11-20
PFMERGE metrics:searches:{tenant-42}:week:2026-11-20 metrics:searches:{tenant-42}:2026-11-14 metrics:searches:{tenant-42}:2026-11-15 metrics:searches:{tenant-42}:2026-11-16 metrics:searches:{tenant-42}:2026-11-17 metrics:searches:{tenant-42}:2026-11-18 metrics:searches:{tenant-42}:2026-11-19 metrics:searches:{tenant-42}:2026-11-20

A merge estimates the union, not the sum of bucket estimates. Summing daily unique counts double-counts a person who appeared on several days. Merging the sketches estimates the unique set across those days. If you need several overlapping windows, preserve source buckets and calculate only the unions requested by the product.

Multi-key commands in Redis Cluster have slot requirements that vary by command and deployment. Related keys can use a shared hash tag such as {tenant-42} to map them to the same slot, but that also concentrates those operations on one shard. Design the key pattern and read the provider’s cluster behavior before depending on multi-key union commands. Redis multi-key and cluster behavior

Design time buckets and rolling windows carefully

For calendar-aligned reports, a daily sketch is simple. Add every canonical user ID to that day’s sketch, set a retention time that exceeds the latest reporting and correction window, and query daily counts. For a seven-day rolling unique count, merge the seven daily sketches. The estimate reflects distinct values across those buckets rather than adding each day’s count.

HyperLogLog is mergeable, but it is not subtractable. If you build a weekly sketch and then want to remove yesterday’s bucket to advance the rolling window, the aggregate sketch cannot remove only yesterday’s observations. Recompute the union from the remaining source buckets, or maintain a hierarchy of independently rebuildable time segments. Do not make an overwritten weekly sketch your only copy if the product later needs different windows.

Choose bucket duration to balance update fan-out and query work. Minute buckets allow fine-grained windows but create many keys and make unions more expensive. Daily buckets are efficient for calendar reports but cannot precisely answer an arbitrary 15-minute window. Hourly buckets can be a practical middle ground, provided query latency and shard placement are measured.

Keep time boundaries unambiguous. Use UTC bucket identifiers or explicitly encode the reporting timezone and daylight-saving policy. A local day may contain 23 or 25 hours. Late-arriving events require a policy for reopening a bucket, extending its TTL, or updating a correction store. If data comes from a delayed stream, expire the sketch after the maximum lateness window plus the reporting and audit retention period.

For a large union across many buckets, avoid repeatedly issuing a multi-key PFCOUNT on every dashboard refresh without measuring. Redis notes that multi-key count builds a temporary merged sketch and is more expensive than reading one key. A scheduled rollup can reduce query work, but it needs a rebuild strategy, distinct inputs, and a way to regenerate after a late event. Redis PFCOUNT complexity notes

Choose the identifier that matches the metric

“Unique visitor” is a product definition, not a database field. A logged-in account, browser cookie, device ID, search string, IP address, and session can all yield different counts. Decide whether an anonymous visitor should merge with a later authenticated account, whether bots count, and whether a user who clears cookies becomes a new identifier. Publish the definition beside the metric so teams do not compare incompatible numbers.

Normalize before adding. Version your normalization rule, such as lowercasing a case-insensitive query or converting a canonical account UUID to a stable byte representation. If the normalization changes, do not silently mix old and new IDs in a bucket. Start a new metric version or reprocess authoritative raw events if exact historical comparability is required.

Scope the sketch by tenant and metric. A single global sketch answers a global count. It cannot later reveal which tenant supplied the values or filter out a tenant. If you need per-tenant counts, write separate sketches and plan their cardinality and memory. Keep a key budget: the 12 KB dense size applies per sketch, so millions of tiny buckets can still be costly even when each individual sketch is compact.

If the identifiers are sensitive, avoid writing raw email addresses, phone numbers, or access tokens as elements. A keyed HMAC can make values less directly readable while preserving stable equality within the chosen scope. Protect and rotate the secret carefully. A new HMAC key changes every identifier, so rotation requires a new sketch version or a controlled migration. A deterministic pseudonym still permits linking repeated activity and should be treated as sensitive data.

Know when approximate counts are the wrong primitive

Use an exact set, relational table with a uniqueness constraint, or another exact index when the application must answer whether one person was already counted, list the distinct members, remove an individual member, or produce an exact result. HyperLogLog cannot return the observed values, prove that a particular ID exists, or delete one ID after it has been added.

Do not use it as the only source for billing, entitlements, fraud enforcement, quota rejection, or a regulatory record. Even if a small error seems unlikely to change a threshold today, cardinality estimates may vary around a boundary and cannot support per-entity reconciliation. Store the authoritative events or exact ledger separately, and derive approximate dashboards from them.

For analytics where estimates are acceptable, set a tolerance based on decisions users make with the chart. A high-level trend may tolerate more error than a customer-facing report that is reconciled to an invoice. Compare sampled HyperLogLog estimates against an exact distinct count over representative data, stratified by count size, tenant, time bucket, and identifier distribution. That validation reveals data normalization errors as well as estimator variation.

Redis’s PFCOUNT is a count operation, not an authorization-safe membership check. Do not use it to determine whether an account, token, or user is allowed to perform an action. Enforce access using exact policy and database checks, as discussed in our permission-aware retrieval guide.

Control memory, expiry, and query cost

Estimate memory from the number of active bucket keys, not only from the number of unique users. A dense sketch is roughly 12 KB before key and Redis object overhead. Sparse sketches can be smaller for low cardinality. Thousands of tenants times hourly buckets can grow into a significant allocation even though each counter is described as “constant space.” Multiply the number of simultaneous sketches by a measured size distribution and include replication and allocator headroom.

Use explicit expiration only after the business retention window. If a daily sketch expires at midnight, a report opened one minute later may lose its source. Set TTL based on how far back users can query, how late source events arrive, and how long rollups may need rebuilding. Remember that an expired source cannot recreate a materialized union.

Monitor sketch key count, memory, expirations, failed writes, per-bucket update rate, union query latency, rollup lag, and correction volume. Keep labels bounded. A metric label with arbitrary user ID can create a separate observability cardinality problem, even when the counter itself uses HyperLogLog.

For multi-key union queries in a clustered environment, test the exact Redis topology. Hash tags can force related keys to the same slot, but may make a hot key range reside on one shard. Alternatively, read sketches from appropriate shards and merge in an application library only if formats and implementation compatibility are guaranteed. Redis recommends using its own merge commands for Redis structures and notes that multi-key command behavior varies across cluster configurations. Redis cluster multi-key operations

Validate the metric before exposing it

Create a test dataset with known duplicates and expected exact cardinalities. Include empty input, one value, repeated values, overlapping buckets, disjoint buckets, late arrivals, normalized case variants, and high-cardinality identifiers. Compare approximate estimates with an exact set built from the same canonical byte strings. Test estimate error across several cardinality ranges rather than asserting every run falls inside the published standard error.

Test the Redis behavior as an operational system too. Rebuild a merged rollup into a clean destination and confirm stale destination data is not included. Test expiry while a rollup is scheduled. Exercise cluster slot errors for cross-key count or merge. Simulate Redis failover and restore under the configured persistence. Verify the dashboard labels an estimate and does not imply that a count is exact.

Keep the data path simple. The request handler can enqueue an analytics event or append it to a durable stream, and a consumer can update the appropriate sketch. Make the update idempotent at the event level where redelivery is possible, though applying the same identifier to a sketch naturally leaves its estimated set unchanged. Preserve a separate event ID or inbox if downstream side effects must be deduplicated. See our event-backbone sizing guide for retention and consumer recovery tradeoffs.

Frequently asked questions

Is Redis HyperLogLog accurate to within 0.81% every time?

No. Redis documents 0.81% as the standard error of its estimator, not a maximum error or a 95% confidence interval. Treat the result as approximate, validate it against representative exact samples, and do not use it for decisions that require a guaranteed exact count.

Can I use HyperLogLog to check whether one user was already counted?

No. HyperLogLog estimates the number of distinct values but does not support membership queries or return the identifiers it has seen. Use an exact set or a database uniqueness constraint when the application must answer whether a specific user exists.

Can I remove one item from a Redis HyperLogLog?

No. HyperLogLog supports additions and unions, not removal of an individual observation. Keep source buckets and rebuild a time-window union from the remaining buckets, or use an exact structure if deletion is part of the requirement.

Can I add daily unique counts to get weekly unique visitors?

No. The same visitor can appear on multiple days, so summing daily estimates double-counts them. Merge the daily sketches and count the estimated union, or use an exact event set if an exact weekly answer is required.

Use approximate cardinality where the product can tolerate it

Redis HyperLogLog is a useful fit for bounded-memory unique-count metrics when approximate cardinality is enough. Build one sketch per well-defined metric and time bucket, normalize identifiers consistently, and merge sketches to estimate unions. Measure total key memory and multi-key query cost as the number of tenants and buckets grows.

Keep exact business records for billing, authorization, and decisions that require per-user evidence. Validate the estimate against exact samples and communicate its uncertainty to dashboard users. If you are choosing an analytics counter or designing a high-cardinality metrics pipeline, talk with our engineering team about sketch design, retention, and data-quality checks.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with web applications

Discuss your project