Warehouse Schema for a Consumer App's Engagement Events
System DesignModel answerLast updated
Model a high-volume user event stream in a relational warehouse so engagement metrics are cheap to compute, handling duplicates, late data, backfills and incremental rollups.
A consumer mobile app emits a continuous stream of user events (app opens, posts, taps, and so on). The analytics team wants to compute standard product metrics from this stream: daily, weekly and monthly active users, new users, D1/D7/D30 retention, funnel conversion (for example signup to first post), sessions per user and session length, and event counts sliced by platform or country.
Design a relational schema that lets these metrics be computed efficiently. State any assumptions about the metric list and scale first.
Your answer should cover:
- Table definitions with columns and data types, primary and foreign keys, and a few sample rows.
- The partitioning, clustering and indexing strategy.
- Where you normalize and where you denormalize, and why.
- How you deal with duplicate events and events that arrive late (or carry unreliable client clocks).
- How the design supports backfills and incrementally maintained aggregate tables.
- How the main metrics map onto your tables.
Hints
Hint 1
Almost every listed metric is 'per user per day' before it is aggregated further. Consider making a user-day table the central grain, and keep a separate raw, append-only layer underneath it.
Hint 2
Mobile clients retry and go offline, so each event needs a client-generated unique ID, and you must distinguish arrival time (trusted) from the device timestamp (not trusted). Think about which one drives partitioning at each layer.
Hint 3
Make every pipeline step idempotent: recompute and overwrite whole date partitions instead of updating rows. Then late data and backfills become 'rerun the affected days' rather than special cases.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions and scale
I would confirm the metric list first: DAU/WAU/MAU, new users, D1/D7/D30 retention, funnels, sessions and session length, and per-platform or per-country breakdowns.
Illustrative scale: 100M daily users at about 50 events each is roughly 5B events per day, around 60K events/s on average and 200K/s at peak. At about 300 bytes per compressed row, that is on the order of 1.5 TB per day. Dashboards refresh daily, so batch correctness matters more than second-level latency. Mobile data is messy: clients are offline for days, retry sends, and have wrong clocks. I assume a columnar warehouse (Spark/Hive, BigQuery, Snowflake); the same ideas work in Postgres with declarative partitioning.
Layered model
Use three layers: raw landing, cleaned atomic facts, then aggregated facts, plus small dimensions.
1. Raw landing (append-only, never updated)
CREATE TABLE raw_events (
event_id VARCHAR(36) NOT NULL, -- client UUID, idempotency key
user_id BIGINT, -- NULL when logged out
device_id VARCHAR(64) NOT NULL,
session_id VARCHAR(36),
event_name VARCHAR(64) NOT NULL,
client_ts TIMESTAMP, -- untrusted
server_ts TIMESTAMP NOT NULL, -- trusted receipt time
platform VARCHAR(16),
app_version VARCHAR(32),
country CHAR(2),
properties JSON,
ingest_date DATE NOT NULL -- partition key
) PARTITION BY (ingest_date);
Partitioning by arrival date keeps ingestion a pure append; old partitions are never rewritten.
2. Cleaned atomic fact
CREATE TABLE fact_events (
event_id VARCHAR(36) NOT NULL,
event_date DATE NOT NULL,
event_ts TIMESTAMP NOT NULL, -- corrected time
server_ts TIMESTAMP NOT NULL,
user_id BIGINT, device_id VARCHAR(64) NOT NULL,
session_id VARCHAR(36),
event_name VARCHAR(64) NOT NULL REFERENCES dim_event_type(event_name),
platform VARCHAR(16), app_version VARCHAR(32), country CHAR(2),
properties JSON, ingest_date DATE NOT NULL,
PRIMARY KEY (event_date, event_id)
) PARTITION BY (event_date) CLUSTER BY (user_id, event_name);
Timestamp correction rule: trust client_ts only if it lies within [server_ts - 7 days, server_ts + 5 minutes]; otherwise use server_ts. event_date is the UTC date of the corrected timestamp.
3. Dimensions
CREATE TABLE dim_event_type (
event_name VARCHAR(64) PRIMARY KEY,
category VARCHAR(32),
counts_as_active BOOLEAN NOT NULL -- one definition of "active"
);
CREATE TABLE dim_user ( -- SCD Type 2
user_sk BIGINT PRIMARY KEY,
user_id BIGINT NOT NULL,
signup_ts TIMESTAMP, country CHAR(2), acquisition_channel VARCHAR(32),
valid_from DATE NOT NULL, valid_to DATE, is_current BOOLEAN NOT NULL
);
4. Incremental aggregates (what dashboards read)
CREATE TABLE fact_user_daily (
ds DATE NOT NULL, user_id BIGINT NOT NULL,
platform VARCHAR(16), country CHAR(2),
event_count INT NOT NULL, active_event_count INT NOT NULL,
session_count INT NOT NULL, active_seconds INT NOT NULL,
first_event_ts TIMESTAMP, last_event_ts TIMESTAMP,
is_new_user BOOLEAN NOT NULL,
PRIMARY KEY (ds, user_id)
) PARTITION BY (ds) CLUSTER BY (user_id);
CREATE TABLE fact_user_first_seen ( -- one row per user
user_id BIGINT PRIMARY KEY,
first_active_date DATE NOT NULL,
first_platform VARCHAR(16), first_country CHAR(2)
);
CREATE TABLE fact_sessions (
session_id VARCHAR(36), event_date DATE, user_id BIGINT,
start_ts TIMESTAMP, end_ts TIMESTAMP, event_count INT,
PRIMARY KEY (event_date, session_id)
) PARTITION BY (event_date);
Sample rows:
| event_id | event_date | event_ts | user_id | event_name | platform | ingest_date |
|---|---|---|---|---|---|---|
| a1f... | 2024-05-01 | 2024-05-01 09:14:03 | 42 | app_open | ios | 2024-05-01 |
| b7c... | 2024-05-01 | 2024-05-01 09:15:40 | 42 | post_create | ios | 2024-05-03 (late) |
| ds | user_id | event_count | session_count | active_seconds | is_new_user |
|---|---|---|---|---|---|
| 2024-05-01 | 42 | 37 | 3 | 1260 | false |
Metric mapping
- DAU: count rows in
fact_user_dailyfor onedswithactive_event_count > 0. - WAU/MAU: distinct users over 7 or 30 partitions; store per-day HLL sketches to make this cheap.
- New users:
is_new_userorfirst_active_date = ds. - Dn retention: join
fact_user_first_seen(the cohort) tofact_user_dailyonds = first_active_date + n, divide by cohort size. - Funnels: scan
fact_eventsfiltered byevent_name, relying on partition pruning and clustering. - Sessions: read
fact_sessionsor the session columns offact_user_daily.
Normalize vs. denormalize
- Normalize for governance:
dim_event_type.counts_as_activegives every team the same DAU definition.dim_useras SCD2 allows "as of" analysis of attributes such as country. - Denormalize for scan cost: copy
platform,countryandapp_versiononto events and user-day rows to avoid joins against multi-billion-row tables. Low-cardinality strings compress to almost nothing in columnar storage. Note that these values are as of event time, which is usually desired; document it. - Keep
propertiesas JSON because event schemas change quickly; promote hot fields to real columns when they are queried frequently.
Partitioning and indexing
- Partition by date everywhere: pruning, per-day TTL, and atomic partition overwrite. Raw by
ingest_date, facts byevent_date. - Cluster by
user_idso user-day aggregation and retention joins are co-located; addevent_nameas a secondary key for funnels. - Columnar warehouses use min/max zone maps, so heavy B-tree indexing is unnecessary. In Postgres, rely on partition pruning plus a BRIN or B-tree on
(user_id, event_ts)within partitions.
Duplicates and late data
- Dedup: the client UUID is the idempotency key. When building
fact_events, keep one row per(event_id)usingROW_NUMBER() OVER (PARTITION BY event_id ORDER BY server_ts). Dedup within a lookback window (say 7 days of ingest partitions) so cost stays bounded. - Late events: because raw is partitioned by arrival, a late event lands in today's raw partition but belongs to an older
event_date. Each daily run rebuilds theevent_datepartitions touched by new arrivals within the lookback window, then recomputesfact_user_dailyandfact_sessionsfor those days. Beyond the window, either drop with a counter or send to a periodic correction job. - Bad clocks: apply the timestamp correction rule above and track how often it fires as a quality metric.
- Sessions that cross midnight: assign by session start, and recompute sessions at the user level over a two-day span.
Backfills and incremental builds
- All jobs are idempotent:
INSERT OVERWRITEa date partition from upstream partitions. Rerunning is always safe. - A backfill is a loop over a date range in dependency order: fact_events, then user_daily and sessions, then first_seen.
fact_user_first_seenis cumulative: for each day, insert only users not already present. For a backfill, rebuild it asMIN(ds)overfact_user_dailyto avoid order-dependent drift.- Keep raw data long enough (for example 90 days) to replay; the raw layer is the source of truth for reprocessing after logic changes.
Common mistakes
- Partitioning the fact table by arrival date, which scatters a day's events across partitions and makes late data hard to fix.
- Trusting client timestamps without bounds.
- Updating rows in place instead of overwriting partitions, which breaks idempotency.
- Defining "active" separately in each dashboard.
- Joining a big event table to a user dimension on every query instead of snapshotting needed attributes.
- Computing MAU by summing DAU rather than counting distinct users.