Designing a Scalable Event Data Analytics Warehouse
SQL & DataModel answerLast updated
Architect an end-to-end data warehouse for high-throughput event logs, detailing schema design, idempotent deduplication, metric modeling, and performance optimization.
You are tasked with designing an enterprise analytics data warehouse and ingestion framework to analyze user retention, ARPU (Average Revenue Per User), and regional product usage at a scale of approximately 50 million daily events. The system runs on a modern cloud data platform such as Snowflake or BigQuery.
Address the following four technical dimensions:
1. Data Modeling & Schema Strategy
Propose a multi-tier data architecture containing raw landing, core facts/dimensions, and analytical marts.
- Define explicit DDL for core tables (e.g., event facts, financial orders, user dimensions, regional dimensions).
- Specify table partitioning, clustering/sorting strategies, and key definitions.
- Detail your approach to Slowly Changing Dimensions (SCD Type 2) for tracking dynamic user attributes (e.g., user region, app version). Explain how event facts are linked to historical state.
2. Idempotency, Late-Arriving Data & Deduplication
Events can arrive out of order, up to 14 days late, and may contain duplicates with identical natural keys (user_id, event_ts, event_type).
- Define your deduplication key logic and data merging strategy.
- Detail an ingestion procedure that guarantees idempotent processing under retries.
- Explain how to handle late-arriving records without distorting cohort retention figures.
- Outline a historical backfill plan for schema updates or logic adjustments that minimizes resource consumption and query cost.
3. Metric Marts & Data Quality Control
Design the schema and logic for derived reporting tables (specifically, weekly cohort retention and cumulative ARPU).
- Provide the SQL logic required to build these cohort metrics, explaining windowing mechanics and date bucketing.
- Define automated data quality and integrity tests to validate cohort stability and metric boundaries over time.
4. Performance Tuning & Cost Optimization
- Calculate baseline data volume estimates for raw and compressed storage over a 1-year window.
- Justify your choice of partition granularity and clustering keys based on query patterns (e.g., 8-week top regional usage, rolling DAU/WAU/MAU).
- Detail cost reduction strategies using partition pruning, result caching, and approximate aggregation techniques (e.g., HyperLogLog).
Hints
Hint 1
Consider how point-in-time joins between fact tables and dynamic dimension tables (SCD Type 2) prevent backdating bias when processing late-arriving events.
Hint 2
When designing incremental metric builds, recomputing entire affected date buckets is significantly more robust against out-of-order data than trying to maintain running counters.
Hint 3
Ensure cohort retention calculations handle non-active weeks gracefully and clearly distinguish between ARPU (total cohort size denominator) and ARPPU (paying users only).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scale Assumptions & Architectural Overview
Before modeling, establish baseline computational constraints for an operation ingesting 50 million events per day:
- Throughput: ~580 events/sec average; peak sustained loads of 2,000–3,000 events/sec.
- Data Volume:
- Raw JSON (uncompressed): ~1 KB/event $\rightarrow$ 50 GB/day, ~18 TB/year.
- Columnar Compressed (Parquet/ORC/native cloud format): ~120 bytes/event $\rightarrow$ 6 GB/day, ~2.2 TB/year.
- User Base: ~5M Daily Active Users (DAU), ~100M total registered accounts.
- SLA & Freshness: Hourly micro-batch ingestion into facts; daily incremental rebuilds for analytical metrics marts.
- Data Lag: Events may arrive up to 14 days out of sequence.
Tiered Architecture
- Landing Tier (
raw): Append-only staging area. Retains immutable source payloads partitioned by ingestion timestamp. - Core Tier (
core): Normalized data model. Enforces deduplication, resolves surrogate keys, and stores clean fact and dimension tables. - Marts Tier (
mart): Aggregated metrics modeled for business intelligence, reporting, and cohort analytics.
2. Core Schema & DDL Strategy
-- Core Fact Table for User Events
CREATE TABLE core.fact_events (
event_id STRING NOT NULL, -- Client UUID or derived SHA256 hash
user_id STRING NOT NULL, -- Natural user identifier
user_sk INT64, -- FK to dim_user_history (SCD Type 2 at event_ts)
event_ts TIMESTAMP NOT NULL, -- Event creation time at client
event_date DATE NOT NULL, -- UTC Date derived from event_ts (Partition Key)
event_type STRING NOT NULL, -- e.g., 'page_view', 'checkout_click'
app_version STRING, -- Degenerate dimension for instant filtering
country_code STRING, -- Degenerate dimension for instant filtering
properties JSON, -- Dynamic payload attributes
ingested_at TIMESTAMP NOT NULL -- System processing timestamp
)
PARTITION BY event_date
CLUSTER BY event_type, user_id;
-- Core Fact Table for Revenue/Orders
CREATE TABLE core.fact_orders (
order_id STRING NOT NULL, -- Natural order key
user_id STRING NOT NULL, -- Natural user key
user_sk INT64, -- FK to dim_user_history at order_ts
order_ts TIMESTAMP NOT NULL,
order_date DATE NOT NULL, -- Partition Key
amount_usd NUMERIC(12, 4), -- Standardized currency amount
refund_usd NUMERIC(12, 4),
order_status STRING,
updated_at TIMESTAMP NOT NULL
)
PARTITION BY order_date
CLUSTER BY user_id;
-- Core Dimension Table: User History (SCD Type 2)
CREATE TABLE core.dim_user_history (
user_sk INT64 NOT NULL, -- Surrogate key: HASHTYPE(user_id || valid_from)
user_id STRING NOT NULL, -- Natural Key
signup_ts TIMESTAMP NOT NULL, -- Permanent account registration timestamp
country_code STRING,
app_version STRING,
valid_from TIMESTAMP NOT NULL, -- Version effective start timestamp
valid_to TIMESTAMP NOT NULL, -- Version effective end timestamp ('9999-12-31' if active)
is_current BOOLEAN NOT NULL -- Flag indicating latest attribute snapshot
)
CLUSTER BY user_id;
Slowly Changing Dimension (SCD Type 2) Mechanics
- Attribute Splitting: Rapidly changing attributes (such as
app_version) can create excessive dimension versions. Highly mutable properties can be retained directly onfact_eventsas degenerate dimensions, while stable attributes (such as homecountry_codeor user tier) are managed indim_user_history. - Point-in-Time Joins: Facts resolve
user_skduring batch enrichment by joining on the state valid at event generation time:
This guarantees that late-arriving historical events inherit the attributes that were active when the event actually occurred, avoiding retrofitting modern attributes onto past actions.WHERE event.user_id = dim.user_id AND event.event_ts >= dim.valid_from AND event.event_ts < dim.valid_to
3. Idempotency, Deduplication & Late-Arriving Ingestion
Deduplication Strategy
If an explicit client event_id is unavailable, synthesize an idempotent hash key:
$$\text{event_id} = \text{SHA256}(\text{user_id} \mathbin{\Vert} \text{CAST}(\text{event_ts AS STRING}) \mathbin{\Vert} \text{event_type})$$
To process incoming micro-batches from raw, partition windowing strips internal batch duplicates:
CREATE OR REPLACE TEMPORARY TABLE staging_deduped AS
SELECT * EXCEPT(row_num)
FROM (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY event_id, DATE(event_ts)
ORDER BY ingested_at DESC
) AS row_num
FROM raw.events_landing
WHERE ingested_at > (SELECT MAX(last_proc_ts) FROM core.ingestion_watermark)
)
WHERE row_num = 1;
Idempotent Upsert (MERGE) Execution
To prune partition scans on large target tables, restrict the target search space using the known maximum late-arrival threshold (14 days):
MERGE INTO core.fact_events AS target
USING staging_deduped AS source
ON target.event_id = source.event_id
AND target.event_date = DATE(source.event_ts)
AND target.event_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 15 DAY)
WHEN NOT MATCHED THEN
INSERT (event_id, user_id, event_ts, event_date, event_type, app_version, country_code, properties, ingested_at)
VALUES (source.event_id, source.user_id, source.event_ts, DATE(source.event_ts), source.event_type, source.app_version, source.country_code, source.ingested_at);
Processing Late-Arriving Data
Never update cohort aggregations using additive mutations (+1 counters). Instead, rely on partition-level replacement:
- Identify all distinct
event_datevalues updated in the latest processing run. - Map these dates to affected calendar weeks (
activity_week). - Re-aggregate downstream
marttables for the affected(signup_week, week_index)combinations using a dynamic slice delete-and-insert operation.
Backfill Strategy
When downstream transformations or business definitions change:
- Re-execute upstream transformation logic from immutable
rawtables into temporary shadow tables (core.fact_events_v2). - Run data quality assertion checks comparing
v1andv2. - Perform atomic swap operations:
- Snowflake:
ALTER TABLE core.fact_events SWAP WITH core.fact_events_v2; - BigQuery: Overwrite table partitions transactionally using
WRITE_TRUNCATEtasks.
- Snowflake:
4. Derived Analytics Marts & Data Quality
Metric Table: Cohort Retention & Cumulative ARPU
CREATE TABLE mart.cohort_weekly_metrics (
signup_week DATE NOT NULL,
week_index INT64 NOT NULL,
cohort_size INT64 NOT NULL,
active_users INT64 NOT NULL,
retention_rate NUMERIC(6, 4),
weekly_revenue NUMERIC(14, 2),
cum_arpu NUMERIC(10, 4),
updated_at TIMESTAMP NOT NULL
)
CLUSTER BY signup_week;
-- Incremental Rebuild Query for Affected Cohorts
WITH user_cohorts AS (
SELECT
user_id,
DATE_TRUNC(DATE(signup_ts), WEEK(MONDAY)) AS signup_week
FROM core.dim_user_history
WHERE valid_from = signup_ts -- Captures initial state/signup date
),
cohort_sizes AS (
SELECT signup_week, COUNT(DISTINCT user_id) AS cohort_size
FROM user_cohorts
GROUP BY 1
),
weekly_user_activity AS (
SELECT
e.user_id,
DATE_TRUNC(e.event_date, WEEK(MONDAY)) AS activity_week,
SUM(COALESCE(o.amount_usd - o.refund_usd, 0)) AS revenue_usd
FROM core.fact_events e
LEFT JOIN core.fact_orders o
ON e.user_id = o.user_id
AND e.event_date = o.order_date
GROUP BY 1, 2
),
cohort_activity AS (
SELECT
c.signup_week,
CAST(DATE_DIFF(a.activity_week, c.signup_week, DAY) / 7 AS INT64) AS week_index,
COUNT(DISTINCT a.user_id) AS active_users,
SUM(a.revenue_usd) AS weekly_revenue
FROM user_cohorts c
JOIN weekly_user_activity a ON c.user_id = a.user_id
WHERE a.activity_week >= c.signup_week
GROUP BY 1, 2
)
SELECT
ca.signup_week,
ca.week_index,
cs.cohort_size,
ca.active_users,
ROUND(CAST(ca.active_users AS NUMERIC) / cs.cohort_size, 4) AS retention_rate,
ca.weekly_revenue,
ROUND(
SUM(ca.weekly_revenue) OVER (
PARTITION BY ca.signup_week
ORDER BY ca.week_index
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) / cs.cohort_size,
4
) AS cum_arpu,
CURRENT_TIMESTAMP() AS updated_at
FROM cohort_activity ca
JOIN cohort_sizes cs ON ca.signup_week = cs.signup_week;
Metric Modeling Note: ARPU divides total cohort cumulative revenue by the total initial cohort size (including non-paying users). Dividing solely by paying users yields ARPPU (Average Revenue Per Paying User).
Data Quality Assertions
Automate checks post-materialization:
- Retention Upper Bound:
ASSERT NOT EXISTS (SELECT 1 FROM mart.cohort_weekly_metrics WHERE retention_rate > 1.0 OR retention_rate < 0.0); - Monotonic Cohort Size Verification: Ensure baseline cohort sizes remain invariant over consecutive runs:
SELECT signup_week FROM mart.cohort_weekly_metrics GROUP BY signup_week HAVING COUNT(DISTINCT cohort_size) > 1; -- Should return zero rows - Week Zero Integrity Check:
week_index = 0retention rate should equal1.0unless single-day signup dropoff rules explicitly allow immediate churn.
5. Performance Optimization & Cost Controls
Key Indexing & Partition Pruning Strategies
| Analysis Pattern | Partition Key | Cluster / Sorting Keys | Performance Benefit |
|---|---|---|---|
| Top Countries (Last 8 Weeks) | event_date | country_code, event_type | Prunes scanning to last 56 partitions; clusters geography contiguous blocks. |
| Rolling DAU / WAU / MAU | event_date | user_id | Scans target dates; groups matching users into single micro-partitions. |
| Cohort Funnel Analysis | event_date | event_type, user_id | Allows engine to skip non-relevant event types completely. |
Approximate Aggregations for Active Users
For high-level dashboard queries where exact distinct counts are unnecessary, avoid scanning raw string identifiers by using HyperLogLog (HLL) sketch algorithms:
-- HyperLogLog State Materialization for DAU
CREATE TABLE mart.daily_user_sketches AS
SELECT
event_date,
country_code,
HLL_COUNT.INIT(user_id) AS user_sketch
FROM core.fact_events
GROUP BY 1, 2;
-- Fast Approximation Query Across Dynamic Intervals
SELECT
country_code,
HLL_COUNT.MERGE(user_sketch) AS approx_mau
FROM mart.daily_user_sketches
WHERE event_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
GROUP BY 1;
Result: Query execution speeds improve by over 10x–50x while maintaining $\approx 99%$ accuracy ($\pm 1%$ standard error rate), significantly reducing compute slot utilization and cost.
Execution & Cost Summary
- Partition Bounds: Enforce mandatory dynamic partition filters on
event_datein BI query templates. - Micro-Partition Size: Target warehouse file micro-partitions around 100 MB–500 MB compressed.
- Caching Utilization: Leverage warehouse result caching by serving immutable past cohort weeks directly from materialized tables.