Backend & GCP Data Engineer Guide: SaaS Cohort Retention SQL, Net Dollar Retention (NDR) & BigQuery BI Pipelines
Executive teams and SaaS investors rely on accurate monthly cohort retention matrices, Net Dollar Retention (NDR), and expansion/contraction MRR waterfalls. Computing these metrics inside application loops in Python is slow and bug-prone. As a Senior Backend Engineer and Google Cloud Certified GCP Data Engineer, I push cohort and revenue analytics into set-based PostgreSQL / BigQuery CTEs and window functions.
1. Production SQL for Monthly User Cohort Retention Matrix
Below is the single-pass SQL pattern using `DATE_TRUNC('month', ...)` and `AGE()` / `DATE_DIFF()` to compute cohort size and active retention percentages across months $0..12$:
WITH user_cohorts AS (
SELECT
user_id,
DATE_TRUNC('month', created_at)::date AS cohort_month
FROM accounts_user
WHERE is_active = TRUE
),
monthly_activity AS (
SELECT DISTINCT
e.user_id,
DATE_TRUNC('month', e.occurred_at)::date AS activity_month
FROM telemetry_events e
),
cohort_sizes AS (
SELECT cohort_month, COUNT(*) AS initial_users
FROM user_cohorts
GROUP BY cohort_month
)
SELECT
c.cohort_month,
s.initial_users,
(EXTRACT(YEAR FROM AGE(a.activity_month, c.cohort_month)) * 12 +
EXTRACT(MONTH FROM AGE(a.activity_month, c.cohort_month)))::int AS month_offset,
COUNT(DISTINCT a.user_id) AS retained_users,
ROUND(100.0 * COUNT(DISTINCT a.user_id) / NULLIF(s.initial_users, 0), 2) AS retention_pct
FROM user_cohorts c
JOIN cohort_sizes s ON s.cohort_month = c.cohort_month
JOIN monthly_activity a ON a.user_id = c.user_id AND a.activity_month >= c.cohort_month
GROUP BY 1, 2, 3
ORDER BY 1 DESC, 3 ASC;
2. Refreshing Materialized Analytics Views Without Locking OLTP Traffic
- `REFRESH MATERIALIZED VIEW CONCURRENTLY`: Schedule background refreshes every 15 minutes via Celery Beat or Cloud Scheduler so tenant dashboards load in under 10ms without scanning raw event tables.
3. Related Backend & GCP Engineering Guides
- Hire a Google Cloud Certified GCP Engineer: BigQuery & Data Engineering
- Hire a Senior Backend Engineer: PostgreSQL & Python Analytics APIs
⚡ Hire Aldian Fazrihady — Senior Cloud, GCP, Backend, AI Application & Full Stack Engineer
Need production cloud architecture, GCP/AWS infrastructure, high-throughput backend systems, AI agents, or full stack web engineering? Book a 1-Day Programming Sprint for $100 USD (International Card / Apple Pay) or Rp 1,000,000 (Indonesian QRIS / Bank Virtual Account), or hire directly on Upwork:
Book $100 / Rp 1M 1-Day Sprint → Hire on Upwork (100% Job Success) →