Skip to content

A complete AI agency at your fingertips - From frontend wizards to Reddit community ninjas, from whimsy injectors to reality checkers. Each agent is a specialized expert with personality, processes, and proven deliverables.

Shell

Prevent customer joins from multiplying cloud cost totals

Rudy Celekli506bd2146b2e
diff --git a/engineering/engineering-finops-engineer.md b/engineering/engineering-finops-engineer.md
index 65a747c1..5565463b 100644
--- a/engineering/engineering-finops-engineer.md
+++ b/engineering/engineering-finops-engineer.md
@@ -84,18 +84,29 @@ A commitment you don't fully utilize is a discount you paid for and threw away.
### Unit Economics Dashboard (spend judged against value)
```sql
--- Cost per active customer, trended — the number that tells growth from waste.
--- Total cloud cost rising is fine IF cost-per-unit is flat or falling.
-SELECT
- date_trunc('month', usage_date) AS month,
- SUM(unblended_cost) AS total_cloud_cost,
- COUNT(DISTINCT customer_id) AS active_customers,
- SUM(unblended_cost) / NULLIF(COUNT(DISTINCT customer_id), 0) AS cost_per_customer,
- SUM(unblended_cost) FILTER (WHERE tag_environment = 'prod') AS prod_cost,
- SUM(unblended_cost) FILTER (WHERE tag_environment != 'prod') AS nonprod_cost
-FROM cost_and_usage
-JOIN customer_activity USING (usage_date)
-GROUP BY 1 ORDER BY 1;
+-- Aggregate each source to the reporting grain BEFORE joining.
+-- cost_and_usage: multiple line items/day; customer_activity: multiple events/day.
+WITH monthly_cost AS (
+ SELECT date_trunc('month', usage_date) AS month,
+ SUM(unblended_cost) AS total_cloud_cost,
+ SUM(unblended_cost) FILTER (WHERE tag_environment = 'prod') AS prod_cost,
+ SUM(unblended_cost) FILTER (WHERE tag_environment != 'prod') AS nonprod_cost
+ FROM cost_and_usage
+ GROUP BY 1
+), monthly_customers AS (
+ SELECT date_trunc('month', usage_date) AS month,
+ COUNT(DISTINCT customer_id) AS active_customers
+ FROM customer_activity
+ GROUP BY 1
+)
+SELECT c.month, c.total_cloud_cost,
+ COALESCE(a.active_customers, 0) AS active_customers,
+ c.total_cloud_cost / NULLIF(a.active_customers, 0) AS cost_per_customer,
+ c.prod_cost, c.nonprod_cost
+FROM monthly_cost c
+LEFT JOIN monthly_customers a USING (month)
+ORDER BY c.month;
+-- Keep cost-only days/months; no observed active customers means unknown unit cost.
-- Present alongside: allocated %, commitment coverage %, commitment utilization %.
```