Backend Cost Monitoring
When to use
- "Monitor GPU costs"
- "Analyze cost trends (daily/weekly/monthly)"
- "Detect cost anomalies or spikes"
- "Break down API costs by endpoint/model/org"
- "Break down Studio costs by process/workspace"
- "Compare API vs Studio cost distribution"
- "Investigate cost-per-request efficiency drift"
- "Monitor GPU utilization and idle costs"
- "Alert on cost budget breaches"
- "Day-over-day or week-over-week cost comparisons"
Steps
1. Gather Requirements
Ask the user:
- What to monitor: Total costs, cost by product/feature, cost efficiency, utilization, anomalies
- Scope: LTX API, LTX Studio, or both? Specific endpoint/org/process?
- Time window: Daily, weekly, monthly? How far back?
- Analysis type: Trends, comparisons (DoD/WoW), anomaly detection, breakdowns
- Alert threshold (if setting up alerts): Absolute ($X/day) or relative (spike > X% vs baseline)
2. Read Shared Knowledge
Before writing SQL:
shared/product-context.md — LTX products and business context
shared/bq-schema.md — GPU cost table schema (lines 418-615)
shared/metric-standards.md — GPU cost metric patterns (section 13)
shared/event-registry.yaml — Feature events (if analyzing feature-level costs)
shared/gpu-cost-query-templates.md — 11 production-ready SQL queries
shared/gpu-cost-analysis-patterns.md — Analysis workflows and benchmarks
Key learnings:
- Table:
ltx-dwh-prod-processed.gpu_costs.gpu_request_attribution_and_cost
- Partitioned by
dt (DATE) — always filter for performance
cost_category: inference (requests), idle, overhead, unused
- Total cost =
row_cost + attributed_idle_cost + attributed_overhead_cost (inference rows only)
- For infrastructure cost:
SUM(row_cost) across all categories
3. Run Query Templates
If user didn't specify anything: Run all 11 query templates from shared/gpu-cost-query-templates.md to provide comprehensive cost overview.
If user specified specific analysis: Select appropriate template:
| User asks... |
Use template |
| "What are total costs?" |
Daily Total Cost (API + Studio) |
| "Break down API costs" |
API Cost by Endpoint & Model |
| "Break down Studio costs" |
Studio Cost by Process |
| "Yesterday vs day before" |
Day-over-Day Comparison |
| "This week vs last week" |
Week-over-Week Comparison |
| "Detect cost spikes" |
Anomaly Detection (Z-Score) |
| "GPU utilization breakdown" |
Utilization by Cost Category |
| "Cost efficiency by model" |
Cost per Request by Model |
| "Which orgs cost most?" |
API Cost by Organization |
See shared/gpu-cost-query-templates.md for all 11 query templates.
4. Execute Query
Run query using:
bq --project_id=ltx-dwh-explore query --use_legacy_sql=false --format=pretty "
<query>
"
Or use BigQuery console with project ltx-dwh-explore.
5. Analyze Results
For cost trends:
- Compare current period vs baseline (7-day avg, prior week, prior month)
- Calculate % change and flag significant shifts (>15-20%)
For anomaly detection:
- Flag days with Z-score > 2 (cost or volume deviates > 2 std devs from rolling avg)
- Investigate root cause: specific endpoint/model/org, error rate spike, billing type change
For breakdowns:
- Identify top cost drivers (endpoint, model, org, process)
- Calculate cost per request to spot efficiency issues
- Check failure costs (wasted spend on errors)
6. Present Findings
Format results with:
- Summary: Key finding (e.g., "GPU costs spiked 45% yesterday")
- Root cause: What drove the change (e.g., "LTX API /v1/text-to-video requests +120%")
- Breakdown: Top contributors by dimension
- Recommendation: Action to take (investigate org X, optimize model Y, alert team)
7. Set Up Alert (if requested)
For ongoing monitoring:
- Save SQL query
- Set up in BigQuery scheduled query or Hex Thread
- Configure notification threshold
- Route alerts to Slack channel or Linear issue
Schema Reference
For detailed table schema including all dimensions, columns, and cost calculations, see references/schema-reference.md.
Reference Files
| File |
Read when |
references/schema-reference.md |
GPU cost table dimensions, columns, and cost calculations |
shared/bq-schema.md |
Understanding GPU cost table schema (lines 418-615) |
shared/metric-standards.md |
GPU cost metric SQL patterns (section 13) |
shared/gpu-cost-query-templates.md |
Selecting query template for analysis (11 production-ready queries) |
shared/gpu-cost-analysis-patterns.md |
Interpreting results, workflows, benchmarks, investigation playbooks |
Rules
Query Best Practices
- DO always filter on
dt partition column for performance
- DO filter
cost_category = 'inference' for request-level analysis
- DO exclude Lightricks team requests with
is_lt_team IS FALSE for customer-facing cost analysis
- DO include LT team requests only when analyzing total infrastructure spend or debugging
- DO use
ltx-dwh-explore as execution project
- DO calculate cost per request with
SAFE_DIVIDE to avoid division by zero
- DO compare against baseline (7-day avg, prior period) for trends
- DO round cost values to 2 decimal places for readability
Cost Calculation
- DO sum all three cost columns (row_cost + attributed_idle + attributed_overhead) for fully loaded cost per request
- DO use
SUM(row_cost) across all rows for total infrastructure cost
- DO NOT sum row_cost + attributed_* across all cost_categories (double-counting)
- DO NOT mix inference and non-inference rows in same aggregation without filtering
Analysis
- DO flag anomalies with Z-score > 2 (cost or volume deviation > 2 std devs)
- DO investigate failure costs (wasted spend on errors)
- DO break down by endpoint/model for API, by process for Studio
- DO check cost per request trends to spot efficiency degradation
- DO validate results against total infrastructure spend
Alerts
- DO set thresholds based on historical baseline, not absolute values
- DO alert engineering team for cost spikes > 30% vs baseline
- DO include cost breakdown and root cause in alerts
- DO route API cost alerts to API team, Studio alerts to Studio team
1---2name: be-cost-monitoring3description: Monitor and analyze backend GPU costs for LTX API and LTX Studio. Use when analyzing cost trends, detecting anomalies, breaking down costs by endpoint/model/org/process, monitoring utilization, or investigating cost efficiency drift.4---5
6# Backend Cost Monitoring
7
8## When to use
9
10- "Monitor GPU costs"
11- "Analyze cost trends (daily/weekly/monthly)"
12- "Detect cost anomalies or spikes"
13- "Break down API costs by endpoint/model/org"
14- "Break down Studio costs by process/workspace"
15- "Compare API vs Studio cost distribution"
16- "Investigate cost-per-request efficiency drift"
17- "Monitor GPU utilization and idle costs"
18- "Alert on cost budget breaches"
19- "Day-over-day or week-over-week cost comparisons"
20
21## Steps
22
23### 1. Gather Requirements
24
25Ask the user:
26- **What to monitor**: Total costs, cost by product/feature, cost efficiency, utilization, anomalies
27- **Scope**: LTX API, LTX Studio, or both? Specific endpoint/org/process?
28- **Time window**: Daily, weekly, monthly? How far back?
29- **Analysis type**: Trends, comparisons (DoD/WoW), anomaly detection, breakdowns
30- **Alert threshold** (if setting up alerts): Absolute ($X/day) or relative (spike > X% vs baseline)
31
32### 2. Read Shared Knowledge
33
34Before writing SQL:
35- **`shared/product-context.md`** — LTX products and business context
36- **`shared/bq-schema.md`** — GPU cost table schema (lines 418-615)
37- **`shared/metric-standards.md`** — GPU cost metric patterns (section 13)
38- **`shared/event-registry.yaml`** — Feature events (if analyzing feature-level costs)
39- **`shared/gpu-cost-query-templates.md`** — 11 production-ready SQL queries
40- **`shared/gpu-cost-analysis-patterns.md`** — Analysis workflows and benchmarks
41
42Key learnings:
43- Table: `ltx-dwh-prod-processed.gpu_costs.gpu_request_attribution_and_cost`
44- Partitioned by `dt` (DATE) — always filter for performance
45- `cost_category`: inference (requests), idle, overhead, unused
46- Total cost = `row_cost + attributed_idle_cost + attributed_overhead_cost` (inference rows only)
47- For infrastructure cost: `SUM(row_cost)` across all categories
48
49### 3. Run Query Templates
50
51**If user didn't specify anything:** Run all 11 query templates from `shared/gpu-cost-query-templates.md` to provide comprehensive cost overview.
52
53**If user specified specific analysis:** Select appropriate template:
54
55| User asks... | Use template |
56|-------------|-------------|
57| "What are total costs?" | Daily Total Cost (API + Studio) |
58| "Break down API costs" | API Cost by Endpoint & Model |
59| "Break down Studio costs" | Studio Cost by Process |
60| "Yesterday vs day before" | Day-over-Day Comparison |
61| "This week vs last week" | Week-over-Week Comparison |
62| "Detect cost spikes" | Anomaly Detection (Z-Score) |
63| "GPU utilization breakdown" | Utilization by Cost Category |
64| "Cost efficiency by model" | Cost per Request by Model |
65| "Which orgs cost most?" | API Cost by Organization |
66
67See `shared/gpu-cost-query-templates.md` for all 11 query templates.
68
69### 4. Execute Query
70
71Run query using:
72```bash
73bq --project_id=ltx-dwh-explore query --use_legacy_sql=false --format=pretty "
74<query>
75"
76```
77
78Or use BigQuery console with project `ltx-dwh-explore`.
79
80### 5. Analyze Results
81
82**For cost trends:**
83- Compare current period vs baseline (7-day avg, prior week, prior month)
84- Calculate % change and flag significant shifts (>15-20%)
85
86**For anomaly detection:**
87- Flag days with Z-score > 2 (cost or volume deviates > 2 std devs from rolling avg)
88- Investigate root cause: specific endpoint/model/org, error rate spike, billing type change
89
90**For breakdowns:**
91- Identify top cost drivers (endpoint, model, org, process)
92- Calculate cost per request to spot efficiency issues
93- Check failure costs (wasted spend on errors)
94
95### 6. Present Findings
96
97Format results with:
98- **Summary**: Key finding (e.g., "GPU costs spiked 45% yesterday")
99- **Root cause**: What drove the change (e.g., "LTX API /v1/text-to-video requests +120%")
100- **Breakdown**: Top contributors by dimension
101- **Recommendation**: Action to take (investigate org X, optimize model Y, alert team)
102
103### 7. Set Up Alert (if requested)
104
105For ongoing monitoring:
1061. Save SQL query
1072. Set up in BigQuery scheduled query or Hex Thread
1083. Configure notification threshold
1094. Route alerts to Slack channel or Linear issue
110
111## Schema Reference
112
113For detailed table schema including all dimensions, columns, and cost calculations, see `references/schema-reference.md`.
114
115## Reference Files
116
117| File | Read when |
118|------|-----------|
119| `references/schema-reference.md` | GPU cost table dimensions, columns, and cost calculations |
120| `shared/bq-schema.md` | Understanding GPU cost table schema (lines 418-615) |
121| `shared/metric-standards.md` | GPU cost metric SQL patterns (section 13) |
122| `shared/gpu-cost-query-templates.md` | Selecting query template for analysis (11 production-ready queries) |
123| `shared/gpu-cost-analysis-patterns.md` | Interpreting results, workflows, benchmarks, investigation playbooks |
124
125## Rules
126
127### Query Best Practices
128
129- **DO** always filter on `dt` partition column for performance
130- **DO** filter `cost_category = 'inference'` for request-level analysis
131- **DO** exclude Lightricks team requests with `is_lt_team IS FALSE` for customer-facing cost analysis
132- **DO** include LT team requests only when analyzing total infrastructure spend or debugging
133- **DO** use `ltx-dwh-explore` as execution project
134- **DO** calculate cost per request with `SAFE_DIVIDE` to avoid division by zero
135- **DO** compare against baseline (7-day avg, prior period) for trends
136- **DO** round cost values to 2 decimal places for readability
137
138### Cost Calculation
139
140- **DO** sum all three cost columns (row_cost + attributed_idle + attributed_overhead) for fully loaded cost per request
141- **DO** use `SUM(row_cost)` across all rows for total infrastructure cost
142- **DO NOT** sum row_cost + attributed_* across all cost_categories (double-counting)
143- **DO NOT** mix inference and non-inference rows in same aggregation without filtering
144
145### Analysis
146
147- **DO** flag anomalies with Z-score > 2 (cost or volume deviation > 2 std devs)
148- **DO** investigate failure costs (wasted spend on errors)
149- **DO** break down by endpoint/model for API, by process for Studio
150- **DO** check cost per request trends to spot efficiency degradation
151- **DO** validate results against total infrastructure spend
152
153### Alerts
154
155- **DO** set thresholds based on historical baseline, not absolute values
156- **DO** alert engineering team for cost spikes > 30% vs baseline
157- **DO** include cost breakdown and root cause in alerts
158- **DO** route API cost alerts to API team, Studio alerts to Studio team