Engagement Analytics Pipeline: Daily and Monthly Unique Users
System DesignModel answerLast updated
Design a pipeline that ingests app events and serves daily and monthly distinct-user counts, with sliced dashboards, correct handling of late data, and sound data-quality and privacy practices.
Problem
A consumer app with web and mobile clients needs an internal system that reports how many distinct people use it each day and each month. Design that system end to end.
A user counts as active in a time window if they produced at least one qualifying event in that window. Qualifying events are things like app open, session start, page view, or login. Passive traffic such as background pings does not count.
What to cover
- Definitions. Define the daily unique-user metric. For the monthly metric, pick either calendar-month uniques or a rolling 30-day window, justify the choice, and explain what you give up.
- Ingestion and event schema. Explain how events from web and mobile reach your backend, and list the fields every event must carry.
- Identity and duplicates. Describe how you handle repeated deliveries of the same event, and define a single canonical user key when events may carry a
user_id, a device or anonymous ID, or neither (logged-out usage). - Correctness of the numbers. Explain how you deal with time zones and day boundaries, late events, out-of-order events, client clock skew, and reprocessing of history.
- Storage and compute. Justify your choices between streaming and batch, and between exact and approximate distinct counting.
- Serving. Support near-real-time dashboards plus historical queries by date range, platform, country, and app version. Discuss latency, caching, and what correctness you promise to consumers.
- Operations. Cover anomaly detection, reconciliation, failure handling, and privacy (PII handling and retention).
Scale assumptions you may adopt or adjust
State your own numbers. A reasonable starting point is around 100M daily users, 300M monthly users, and several billion events per day.
Hints
Hint 1
Distinct counts are idempotent: a duplicated event cannot inflate the number of unique users. Think about where deduplication actually matters and where it is only an optimization.
Hint 2
You cannot add 30 daily unique counts to get a monthly one. Think about storing something per day that can be merged later, such as a per-day set of user IDs (bitmap) or a mergeable sketch.
Hint 3
Separate a fast, provisional path from a slow, authoritative one, and make the authoritative path a deterministic, re-runnable function of raw data plus a definition version so backfills are safe.
Hint 4
Keep the design simple enough to explain clearly: one raw store, one compact per-user-per-day table, one serving store. Be explicit about what lives where and why.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and scale
Assumptions: ~100M DAU, ~300M MAU, ~50 events per user per day, so ~5B events/day (~60K/s average, ~200K/s peak) at ~1 KB each, or ~5 TB/day raw. Dashboards should be fresh within 1-2 minutes; official numbers are finalized about two days after the day ends. Queries slice by date range, platform, country and app version, with p99 under about 1 s. The warehouse itself is out of scope.
2. Metric definitions
- DAU: distinct canonical users with at least one qualifying event on day D. Default day boundary is UTC.
- MAU, primary choice: rolling 30 days (D-29..D). It yields a comparable value every day, makes the DAU/MAU stickiness ratio meaningful, and avoids 28-31 day month artifacts.
- Calendar-month MAU suits finance and billing alignment, but gives one final number per month, a month-to-date value that climbs all month, and a structurally low February. Since both are unions of daily user sets, I would offer it as a secondary view at almost no cost.
- Keep the list of qualifying events in a versioned config. Changing it triggers a backfill.
3. Ingestion and data model
Clients (SDKs batch and retry with backoff) send to a stateless, autoscaled collector. It validates against a schema registry, routes bad events to a dead-letter queue, and writes to Kafka partitioned by a hash of the canonical key. Two consumers:
- a stream processor (Flink) for fresh numbers,
- a raw lake (Parquet/Iceberg, partitioned by date and hour) as the source of truth.
Required fields:
| Field | Purpose |
|---|---|
event_id (client UUID) | dedup |
event_name, schema_version | qualification, evolution |
user_id (nullable), anonymous_id/device_id | identity |
client_ts, client_sent_ts, server_received_ts | skew correction |
tz_offset | local-day attribution |
platform, app_version, os | dimensions |
country | derived from IP at ingest, then the IP is dropped |
4. Duplicates and identity
Dedup. Retries and SDK replays create duplicates. Use keyed state on event_id with a ~48h TTL in the stream, and ROW_NUMBER() OVER (PARTITION BY event_id) in batch. The key point: unique-user counts are naturally idempotent, so imperfect dedup does not distort DAU. It matters for event counts and depth metrics only.
Canonical key, in priority order:
user_idif present.- Else look up
anonymous_idin an alias table (anonymous_id -> user_id), filled whenever a login event carries both. - Else
anon:<anonymous_id>.
When a logged-out device is later linked to an account, the batch layer recomputes so the same person is not counted twice on a day. Publish Total DAU and Logged-in DAU separately, and state that anonymous IDs overcount people (cleared cookies, multiple devices).
5. Getting the numbers right
- Event time, not arrival time. Correct skew with
event_ts = server_received_ts - (client_sent_ts - client_ts). Clamp implausible values (future, or older than ~7 days) toserver_received_ts. - Day boundaries. The official metric is the UTC day. Also store
local_datefromtz_offsetfor regional "local DAU". Never mix the two in one chart. - Late and out-of-order events. Streaming uses watermarks with ~10 minutes of allowed lateness; its numbers are labeled provisional. Updating a set or sketch is a union, so order does not matter. Batch finalizes day D around T+48h; later arrivals still land in their correct
event_datepartition, and a nightly job restates partitions whose late volume exceeds a threshold. - Backfills. Batch outputs are deterministic functions of (raw partition, definition version) written with partition overwrite, so reruns are safe. Because each rolling MAU point spans 30 days, restating day D means recomputing MAU for D..D+29.
6. Storage, compute, exact vs approximate
A Lambda-style split keeps things understandable:
- Streaming maintains HyperLogLog sketches per (time bucket, platform, country, app_version) for freshness.
- Batch (Spark) builds the core table
user_day(event_date, user_key, platform, country, app_version, first_event_ts, event_count): ~100-150M rows/day, cheap, and the source for any future metric.
Counting strategy:
- DAU: exact via
COUNT(DISTINCT)onuser_day. - Rolling MAU: the hard case, since daily counts cannot be summed.
- Official/headline MAU: map users to dense integer IDs and store a Roaring bitmap per day per slice; MAU is the cardinality of the OR of 30 bitmaps. Exact, compact, seconds to compute.
- Ad-hoc slices: HLL sketches (precision 14, ~16 KB, ~0.8% error) per (date, platform, country, version) cell. About 30K cells/day is roughly 500 MB/day. Any range and filter is a sketch union, and users present in several slices are not double-counted.
- Use Theta sketches if intersections are needed ("active on iOS and Android").
Policy: headline numbers exact, exploratory slices within ~1%, and the UI labels which is which.
7. Serving
Load daily exact aggregates and sketch columns into an OLAP store (Pinot, Druid or ClickHouse). A metrics API takes metric, window, date range, filters and tz, and returns values plus metadata: status (provisional or final), exact or approximate, and as_of. Cache finalized historical ranges aggressively (immutable until a restatement bumps a version), keep a short TTL for today. Pre-aggregated cubes give p99 well under 1 s. Provisional data from the stream and final data from batch are merged by date, with batch winning once available.
8. Monitoring, quality, failures, privacy
- Anomaly detection: compare DAU to same-weekday history; alert on drops by platform or version (often an SDK bug), and on spikes (often bot traffic or duplicate IDs).
- Reconciliation: compare stream vs batch daily; alert if the gap exceeds ~1%. Track DLQ rate, schema-violation rate and consumer lag.
- Fault tolerance: Kafka replication, Flink checkpointing with exactly-once sinks, replay from the raw lake. Idempotent batch overwrites make retries safe.
- Privacy: drop raw IP after geo lookup, hash or pseudonymize IDs in analytics tables, restrict raw-event access, apply retention (e.g. raw 13 months, aggregates longer), and support deletion requests by rebuilding affected partitions. Aggregates should avoid tiny cohorts that could identify individuals.
Trade-offs and common mistakes
- Summing daily uniques to get monthly uniques.
- Using arrival time instead of event time.
- Mixing UTC and local days on one chart.
- Overbuilding: keep the story simple. State clearly where raw data, the
user_daytable and the serving store live, and why each exists. - Not telling consumers which numbers are provisional or approximate.
- Forgetting that a restated day forces 30 days of MAU to be recomputed.