Rerun-Safe Monthly Churn Pipeline with Late Events
System DesignModel answerLast updated
Design a daily pipeline that turns streaming subscription events into month-end churn and retention metrics, tolerating late data, safe reruns, 12-month backfills, and changing metric definitions.
Scenario
A subscription business emits a stream of events: start, upgrade, downgrade, cancel and reactivate. Each event has an event_id, subscription_id, customer_id, plan_id, mrr, an event timestamp and an ingestion timestamp. Events can show up as much as 3 days after they happened.
You own a daily batch job that must publish month-end metrics:
- Logo churn
- Gross revenue churn
- Net revenue retention (NRR)
Requirements
- Every run is idempotent: rerunning on the same inputs produces the same outputs and never double-applies an event.
- You can backfill the last 12 months.
- Plan attributes change over time, so the plan dimension is a Type 2 slowly changing dimension.
- The pipeline has data quality checks that can block publication.
- Results are reproducible, so a past number can be explained and regenerated.
What to cover
- DAG. Describe the tasks and their dependencies from raw events through curated snapshots to published metrics. State partitioning, clustering and keys for each table.
- Snapshot upsert. Write SQL (a MERGE or equivalent) that builds a monthly subscription snapshot from event-level changes. It must handle late cancels and reactivations correctly and must not double-apply anything on a rerun.
- Selective recompute. Explain how you detect which months a late event affects, recompute only those, and prove the recompute is correct using invariants.
- Metric versioning. Explain how historical reports stay interpretable when a metric definition changes (for example, via a semantic layer with versioned views).
State your assumptions about the schema before you start.
Hints
Hint 1
Avoid applying deltas to yesterday's output. If each snapshot row is a pure function of the deduplicated event history up to that month end, reruns are naturally safe.
Hint 2
A late event changes the state at its own month end and, because state carries forward, every later month too. Think about what range you must recompute and what high-water mark tells you where to start.
Hint 3
For metrics, define the cohort first: customers with MRR > 0 at the previous month end. Then logo churn, gross churn and NRR are all ratios over that same cohort, and invariants such as 'NRR = 1 - gross churn + expansion' become checkable.
Hint 4
For versioning, make the version part of the metric table key and expose both a pinned view and a 'current' alias, so old dashboards do not silently change.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Events carry event_id, subscription_id, customer_id, event_type (start, upgrade, downgrade, cancel, reactivate), plan_id, mrr, event_ts, ingested_at and a per-subscription event_seq. Delivery is at-least-once, so duplicates occur.
Core principle
Each snapshot row is a pure function of deduplicated event history up to a month end. Nothing is applied as a delta to prior output. A late cancel just changes which event is "latest" for a subscription, so reruns cannot double-apply anything.
1) DAG, partitioning, keys
ingest_raw -> dq_raw -> stg_events (dedup) --+
+-> fct_sub_month (MERGE) -> dq_snapshot -> metrics_monthly -> publish
src_plans -> dim_plan_scd2 ------------------+
detect_affected_months (ingested_at watermark) parameterizes snapshot + metrics
| Table | Key | Partition | Cluster |
|---|---|---|---|
raw_events (append-only) | event_id, ingested_at | ingest_date | event_type |
stg_events | event_id, latest ingest wins | event_date | subscription_id, event_ts |
dim_plan_scd2 | surrogate plan_sk; natural plan_id + valid_from | none | plan_id |
fct_sub_month | (snapshot_month, subscription_id) | snapshot_month | customer_id |
metrics_monthly | (snapshot_month, metric_name, metric_version) | snapshot_month | metric_name |
etl_run_log | run_id | none | none |
SCD2 plans: when an attribute hash changes, close the open row (valid_to = change_ts) and insert a new row with valid_to = '9999-12-31'. Snapshots join on month_end >= valid_from AND month_end < valid_to, giving the plan as of that month end rather than today's.
Gates: dq_raw checks schema, non-null keys, valid enum, mrr >= 0 and duplicate rate. dq_snapshot checks the invariants below. A failure blocks publish.
2) Snapshot MERGE
-- :start_month, :end_month, :run_id
MERGE INTO fct_sub_month t
USING (
WITH months AS (
SELECT month_start AS snapshot_month, month_end
FROM dim_calendar_month
WHERE month_start BETWEEN :start_month AND :end_month
),
latest AS (
SELECT m.snapshot_month, m.month_end, e.subscription_id, e.customer_id,
e.event_type, e.plan_id, e.mrr, e.event_ts,
ROW_NUMBER() OVER (
PARTITION BY m.snapshot_month, e.subscription_id
ORDER BY e.event_ts DESC, e.event_seq DESC, e.event_id DESC) rn
FROM months m
JOIN stg_events e ON e.event_ts < m.month_end + INTERVAL '1' DAY
),
src AS (
SELECT l.snapshot_month, l.subscription_id, l.customer_id, p.plan_sk,
CASE WHEN l.event_type = 'cancel' THEN 'churned' ELSE 'active' END status,
CASE WHEN l.event_type = 'cancel' THEN 0 ELSE l.mrr END mrr,
l.event_ts last_event_ts
FROM latest l
LEFT JOIN dim_plan_scd2 p
ON p.plan_id = l.plan_id
AND l.month_end >= p.valid_from AND l.month_end < p.valid_to
WHERE l.rn = 1
)
SELECT s.*, MD5(CONCAT_WS('|', customer_id, plan_sk, status,
CAST(mrr AS VARCHAR), CAST(last_event_ts AS VARCHAR))) row_hash
FROM src s
) s
ON t.snapshot_month = s.snapshot_month AND t.subscription_id = s.subscription_id
WHEN MATCHED AND t.row_hash <> s.row_hash THEN UPDATE SET
customer_id = s.customer_id, plan_sk = s.plan_sk, status = s.status,
mrr = s.mrr, last_event_ts = s.last_event_ts, row_hash = s.row_hash,
updated_run_id = :run_id
WHEN NOT MATCHED THEN INSERT
(snapshot_month, subscription_id, customer_id, plan_sk, status, mrr,
last_event_ts, row_hash, updated_run_id)
VALUES (s.snapshot_month, s.subscription_id, s.customer_id, s.plan_sk, s.status,
s.mrr, s.last_event_ts, s.row_hash, :run_id)
WHEN NOT MATCHED BY SOURCE
AND t.snapshot_month BETWEEN :start_month AND :end_month THEN DELETE;
Why this is safe:
- Upstream dedup:
stg_eventsis a MERGE onevent_id, so replayed messages collapse to one row. - Deterministic tie-break:
event_seq, thenevent_id, so equal timestamps give stable output. - Scoped delete: removes rows invalidated by a corrected event, only inside the recompute range.
- No-op reruns: the
row_hashguard means an unchanged rerun updates zero rows, which makes idempotency directly testable. - Engines without
NOT MATCHED BY SOURCE: delete the range and insert in one transaction, or use an atomic partition overwrite. - Cost: scanning all history per month is correct but expensive. Computing months in order (state(m) = state(m-1) + events in m) is cheaper and still idempotent as long as m-1 is rederived in the same run.
Metrics use customer grain over consecutive snapshots. The cohort prev is customers with MRR > 0 at m-1, and cur_mrr is their MRR at m.
- Logo churn = count(prev with cur_mrr = 0) / count(prev)
- Gross revenue churn = sum(prev_mrr - LEAST(cur_mrr, prev_mrr)) / sum(prev_mrr), covering cancellations and contraction
- NRR = sum(cur_mrr) / sum(prev_mrr) over the prev cohort only, so new customers are excluded
3) Recomputing only affected months
Detect. etl_run_log stores the last successful ingested_at high-water mark:
SELECT MIN(DATE_TRUNC('month', event_ts)) AS start_month
FROM stg_events WHERE ingested_at > :last_hwm;
Range. Recompute [start_month, current_month], plus one prior month so the metrics have a prev snapshot. State carries forward, so a late March cancel changes March, April and every later month. With T+3 lateness, most runs touch only the current and previous month. A true 12-month backfill is the same job with explicit parameters.
Advance the watermark only after publish succeeds, and write run_id, range and row counts to the log. A failed run simply repeats.
Invariants (checked in dq_snapshot):
- Primary key uniqueness on (
snapshot_month,subscription_id). - Churned rows have
mrr = 0, and active rows havemrr > 0. - Row count per month is at least the previous month's, because subscriptions are never dropped, only churned.
- Reconciliation: MRR(m) = MRR(m-1) + new + expansion + reactivation - contraction - churn, exactly.
- NRR is at least 1 - gross revenue churn, and logo churn lies in [0, 1].
- Months outside the range have unchanged row hashes, so the recompute stayed scoped.
- Idempotency test: running twice yields zero updated rows on the second run.
- Comparison against the previous published value: flag deltas above a threshold for months that were recomputed, and record them as restatements.
4) Metric versioning
- Put
metric_versionin the key ofmetrics_monthly, and store a definition record (SQL text hash, owner, effective date, change reason) in ametric_definitionstable. - Each version is a view over the snapshot, for example
churn_v1andchurn_v2. Achurn_currentalias points at the latest version, while dashboards that need stability pin a version. - On a definition change, backfill the new version for all history and keep the old one. Both can then be compared side by side over the same months.
- Keep snapshot facts version-independent; only the metric layer changes. That is why recomputing a metric never requires rebuilding events.
- Reproducibility: record the code commit,
run_idand input watermark with each metrics row, and optionally use table time travel or snapshots to regenerate a past report.
Common mistakes
- Applying deltas to the previous output, so reruns double-count.
- Recomputing only the month of the late event and ignoring later months.
- Including new customers in NRR.
- Joining the current plan instead of the plan valid at month end.
- Nondeterministic ordering when timestamps tie.
- Advancing the watermark before publish succeeds.
- Overwriting a metric in place on a definition change, which silently rewrites history.