Consumer Engagement Metrics Pipeline for DAU and MAU
Medium · System Design · Software Engineer · Onsite
Prompt
Architect an analytics pipeline and query layer that calculates and serves Daily Active Users (DAU) and Monthly Active Users (MAU) for a consumer product operating at massive scale across web browsers and mobile apps.
Count a user as active within a given window whenever they trigger at least one intentional foreground interaction—such as launching the app, viewing a screen or web page, signing in, or initiating a session—during that interval.
Your architecture needs to specify:
- Exact metric semantics: DAU measures distinct active users within a single calendar day. For MAU, pick one primary window—either a calendar month or a trailing 30-day period—defend that choice, and contrast its trade-offs against the alternative.
- Telemetry collection and schema: Ingest client activity from web and mobile applications, detailing the required fields on each event payload.
- Deduplication and user identity: Prevent retried deliveries from inflating counts, and define how a canonical user identifier reconciles
user_id,device_id/anonymous_id, and unauthenticated sessions. - Temporal accuracy and recomputation: Handle time-zone day cutoffs, delayed offline uploads, out-of-order arrivals, and historical backfills or rule revisions.
- High-scale compute and state: Justify where you use real-time streaming versus batch jobs, and where you rely on exact distinct sets versus probabilistic sketches.
- Dashboard and slice serving: Power low-latency intraday views for leadership and product teams alongside historical breakdowns sliced across date windows, client
platform, releaseapp_version, andcountry, covering caching, response times, and provisional-versus-final guarantees. - Reliability, quality gates, and privacy: Cover anomaly alerting, cross-pipeline reconciliation, fault recovery, PII scrubbing, and data-retention limits.
Scope & Expectations
- Crisp metric, identity, and time-boundary definitions that explain how logged-out visitors, multi-device accounts, and rolling-versus-calendar windows behave.
- Back-of-the-envelope traffic and storage sizing that motivates your ingestion log, streaming aggregator, batch truth pipeline, and cardinality data structures.
- Concrete handling of mobile clock skew, multi-day offline event delays, idempotent retries, and definition backfills without corrupting finalized historical reports.
- A fast serving design with clear freshness/finality badges, automated data-quality checks before publishing numbers, and privacy-safe retention and deletion controls.
Step-by-step walkthrough
Clarify requirements and define DAU and MAU
At first glance, counting Daily Active Users (DAU) and Monthly Active Users (MAU) looks like a single
COUNT(DISTINCT user_id)query. At consumer scale, however, events arrive duplicated from mobile retries, delayed by hours from offline phones, split across logged-out and logged-in states, and spread across 24 time zones. Pinning down crisp definitions comes first because every storage and pipeline decision follows from them.Metric definitions
- Qualifying event: A deliberate foreground action initiated by the user—
app_open,screen_view,page_view,login, orsession_start. Background system telemetry (push_received, silent background refresh, crash uploads) does not qualify; otherwise an unopened phone receiving a push notification in someone's pocket gets counted as active. - Active user: A distinct canonical user key (defined in Deep Dive 1) with at least one qualifying event in the target window.
- DAU(d): Exact distinct active users on calendar day
dusing UTC day boundaries (00:00:00to23:59:59.999 UTC), plus a separate per-country local-day view for regional product teams. - Primary MAU(d) — Rolling 30-day window (
[d - 29, d]): Exact distinct users active on at least one day in the 30-day window ending on dayd. We also publish calendar-month MAU from the exact same daily user sets for quarterly finance reporting.
Criterion Rolling 30-Day MAU (Chosen Primary) Calendar-Month MAU (Secondary) ----------------------------------------------------------------------------------------------------- Cadence Available every single day Final only after month-end Window length consistency Always 30 days Varies 28-31 days (Feb looks ~10% lower than Jan/Mar artificially!) Stickiness ratio (DAU / MAU) Apples-to-apples on any date d Mismatched until last day of month Weekday composition 4 full weeks + 2 extra weekdays Varies by calendar month Financial / board reporting Unnatural ("30d ending Oct 17") Standard ("October MAU")(Note: Teams sensitive to the mild 2-day weekday wobble of a 30-day window often add WAU (7-day) and 28-day active users—exact 4-week multiples—computed identically.)
Non-functional targets
- Freshness vs. finality: Intraday DAU updates within 2 minutes labeled
provisional (approx). Historical days recompute nightly across a full 72-hour late-event grace window, then lock asfinal (exact). - Query latency: Dashboard loads under p95 <= 500 ms.
- Privacy: Zero raw PII (personally identifiable information, such as emails or raw IP addresses) in analytics tables; strict opt-out filtering and bounded retention.
- Qualifying event: A deliberate foreground action initiated by the user—
Estimate scale with back-of-the-envelope math
Assume a large consumer app with 100M daily active logged-in accounts, 60M daily active logged-out devices (
160Mtotal daily identifiers), 300M rolling 30-day MAU, and 1.5B distinct identifiers seen over 13 months:- Ingestion rate:
160M daily keys × 50 raw events/day (all telemetry) = 8B events/day. Dividing by86,400 s/daygives~93,000 events/saverage and ~280,000 events/s at 3× peak (~280 MB/sat1 KBJSON/event). Raw volume is~8 TB/dayuncompressed, or ~1 TB/day in compressed Parquet (a column-oriented file format). - Compact daily user summary (
user_day_activity): Collapsing 50 daily events per user down to one row per(key, utc_date, local_date, platform, country, app_version)yields~250M rows/day × 60 B ≈ 15 GB/day(~450 GBfor 30 days)—over 60× smaller than raw events! - Exact sets via Roaring Bitmaps: Mapping
1.5Bkeys to sequential 32-bit unsigned integers (0 .. 4.29B) lets us represent one day's active users as a Roaring Bitmap—a compressed bit-array where biti = 1means integer IDiwas active. Even uncompressed,1.5B bits = 187.5 MB/day; bitwiseOR-ing 30 daily bitmaps (<= 5.6 GB) computes exact 30-day MAU in a few seconds! - Live & ad-hoc slices via HyperLogLog (HLL): An HLL sketch is a fixed-size probabilistic counter (
2^14 = 16,384small registers taking12–16 KB) that estimates distinct counts with a relative standard error of1.04 / sqrt(16,384) = 0.81%. Across(3 platforms + ALL) × (200 countries + ALL) × (30 live app versions + ALL), there are at most4 × 201 × 31 = 24,924cube cells (~10,000non-empty in practice) ×16 KB≈ 160 MB/day (<= 400 MB/dayworst case).
Workload Naive Raw Scan Pre-Aggregated Design ---------------------------------------------------------------------------------------------------- Official exact DAU / MAU30 Scan 30 TB Parquet Bitwise OR of 30 Roaring Bitmaps (~seconds) Intraday live DAU Impossible at 280k/s Stream into hourly HLL sketches (~16 KB/cell) Ad-hoc 30d slice (iOS+DE+v8.2) Minutes per click Merge 30 pre-built HLL sketches (< 20 ms)- Ingestion rate:
Specify the event schema, ingestion API, and storage tables
Required client + collector event fields
Field Example Purpose ---------------------------------------------------------------------------------------------------- event_id "f47ac10b-58cc-..." (UUIDv4) Generated once on device; reused across retries event_name "app_open" Checked against qualifying-event allowlist client_ts 2026-11-26T23:58:10.120Z Device clock when action occurred client_sent_ts 2026-11-27T01:40:00.000Z Device clock at upload batch send (measures skew!) server_received_ts 2026-11-27T01:40:01.050Z Stamped by collector (never trusted from client) user_id "u_8812" or null Internal pseudonymous account ID when logged in anonymous_id HMAC(install_id or cookie_id) Device/browser ID; keyed-hashed at collector platform "ios" | "android" | "web" Slice dimension app_version "8.2.0" Slice dimension tz_offset_minutes -480 Computes user's local_date alongside UTC date country "US" Resolved from IP at collector; raw IP immediately dropped! seq 419 Per-install counter to detect dropped SDK packets consent_analytics true False events are dropped immediately at edgeIngestion endpoint: Clients upload gzipped batches (
<= 100events or500 KB) toPOST /v1/events:batch. Mobile SDKs persist unsent batches in an on-disk SQLite/file queue and retry with exponential backoff when offline. Stateless collectors validate schemas, dropconsent_analytics == false, map IP ->countryand discard the IP, write to Kafka, and return202 Accepted(listing any malformed indices so the SDK drops bad payloads instead of retrying forever).Storage data model
raw_events S3 Parquet partitioned by received_hour (retained 90 days) dense_id_map canonical_key -> uint32 dense_id (append-only lookup; enables Roaring Bitmaps) device_login_links (anonymous_id, utc_date) -> single user_id if exactly 1 account logged in that day user_day_activity (utc_date, local_date, canonical_key, dense_id, platform, country, app_version) + qualifying_count + map<event_name, count> (partitioned by utc_date; 25 months) daily_bitmaps (utc_date, dim_type, dim_val) -> RoaringBitmap of uint32 dense_ids daily_sketches (utc_date, platform_or_all, country_or_all, version_or_all) -> 16 KB HLL sketch realtime_sketches (utc_hour, platform_or_all, country_or_all, version_or_all) -> 16 KB HLL sketch metric_daily (metric, def_ver, date, platform, country, app_version) -> value, method, status ('provisional'|'final'|'restated'), data_versionNotice why
local_dateis part ofuser_day_activity's primary key grain: for a user in Vancouver (UTC-8), one UTC day (Oct 14 00:00–23:59 UTC) spansOct 13 16:00–23:59local andOct 14 00:00–15:59local—two different local dates!Connect the streaming and batch architecture
Web & Mobile SDKs (gzip batches, persistent offline queue, UUIDv4 event_id) | v [ Stateless Edge Collectors: Consent filter, GeoIP -> drop IP, stamp ts ] | v [ Kafka: raw_events (256 partitions by anonymous_id, 7-day retention) ] | \ v v [ Speed Path: Apache Flink ] [ S3 Sink: raw_events Parquet ] - qualifying allowlist | - clock-skew fix v - u:<user_id> or d:<anon_id> [ Truth Path: Nightly Spark DAG (02:00 UTC) ] - updates hourly HLL cube cells - recomputes last 4 UTC days (T-1 .. T-4) | - event_id dedupe + same-day stitching v - writes user_day_activity & daily_bitmaps [ OLAP: realtime_sketches ] - computes exact DAU, MAU30, MAU_month | - stages -> runs quality gates -> swaps! | | +--------------------+-----------------------+ v [ OLAP Serving Store: metric_daily + daily_sketches ] | [ Metrics Query Service + Redis Cache ] | Product, Regional & Executive DashboardsBoth pipelines share one metric specification, but divide work cleanly: Flink delivers sub-2-minute
provisionalHLL estimates for today, while Spark delivers exact, stitched, deduplicated numbers that seamlessly supersede the streaming estimates as soon as each nightly batch passes data-quality gates.Deep dive 1: De-duplication and canonical user identity
Why duplicates don't break DAU/MAU in streaming: Network timeouts cause mobile SDKs to resend batches with the same
event_id. Fortunately, DAU and MAU measure set cardinality (the number of distinct elements in a set), and set union is naturally idempotent: adding"u:8812"twice yields{ "u:8812" }, size1. That means Flink does not need a> 100 GBstreaming state table of 8 billionevent_ids just to count live DAU! In the nightly Spark job, we deduplicate byevent_idacross the 4-day window soqualifying_countand per-event-type breakdowns inuser_day_activityare also 100% exact.Canonical user identity across logged-in and logged-out traffic: 1. Separate headline users from anonymous devices: Headline
DAU/MAUcountsu:<user_id>(authenticated accounts). Logged-out activity (d:<anonymous_id>) is published as a separateDAU_anonymousmetric (plus an optionalDAU_total_identifiersupper bound). Mixing raw cookie IDs into headline DAU overcounts single humans who clear Safari cookies or use both a phone and a laptop. 2. Same-day single-owner stitching (without shared-device corruption or history drift): Suppose Maya opens the app logged out at08:30(anonymous_id = anon_9c) and signs in asu_731at08:32on the same UTC dayd. Linking(anon_9c, d) -> u_731attributes her08:30event tou:u_731, avoiding double-counting her as bothu:u_731andd:anon_9cin total identifiers (and properly counting her if her only logged-in event that day was a non-qualifying background sync). Two guardrails keep stitching clean: - Shared devices (>= 2distinctuser_ids on dayd): Do not guess which family member tapped the screen while logged out; leave logged-out events asd:<anonymous_id>. - No cross-day retroactive rewriting: Logging in on October 25 never mutates finalized DAU from September.def map_single_owner_devices(day_events): """Map (anonymous_id, utc_date) -> user_id when exactly one account used that device.""" users_per_device_day = {} for event in day_events: user_id = event.get("user_id") if user_id is not None: device_day = (event["anonymous_id"], event["utc_date"]) users_per_device_day.setdefault(device_day, set()).add(user_id) single_owners = {} for device_day, distinct_users in users_per_device_day.items(): # Shared family tablets (len >= 2) are intentionally excluded. if len(distinct_users) == 1: single_owners[device_day] = next(iter(distinct_users)) return single_owners def resolve_canonical_key(event, single_owners): """Return 'u:<user_id>' for known users or 'd:<anonymous_id>' for unlinked devices.""" if event.get("user_id") is not None: return "u:" + event["user_id"] stitched_user = single_owners.get((event["anonymous_id"], event["utc_date"])) if stitched_user is not None: return "u:" + stitched_user return "d:" + event["anonymous_id"]Deep dive 2: Clock skew, time zones, late events, and backfills
Correcting broken client clocks and airplane delays: Neither raw
client_ts(a phone with a misconfigured clock set to 2021!) norserver_received_ts(an offline flight event uploaded the next morning!) is reliable by itself. Because every batch carriesclient_sent_tsstamped by the same device clock right when uploaded, their difference measures the device's clock offset (ignoring ~1 second of network transit):clock_skew = server_received_ts - client_sent_ts corrected_event_ts = min(client_ts + clock_skew, server_received_ts) # clamp future timestamps # Example: offline flight tap at client_ts = Oct 14 23:45, uploaded 2h later at Oct 15 01:45: # client_sent_ts = Oct 15 01:45, server_received_ts = Oct 15 01:45 -> clock_skew = 0 # corrected_event_ts = Oct 14 23:45 UTC -> lands accurately on Oct 14, NOT Oct 15!Events with
corrected_event_ts < server_received_ts - 30 daysare routed to a quarantine table and counted in SDK health metrics rather than polluting historical partitions.Time zones: Global DAU uses UTC so every day is an exact 24 hours with zero daylight-saving jumps. Regional teams query
local_date = date(corrected_event_ts + tz_offset_minutes)stored inuser_day_activity; dashboards never mix UTC and local series on the same chart.Exact 72-hour late-event finality lifecycle: Suppose ~99.5% of offline mobile events arrive within 24 hours and ~99.95% arrive within 72 hours (3 full days). Distinguish carefully between activity day
dand the wall-clock morningTwhen the nightly Spark job runs at02:00 UTC: - Activity daydfinishes atd + 100:00 UTC. - Atd + 102:00 UTC, an event from23:59 UTCon daydhas had only 2 hours to arrive; atd + 202:00 UTC, 26 hours; atd + 302:00 UTC, 50 hours; and atd + 402:00 UTC, 74 hours (> 72 hours for every minute of dayd)! - Therefore, each night on dateTat02:00 UTC, Spark recomputes the 4 UTC daysT - 1, T - 2, T - 3, T - 4, refreshesMAU30forT - 4 .. T - 1, and marks dayT - 4(andMAU30(T - 4))final:Timeline for Activity Day d = Oct 14: Oct 14 00:00 - 23:59 UTC : Flink updates hourly HLL -> status = provisional, method = approx Oct 15 02:00 UTC (d + 1) : Spark run #1 (2h min grace) -> status = provisional, method = exact Oct 16 02:00 UTC (d + 2) : Spark run #2 (26h min grace) -> status = provisional, method = exact Oct 17 02:00 UTC (d + 3) : Spark run #3 (50h min grace) -> status = provisional, method = exact Oct 18 02:00 UTC (d + 4) : Spark run #4 (74h min grace) -> LOCKED: status = final, method = exact! After Oct 18 02:00 UTC : Ultra-late events logged to late_events; restate (bumping data_version) only if monthly audit shows > 0.1% impact on any finalized day.Unordered arrivals and metric-definition backfills: Set union is commutative (
A ∪ B == B ∪ A), so unordered arrival within the window never alters DAU or MAU. When product changes a metric rule (for instance, removingloginfrom qualifying events), createdefinition_version = 2, recompute daily bitmaps directly fromuser_day_activity's per-event-name map (up to 25 months back without touching raw logs!), publishv1andv2side by side, and annotate the dashboard cutover.Deep dive 3: Exact Roaring Bitmaps vs. approximate HyperLogLog
Exact path (Roaring Bitmaps +
user_day_activity): - LetS_dbe the Roaring Bitmap of 32-bitdense_ids active on UTC dayd. ThenDAU(d) = |S_d|,MAU30(d) = |S_{d-29} ∪ ... ∪ S_d|, and single-dimension MAUs (country = 'DE') union 30 daily country bitmaps in seconds with zero approximation error. - Subtle multi-dimension trap: Do not computeDAU(d, platform='ios', country='DE')by intersectingS_{d, ios} ∩ S_{d, DE}! A traveler who used Android in Germany in the morning and iOS in France in the evening belongs to both single-dimension bitmaps, even though they never used iOS in Germany! Exact multi-dimension combinations come directly fromCOUNT(DISTINCT dense_id)overuser_day_activity(precomputed nightly for top dashboard views).Approximate path (HyperLogLog sketches for real-time and arbitrary slices): How can
16 KBestimate300,000,000distinct users within0.81%? Think of flipping a fair coin: seeing a streak of10heads in a row (0000000001in binary,9leading zeros before the first1) happens only1 / 1,024of the time, suggesting roughly~1,024distinct coin-flip sequences occurred. HLL hashes each user key uniformly into 64 bits, uses the topP = 14bits to divide keys acrossM = 16,384independent sub-buckets (averaging out luck!), and stores the maximumleading_zeros + 1(rank) seen in each bucket's remaining50bits:import hashlib import math P = 14 NUM_REGISTERS = 1 << P # 16,384 registers (~12-16 KB per sketch) REMAINING_BITS = 64 - P # 50 bits used to count leading zeros def create_hll_sketch(): return [0] * NUM_REGISTERS def hll_add(sketch, canonical_key): """Hash canonical_key to 64 bits and update one register's max rank.""" digest = hashlib.blake2b(canonical_key.encode("utf-8"), digest_size=8).digest() hash64 = int.from_bytes(digest, "big") # Top 14 bits select register index in [0, 16383]. reg_idx = hash64 >> REMAINING_BITS # Bottom 50 bits determine position of first 1-bit (1..51). low_bits = hash64 & ((1 << REMAINING_BITS) - 1) leading_zeros = REMAINING_BITS - low_bits.bit_length() rank = leading_zeros + 1 if rank > sketch[reg_idx]: sketch[reg_idx] = rank def hll_merge(sketch_a, sketch_b): """Exact sketch of (A union B): element-wise max across all 16,384 registers.""" merged = [0] * NUM_REGISTERS for idx in range(NUM_REGISTERS): merged[idx] = max(sketch_a[idx], sketch_b[idx]) return merged def hll_estimate(sketch): """Harmonic-mean cardinality estimator with small-range linear-counting correction.""" alpha_m = 0.7213 / (1.0 + 1.079 / NUM_REGISTERS) harmonic_denom = 0.0 zero_registers = 0 for rank in sketch: harmonic_denom += 2.0 ** (-rank) if rank == 0: zero_registers += 1 raw_estimate = alpha_m * (NUM_REGISTERS ** 2) / harmonic_denom # When many registers are still 0, coupon-collector (linear counting) is sharper. if raw_estimate <= 2.5 * NUM_REGISTERS and zero_registers > 0: return NUM_REGISTERS * math.log(NUM_REGISTERS / zero_registers) return raw_estimate(Production deployments use a standard HLL++ library that adds empirical bias tables for medium counts and sparse lists for tiny cells.) Crucially,
hll_mergeis a lossless register-wisemax: merging 24 hourly sketches gives the exact daily sketch, and merging 30 daily(ios, DE, 8.2.0)sketches gives the 30-day slice MAU in< 10 ms. Never use HLL for intersections (such as retention|A ∩ B| = |A| + |B| - |A ∪ B|), where subtracting two±0.81%estimates of 100M users creates±1Mnoise that swamps a2Moverlap—always use Roaring Bitmaps for intersections!Design dashboard serving, caching, and slice semantics
Serving API
GET /v1/metrics/{dau | mau30 | mau_month | dau_anonymous} ?from=2026-10-28&to=2026-11-26&platform=ios&country=DE&app_version=*&day=utc&def_ver=1 -> { "points": [ { "date": "2026-11-26", "value": 1843200, "status": "provisional", "method": "approx", "relative_error_95": 0.016 }, { "date": "2026-11-22", "value": 1910045, "status": "final", "method": "exact" } ], "slice_mode": "overlapping", "data_version": 4182 }Query routing, caching, and slice semantics: - Routing: Totals, single-dimension slices, and popular 2D slices read exact rows from
metric_daily(~10 ms). Arbitrary multi-dimension historical slices (ios + DE + 8.2.0) fetch the matchingdaily_sketchescube cells (for a 30-day chart ofmau30, reading30 + 29 = 59daily sketches and sliding a 30-dayhll_mergewindow in~25 ms). Today's point mergesrealtime_sketches. - Caching:finalpoints are cached in Redis keyed by(query_hash, data_version)with no expiry (invalidated automatically if a restatement incrementsdata_version).provisionalpoints use a 60-second TTL. Top executive dashboards are pre-warmed right after the02:00 UTCbatch swap. - Overlapping slices: A user active on bothiosandwebon Tuesday rightly counts toward bothDAU(ios)andDAU(web), soDAU(ios) + DAU(android) + DAU(web) >= DAU(all). The UI displays a tooltip explaining non-additivity and offers an optionalslice_mode=primary_platform(attributing each user-day to the platform with the most qualifying events, ties broken alphabetically) when finance wants a 100% stacked bar chart.Monitor data quality, handle failures, and protect privacy
Staging quality gates and anomaly detection: Spark writes into staging partitions and swaps them live only if automated checks pass: - Ingestion telemetry: Alert per
sdk_versionifseqcounter gaps exceed0.5%, if rejection rates jump, or if one app version's volume drops> 30%week-over-week (classic broken app release). - Robust anomaly band: CompareDAU(d)against the same weekday across the prior 4–8 weeks usingmedian ± 4 × MAD(Median Absolute Deviation, the median distance from the median, which unlike standard deviation isn't skewed by one past holiday spike). Hold publish for human sign-off on outliers. - Cross-path reconciliation: Assertmax(slice) <= total, verify Flink HLL vs. Spark exact DAU stays within2%(0.81% HLL error + intraday un-stitched/late share), and verify monthly that|RoaringBitmap|equals raw SQLCOUNT(DISTINCT)to the exact integer.Fault tolerance: Offline SDK queues +
event_idsurvive collector outages; 3× replicated 7-day Kafka survives broker failures; Flink checkpoint replay is idempotent on HLLmaxregisters; Spark partition overwrites make batch reruns idempotent.Privacy and compliance (GDPR/CCPA): - Edge minimization: Drop
consent_analytics == falseimmediately; convert IP ->countryand discard raw IP in memory; replace raw device IDs with HMAC-SHA256 (a secret-keyed cryptographic hash stored in KMS) so raw IDs aren't stored while deterministic distinct counting keeps working. - Tiered retention & deletion: Retainraw_events90 days, pseudonymoususer_day_activityanddaily_bitmaps25 months, and aggregatemetric_daily(with cells< 50users suppressed in external exports) indefinitely. Honor right-to-erasure requests by deleting the user fromdense_id_map,device_login_links, anduser_day_activity, and clearing their bit fromdaily_bitmaps.Summarize key design trade-offs
Decision Area Chosen Design Trade-Off / Cost Accepted ----------------------------------------------------------------------------------------------------- Primary MAU definition Rolling 30-day (+ calendar month in batch) Mild weekday wobble; two series Day boundary UTC headline (+ per-country local_date) Local day differs from global chart Headline identity Authenticated `u:` keys (`d:` separate) Logged-out visitors in separate KPI Device-to-user stitching Same-day single-owner devices only Prior days aren't retroactively edited Late-event policy 4 nightly reruns (>=74h grace), then final Recent 3 days stay `provisional` Counting data structures Roaring Bitmaps (exact) + HLL (live/slices) Two paths reconciled nightly Dimension slices Overlapping sets (+ optional primary mode) Default platform lines sum > 100% Raw vs derived retention 90d raw Parquet, 25m user_day_activity Old backfills limited to kept cols
Intuition & how it works
Think of computing DAU and MAU like taking attendance at a massive multi-gate festival where visitors enter dozens of times a day, wear temporary wristbands before picking up their named badge, and sometimes mail in paper attendance slips from offline zones up to three days later. Instead of recounting 8 billion raw gate scans every time an executive loads a chart, we mount fast compact counters at the gates for today's live scoreboard (mergeable HyperLogLog sketches) while an overnight clerk compiles one deduplicated attendance card per person per day (user_day_activity and exact Roaring Bitmaps), refreshing the last 4 days each night before stamping a day's count final.
The naive approach—running SELECT COUNT(DISTINCT user_id) over raw event logs on every dashboard request—scans terabytes of data, takes minutes per click, and returns shifting numbers whenever delayed mobile batches trickle in. Worse, grouping by server arrival time pushes an airplane passenger's Tuesday evening flight activity onto Wednesday, summing 30 daily DAUs counts a daily user 30 times instead of once for MAU, and counting background push notifications inflates DAU with untouched phones sitting in pockets.
Walk through a concrete 4-event trace for Maya (device = anon_9c, account = u_731):
1. Offline flight + clock correction: Maya launches the app at Oct 14 23:45 UTC in airplane mode and uploads 2 hours later at Oct 15 01:45 UTC; subtracting client_sent_ts from server_received_ts shows zero clock skew, placing the event accurately onto Oct 14 UTC during the nightly rerun.
2. Duplicate retry: A spotty cellular connection resends that same batch with the identical event_id; because distinct counting measures set membership ({u_731} ∪ {u_731} = {u_731}), her DAU contribution remains 1 with zero streaming dedupe state.
3. Same-day login stitching: On Oct 15 08:30 UTC, Maya views a screen logged out on anon_9c and signs in as u_731 two minutes later; because u_731 is the sole user on anon_9c that day, both events map to canonical key u:u_731.
4. Exact MAU union: Mapping u:u_731 to integer dense_id = 512 sets bit 512 in both Bitmap(Oct 14) and Bitmap(Oct 15), so DAU(Oct 14) = 1, DAU(Oct 15) = 1, and MAU30(Oct 15) (Bitmap(Oct 14) OR Bitmap(Oct 15)) counts Maya exactly once (1).
Key trade-offs
- Rolling 30-day MAU vs. calendar-month MAU. Rolling 30-day MAU updates every day with a constant 30-day denominator—making
DAU / MAUstickiness meaningful and avoiding February looking ~10% smaller than March—at the cost of not matching monthly accounting periods. Publishing both from the same daily bitmaps satisfies product and finance with one pipeline. - Exact Roaring Bitmaps vs. approximate HyperLogLog (HLL) sketches. Roaring Bitmaps (compressed 32-bit integer sets) compute 100% exact unions and intersections in batch jobs, whereas HLL sketches (
16 KBregister arrays with~0.81%standard error) update in real time and merge across arbitrary slices in milliseconds but fail on small intersections. Using exact bitmaps for official numbers and HLL for live intraday and ad-hoc multi-dimension slices gives each workload the right tool, at the cost of reconciling two paths nightly. - UTC day vs. local day. Standardizing headline DAU on UTC avoids 23- and 25-hour daylight-saving distortions and gives one global cut-off, while storing
local_datein theuser_day_activitygrain supports regional product teams without mixing incompatible axes on one chart. - Authenticated
u:headline vs. combined anonymous IDs. Counting authenticatedu:<user_id>keys as headline DAU ties the metric to real accounts rather than ephemeral browser cookies, while reportingd:<anonymous_id>separately keeps top-of-funnel logged-out traffic visible without silently overcounting multi-device users. - Four-night (>= 72-hour) finality window vs. instant freeze. Recomputing
T - 1throughT - 4nightly captures~99.95%of offline mobile uploads before lockingT - 4asfinal, trading 3 days of clearly badgedprovisionalmovement against permanently undercounting mobile users. - 90-day raw retention + 25-month
user_day_activityvs. keeping raw logs forever. Dropping raw logs after 90 days slashes storage cost and privacy risk while keeping per-event-name counts inuser_day_activitypreserves 25 months of backfill power for metric-definition changes.
Common mistakes
- Counting background push receipts, silent syncs, or health pings as "active", inflating DAU whenever marketing sends a push campaign.
- Bucketing events by
server_received_tsinstead of skew-correctedclient_ts, shifting offline mobile sessions and post-midnight retries onto the wrong calendar day. - Summing daily DAU across 30 days to compute MAU, or adding HLL estimates numerically instead of merging registers with
max(), massively double-counting repeat users. - Intersecting single-dimension daily bitmaps (
S_{d, ios} ∩ S_{d, DE}) to answer multi-dimension queries, which falsely includes a traveler who used Android in Germany and iOS in France on the same day instead of querying(platform, country)pairs inuser_day_activity. - Using HyperLogLog inclusion-exclusion (
|A| + |B| - |A ∪ B|) for small intersections or cohort retention, where±0.81%noise on large sets completely swamps the intersection size. - Retroactively rewriting past months' DAU whenever a logged-out device logs in weeks later, causing closed historical board numbers to drift continuously.
- Rotating the salt on hashed
anonymous_ids daily, which turns one returning device into 30 distinct IDs across a month and destroys MAU accuracy (use a stable KMS-managed HMAC secret key instead, and honor deletion requests explicitly).
Follow-up questions
- Suppose headline DAU suddenly falls by 8% one morning—how would you determine whether users actually left or the telemetry pipeline broke? Check pipeline health before product hypotheses because telemetry bugs isolate fast: inspect collector error rates, Kafka consumer lag, per-install
seqcounter gaps, stream-vs-batch divergence, and event volume broken down byplatformandapp_versionagainst the same weekday last week. An ingestion bug almost always concentrates in one slice (for example,iOS 8.3.0dropping to zero after a broken SDK release), whereas a real outage or regional holiday drops broadly and corroborates with independent backend signals like login RPCs, payment checkouts, and CDN traffic. Meanwhile, the staging anomaly gate (median ± 4 × MAD) automatically holds final publication and posts a dashboard banner until an engineer confirms the cause. - How would you adapt your architecture to calculate Day-7 cohort retention or count users active across both web and mobile? Both questions ask for set intersections, which is where HLL fails and our exact 32-bit
dense_idRoaring Bitmaps shine. For Day-7 retention of users acquired on dayx, store a daily new-user bitmapNew_x(keys whose minimum first-seen date isx) and compute|New_x AND S_{x+7}| / |New_x|; for 30-day cross-platform overlap, union 30 dailywebbitmaps intoW, union 30 dailymobilebitmaps intoM, and compute|W AND M|. Both bitwiseANDoperations execute in milliseconds to seconds in the nightly batch job with zero approximation error. - If product managers ask to filter DAU and MAU by a mutable account attribute such as billing plan or signup channel, how do you support that without blowing up sketch storage? Distinguish event-level attributes (like
app_version) from user-level attributes: never bloat mobile event payloads withacquisition_channel, and instead joinuser_day_activityagainst a date-versioned user dimension table ((user_id, valid_from, valid_to) -> tier, channel) inside the nightly Spark job, which immediately unlocks 25-month historical backfills. Add exact daily Roaring Bitmaps for single-dimension views (S_{d, tier=pro}), and cap high-cardinality dimensions (such as top 50 channels plus"other") while materializing HLL sketches only for queried dimension pairs rather than the full2^Dcube so daily sketch storage stays under a few hundred megabytes.
Follow-up questions
- Suppose headline DAU suddenly falls by 8% one morning—how would you determine whether users actually left or the telemetry pipeline broke?
- How would you adapt your architecture to calculate Day-7 cohort retention or count users active across both web and mobile?
- If product managers ask to filter DAU and MAU by a mutable account attribute such as billing plan or signup channel, how do you support that without blowing up sketch storage?
Similar questions
- Top-URL Traffic and Paid Conversion Analytics System
- Exact Command-Line Line Deduplication Beyond Available RAM
- Mastering and Applying a Recent Technical Skill
- Real-Time Test Status Logger and Interval Queries
- Streaming Test Status Logger and Failure Analytics
- Driving Unowned Engineering Improvements With Senior Leadership
More Vanta interview questions
- Exact Command-Line Line Deduplication Beyond Available RAM Medium
- Mastering and Applying a Recent Technical Skill Medium
- Driving Unowned Engineering Improvements With Senior Leadership Medium Pro
- Consecutive Line Run Deduplicator Medium Pro
- Top-URL Traffic and Paid Conversion Analytics System Medium Pro
- Observability, Debugging, and Safe Rollout for an Enterprise Compliance Assistant Medium Pro
- Real-Time Test Status Logger and Interval Queries Medium Pro
- Streaming Test Status Logger and Failure Analytics Medium Pro
- Streaming Adjacent Line Deduplicator Easy Pro
- Deterministic Course Ordering via Recursive DFS Medium Pro