We are designing a runtime cost dashboard that ties together experience quality, infrastructure usage, and inference spend.
The dashboard should provide insights into:
Experience Quality: Metrics like latency, error rates, user satisfaction (if available), etc.
Infrastructure Usage: CPU, memory, disk I/O, network I/O, etc.
Inference Spend: Cost per inference, total spend, cost per request, etc.
We assume we are in a cloud environment and have access to:
Monitoring data (e.g., from Prometheus, CloudWatch, etc.)
Cost data from cloud provider (e.g., AWS Cost Explorer, GCP Billing, etc.)
Logs from inference services (e.g., model serving, API gateway)
We need to design a system that can collect, aggregate, and display this data in near real-time.
Steps:
Data Collection:
Infrastructure metrics: collected via node exporters, cloud provider metrics, etc.
Experience quality: from application logs, APM tools (like New Relic, Datadog), or custom logs.
Time-series database for metrics (e.g., Prometheus, InfluxDB, TimescaleDB).
Data warehouse for billing data (e.g., BigQuery, Redshift, Snowflake) and possibly for long-term analytics.
Data Processing:
We need to join metrics from different sources by time and by service/instance.
We might need to aggregate by service, model, region, etc.
Visualization:
Dashboard tool (e.g., Grafana, Tableau, Superset) that can query the data sources and display.
Alerting (optional but good to have):
Set up alerts for anomalies (e.g., cost spike, latency increase, etc.)
Let's break down the components:
Component 1: Metrics Collection
Use existing monitoring agents (e.g., Prometheus node exporter, cloudwatch agent) for infra.
For experience quality, we might have application metrics (e.g., from a web framework) and business metrics (e.g., number of successful/failed requests).
For inference spend, we can get detailed billing data (by service, by tag) and then allocate to inference services based on usage.
Component 2: Data Aggregation and Storage
We can use Prometheus for metrics (infra and application) because it's good for time-series and can handle high cardinality if needed.
For billing, we can export cloud billing data to a data warehouse (e.g., BigQuery) and then join with Prometheus data on service name/instance.
Alternatively, we can use a single time-series database that can handle both metrics and events, but billing data is usually daily and not at the same granularity.
Proposed:
Prometheus for metrics (infra and application) with retention for a few weeks.
BigQuery for billing data (with long-term storage) and for running complex joins.
We can set up a pipeline that:
a) Exports Prometheus metrics to a long-term storage (like Thanos or Cortex) if we want to keep them for longer.
b) Exports cloud billing data to BigQuery (daily).
c) Then, in BigQuery, we can create a materialized view that joins the two by service and time.
However, note that Prometheus data is at a higher frequency (e.g., every 15s) and billing data is daily. We might need to aggregate Prometheus data to daily averages for joining.
Alternatively, we can keep the two separate and just use the dashboard to query both and display side by side, or use a tool that can query multiple data sources.
Component 3: Dashboard
We can use Grafana because it supports multiple data sources (Prometheus, BigQuery, etc.) and can create dashboards that combine them.
Example dashboard panels:
Panel 1: Total daily inference spend (from billing) over time.
Panel 2: Average latency per request (from Prometheus) over time.
Panel 3: Total requests per day (from Prometheus) over time.
Panel 4: Cost per request (computed as total spend / total requests) over time.
Panel 5: Infrastructure usage (CPU, memory) for inference services.
Panel 6: Error rate (from Prometheus) over time.
We can also break down by service, model, region, etc.
Component 4: Cost Allocation
To get inference spend per service, we need to tag our resources (e.g., EC2 instances, Kubernetes pods) with the service name and model name.
Then, in the billing data, we can filter by those tags and also by the service (e.g., SageMaker, Vertex AI, etc.).
Alternatively, if we use a managed inference service (like SageMaker), we can get cost per endpoint.
Steps for cost allocation:
a) Tag all resources (compute, storage, network) used by inference services.
b) In the billing data, we have line items with tags. We can sum by tag (service, model, etc.) to get the cost for each inference service.
However, note that some costs might be shared (e.g., a shared database). We might need to use a cost allocation model (e.g., by CPU usage, by request count) to split shared costs.
Component 5: Anomaly Detection
We can set up alerts in Grafana or use a separate system (e.g., Prometheus Alertmanager) to alert on:
Cost spikes (e.g., today's cost is 2x the average of last 7 days)
Latency increase (e.g., p95 latency increased by 50%)
Error rate increase (e.g., error rate > 1%)
Implementation Steps:
Set up monitoring for infrastructure and application metrics (if not already).
For Kubernetes, use kube-state-metrics and node exporter.
For application, expose metrics in Prometheus format.
Set up cloud billing export to BigQuery (or equivalent).
In BigQuery, create a view that aggregates billing data by day and by the tags we care about (service, model, environment, etc.).
In Prometheus, we might already have metrics like:
node_cpu_seconds_total, node_memory_MemAvailable_bytes, etc.
We need to aggregate Prometheus data by day and by service (and model if we have that label) to join with billing.
Example PromQL for daily requests per service:
sum by (service) (increase(http_requests_total[1d]))
But note: we might have multiple models in the same service. We need to label by model as well.
So we need to make sure our application metrics are labeled with model name (if multiple models) or we can have separate services per model.
In Grafana, we can create a dashboard that:
Uses BigQuery as a data source for the billing data (daily aggregates by service and model).
Uses Prometheus as a data source for the metrics (also daily aggregates by service and model).
Then, we can create a panel that shows:
R = daily request count for the same service and model (from Prometheus)
Implementation Plan:
Phase 1: Basic Dashboard
Set up Prometheus and Grafana.
Instrument application to expose metrics (requests, latency, errors) with labels: service, model (if applicable).
Set up cloud billing export to BigQuery.
In BigQuery, create a view that aggregates billing by day, service, and model (if we have model tag on resources).
However, note: in cloud billing, we might not have a tag for model. We might only have service (e.g., the Kubernetes namespace or the EC2 instance name).
So we might need to map:
code
Billing data (by resource) -> resource is used by a service (via tags) -> service runs one or more models.
We can do:
code
Step 1: From billing data, get cost by resource (by day).
Step 2: From Prometheus, get the total requests per model (by day) and also the total requests per service (by day).
Step 3: Then, for each resource, we know which service it belongs to (from tags). Then, we split the resource cost by the model's proportion of requests in that service.
But wait, if a resource (e.g., a node) runs multiple services, then we need to split by service first.
This is getting complex.
Alternatively, we can allocate cost at the service level first:
code
Total cost for a service = sum of costs of resources tagged with that service.
Then, within the service, split by model based on request count.
This requires:
- We have the model label in the application metrics (so we can get model_requests and total_service_requests).
- We have the service tag on the resources (so we can get total_service_cost from billing).
But what if a resource is shared by multiple services? Then we need to split the resource cost by the services' usage (CPU, memory, or requests). This is even more complex.
Given the complexity, we might start with:
code
One model per service, and one service per resource set (e.g., a dedicated node or a dedicated set of pods).
Then, we can directly map:
code
billing data (by resource) -> resource is tagged with service -> service runs one model.
Then, cost for the model = cost for the service.
And then we can also track:
code
cost per request = (service cost) / (number of requests for the service).
This is simpler and we can extend later.
So, for Phase 1, we assume:
Each inference service (endpoint) is dedicated to one model.
We tag all resources (VMs, disks, load balancers, etc.) with the service name (and environment, etc.)
We have application metrics for the service (request count, latency, errors) with the service label.
Then:
code
In BigQuery, we create a view:
SELECT
DATE(usage_start_time) as day,
service_tags.value as service,
SUM(cost) as daily_cost
FROM `billing_table`
WHERE service_tags.key = 'service'
GROUP BY day, service
In Prometheus, we can query:
sum by (service) (increase(http_requests_total[1d]))
Then, in Grafana, we can join these two by day and service (using the BigQuery and Prometheus data sources) and compute:
cost_per_request = daily_cost / request_count
And also show:
latency (p95) for the service.
error_rate = sum by (service) (increase(http_requests_total{status=~"5.."}[1d])) / sum by (service) (increase(http_requests_total[1d]))
15. We can also show:
code
- Infrastructure usage: we can query Prometheus for node metrics and filter by node labels that match the service (if we have such labels).
For example, if we run on Kubernetes and label nodes with the service they run, then:
node_cpu_seconds_total{node=~"$node"} ... but we want by service.
Alternatively, we can use kube-state-metrics to get:
kube_pod_container_resource_limits_cpu_cores{pod=~"$service-.*"}
But this might not be straightforward.
16. Given the time, we can start with:
code
Dashboard panels:
Row 1: Overall
- Total daily cost (from billing)
- Total daily requests (from Prometheus)
- Average cost per request (computed)
Row 2: Per service breakdown (using variable for service)
- Cost per request for the selected service
- Latency (p50, p95, p99) for the selected service
- Error rate for the selected service
- CPU and memory usage for the nodes running the selected service (if we can map)
Row 3: Table of all services with:
- Service name
- Daily cost
- Daily requests
- Cost per request
- p95 latency
- Error rate
17. We can also add:
code
- Alerts: if cost per request increases by X% or if latency increases by Y%.
18. Implementation steps:
code
Step 1: Ensure all resources are tagged with 'service' (and optionally 'model' if we want to break down by model later).
Step 2: Set up cloud billing export to BigQuery and create the view for daily cost by service.
Step 3: Set up Prometheus with application metrics (with service label) and node metrics (with node labels that include service if possible).
Step 4: In Grafana, add BigQuery and Prometheus data sources.
Step 5: Create a dashboard with:
Variables:
- $service: query from Prometheus: label_values(http_requests_total, service)
Panel 1 (Overall total cost):
Query BigQuery: SELECT SUM(daily_cost) FROM view WHERE day = $__timeGroup()
Panel 2 (Overall total requests):
Query Prometheus: sum(http_requests_total)
Panel 3 (Overall cost per request):
Expression: Panel1 / Panel2
Panel 4 (Per service cost per request):
Query BigQuery: daily_cost for the selected service (and day)
Query Prometheus: request count for the selected service (and day)
Expression: BigQuery result / Prometheus result
Panel 5 (Per service latency):
Query Prometheus: histogram_quantile(0.95, sum by (le, service) (rate(http_request_duration_seconds_bucket[1d])))
Panel 6 (Per service error rate):
Query Prometheus:
error_requests = sum by (service) (increase(http_requests_total{status=~"5.."}[1d]))
total_requests = sum by (service) (increase(http_requests_total[1d]))
error_rate = error_requests / total_requests
Panel 7 (Per service resource usage):
This is tricky. We might need to get the nodes that run the service and then sum their CPU and memory.
If we have a label on the node that matches the service (e.g., node has label `service=my-service`), then:
CPU: sum by (service) (rate(node_cpu_seconds_total{mode!="idle", node=~"$node"}[1d]))
But we want by service, so we need to filter nodes by service label.
Alternatively, if we are on Kubernetes, we can use:
kube_pod_container_resource_limits_cpu_cores{pod=~"$service-.*"}
But this gives the limit, not the usage.
We might use:
container_cpu_usage_seconds_total{pod=~"$service-.*"}
But we need to have the container metrics.
Given the complexity, we might leave this for later or use a simpler metric:
Number of pods for the service: count(kube_pod_info{pod=~"$service-.*"})
Step 6: Test and iterate.
19. Extensions:
code
- Break down by model (if we have multiple models per service, we need to adjust the metrics and billing allocation).
- Break down by region.
- Include network costs, storage costs, etc.
- Include cost of managed services (like SageMaker) that might not be tagged with the same service tag.
20. Challenges:
code
- Tagging consistency: we need to ensure every resource is tagged with the service.
- If we use a shared resource (like a load balancer) for multiple services, we need to split the cost. We can split by request count or by data transfer.
Example for load balancer:
We have a load balancer that routes to multiple services.
In the billing data, the load balancer cost is not broken down by service.
We can split by the number of requests (or by data transfer) that each service gets.
We can get the request count per service from the load balancer logs (if available) or from the application metrics (if the load balancer passes the request).
Then:
cost_service = (total_lb_cost * (service_requests / total_requests_to_lb))
This requires:
a) We have the total requests to the load balancer (maybe from the load balancer metrics) and per-service request counts.
b) We can get the load balancer cost from billing (by the load balancer resource).
So we might need to create a separate view for load balancer cost and then allocate.
21. Given the complexity, we might start with:
code
- Dedicated resources per service (no sharing) for inference.
And then gradually handle shared resources.
22. Conclusion:
code
We can build a basic dashboard with:
Data sources: Prometheus and BigQuery (for billing).
Assumptions:
- Each service has its own dedicated resources (or we can allocate shared resources by a simple method like equal split or by request count if we have the data).
Dashboard:
- Overall metrics (total cost, total requests, average cost per request).
- Per service: cost per request, latency, error rate, and resource usage (if available).
- Table of all services.
Then, we can extend to:
- Per model (if we have multiple models per service and we can label by model in the application metrics).
- Shared resource cost allocation.
We can also add:
- Forecasts: predict next month's cost based on current usage.
- Recommendations: e.g., if latency is high and cost is high, maybe we need a bigger instance or a different model.
23. Code for the BigQuery view (assuming we have a tag with key 'service'):
code
CREATE OR REPLACE VIEW `project.dataset.daily_service_cost` AS
SELECT
DATE(usage_start_time) as day,
service_tags.value as service,
SUM(cost) as daily_cost
FROM `project.dataset.gcp_billing_export_v1_001234`
CROSS JOIN UNNEST(resource_tags) as service_tags
WHERE service_tags.key = 'service'
GROUP BY day, service
24. Note: The billing table structure might be different. Adjust accordingly.
For Prometheus, we assume we have:
http_requests_total (counter) with labels: service, method, path, status
http_request_duration_seconds (histogram) with labels: service, method, path
In Grafana, we can use the following queries:
Panel: Total daily requests
Query: sum(http_requests_total)
But note: this is a counter, so we need to use increase() for a range.
Actually, in Grafana, if we set the panel to show the last 1 day, then:
If we:
→ Switch 30% traffic from claude-3-opus to gpt-4-turbo
→ Increase cache TTL from 5min → 30min
→ Move from p3.2xlarge → g5.2xlarge
Then:
• Savings: $48K/month
• Latency impact: +120ms
• Quality delta: -0.2
B. Model Retirement Recommendations
sql
-- Models with high cost and declining usage
SELECT
model_name,
AVG(cost_per_request) as avg_cost,
COUNT(*) as days_active,
SUM(request_count) as total_requests,
(MAX(date) - MIN(date)) as lifetime_days
FROM inference_cost_facts
WHERE date >= '2024-01-01'
GROUP BY model_name
HAVING
avg_cost > (SELECT AVG(cost_per_request)*1.5 FROM ...)
AND total_requests < 1000
AND lifetime_days > 90;
C. Quality-Cost Trade-off Curve
code
Plot:
X = Cost/1k tokens
Y = User satisfaction score
Show Pareto frontier:
"Best quality for given cost tier"
"Lowest cost for given quality tier"
Tagging Policy: All resources must have service, model, env, team tags
Cost Center Mapping: Auto-allocate to teams/departments
Carbon Footprint:Link to Cloud Carbon Footprint tool for emissions tracking
Budget Alerts: Monthly budget per team with progressive alerts (80%, 90%, 100%)
Key Metrics to Track
Metric
Target
Why Important
Cost/Quality Ratio
< $0.01 per 0.1 satisfaction point
Balances cost & UX
GPU Utilization
60-80%
Avoid overprovisioning
Cache Hit Rate
>70% for hot models
Reduces compute cost
Cold Start %
<5%
Impacts UX & cost
Cost/VIP Interaction
< $0.10
Monitor high-value users
This architecture provides actionable insights, not just data. The key is linking technical metrics (latency, errors) with business outcomes (user satisfaction) and financial impact (cost per interaction). Start with Phase 1, then progressively add quality dimensions and advanced analytics.
Latency (p50, p95, p99) for that service and model.
Error rate (status 5xx or 4xx) for that service and model.
We can also break down by region if we have multiple regions.
For infrastructure usage, we can show CPU and memory usage for the nodes running the inference service.
We can label the node metrics with the service (if running on Kubernetes, we can use node labels or pod labels to map to service).
If we have multiple models per service (e.g., a single endpoint that routes to different models), we might need to break down by model in the application metrics.
This might require:
The application to label requests with the model name (if we are doing model-based routing).
Or, we can have separate endpoints per model.
If we are using a managed service (like SageMaker) and we have multiple models in the same endpoint, then we might not have per-model metrics at the application level. In that case, we might need to rely on the managed service's metrics (if available) or instrument at the model level.
We might also want to track:
Number of instances (if auto-scaling) for the inference service.
Model load time (if applicable).
We can also track:
Cost per model: by allocating the billing data (which is by resource) to the model based on the resource usage (e.g., if a model uses 50% of the endpoint's requests, then 50% of the endpoint's cost).
But note: the billing data might be at the resource level (e.g., EC2 instance) and we have multiple models on the same instance.
We can do:
cost_per_model = (total_cost_of_resource * (model_requests / total_requests_on_resource)) per day.
This requires:
a) We know which resource (instance, pod) is serving which model and how many requests each model gets.
If we are using Kubernetes, we can get:
Pod to service mapping (via labels).
Service to model mapping (if one service per model, then easy; if multiple models per service, then we need the model label in the request).
Alternatively, if we are using a model server that exposes per-model metrics (like Triton), then we can get per-model request counts from the server.
Given the complexity, we might start by having one model per service (or endpoint) and then extend.
But our day in BigQuery is a DATE, so we need to cast:
WHERE day BETWEEN TIMESTAMP(__timeFrom()) AND TIMESTAMP(__timeTo())
Actually, $__timeFrom() returns a string in ISO format, so we can do:
WHERE day BETWEEN TIMESTAMP(__timeFrom()) AND TIMESTAMP(__timeTo())
But note: the day in BigQuery is a DATE, and we are comparing with TIMESTAMP. We can do:
WHERE day BETWEEN DATE(__timeFrom()) AND DATE(__timeTo())
Alternatively, we can set the BigQuery query to use:
WHERE day >= TIMESTAMP(__timeFrom()) AND day <= TIMESTAMP(__timeTo())
But then we are comparing DATE with TIMESTAMP, which might not work.
Let's adjust:
We have a DATE column. We want to compare with the dashboard's time range (which is in timestamps).
We can do:
WHERE day BETWEEN TIMESTAMP(__timeFrom()) AND TIMESTAMP(__timeTo())
But BigQuery will implicitly convert the DATE to TIMESTAMP at 00:00:00 UTC.
Alternatively, we can do:
WHERE day >= TIMESTAMP(__timeFrom()) AND day <= TIMESTAMP(__timeTo())
This will work because when comparing DATE and TIMESTAMP, the DATE is cast to TIMESTAMP at 00:00:00.
But note: if the dashboard time range is from 2023-10-01T00:00:00Z to 2023-10-02T00:00:00Z, then we want to include 2023-10-01 and 2023-10-02?
Actually, if we set the dashboard to show the last 1 day, then __timeFrom() is 24 hours ago and __timeTo() is now.
We want to show the day that overlaps with the time range.
Since our billing data is by day (in UTC), we want to show the day of __timeFrom() to the day of __timeTo().
So:
WHERE day BETWEEN TIMESTAMP(__timeFrom()) AND TIMESTAMP(__timeTo())
This will convert the timestamps to dates and then compare.
Alternatively, we can do:
WHERE day >= TIMESTAMP(__timeFrom()) AND day <= TIMESTAMP(__timeTo())
Same.
However, note that the BigQuery view already aggregates by day, so we are safe.
Let's write the BigQuery query for the panel that shows daily cost for a service:
SELECT
day,
daily_cost
FROM project.dataset.daily_service_cost
WHERE service = 'service′ANDdayBETWEENTIMESTAMP(__timeFrom()) AND TIMESTAMP($__timeTo())
ORDER BY day
For Prometheus, we don't need to filter by day because we are using the range vector [1d] and the dashboard time range will adjust the step.
Actually, in Grafana, when we set the panel to use the dashboard time range, the query will be adjusted.
For example, if the dashboard time range is 30d, then the increase(http_requests_total[1d]) will be computed for each 1d step over the 30d.
But we want the daily total, so we set the panel's resolution to 1d.
In Grafana, we can set the panel's "Min interval" to 1d.
Alternatively, we can use:
code
sum by (service) (increase(http_requests_total[${__range}s]))
But then we are getting the total over the entire range, not per day.
We want per day, so we set the panel to use a 1d step and then:
code
sum by (service) (increase(http_requests_total[1d]))
And then set the panel to show the values at each 1d step.
Given the complexity, we might start with a fixed 1d window and then adjust.
Alternatively, we can use:
sum by (service) (increase(http_requests_total[1d]))
and set the panel's time range to 1d, and then use the dashboard's time range to change the day.
But we want to see the trend over multiple days.
So we set the panel to:
code
Query: sum by (service) (increase(http_requests_total[1d]))
And then set the panel's time range to the dashboard's time range, but the step to 1d.
In Grafana, we can set:
code
Min interval: 1d
Then, the query will be evaluated every 1d over the dashboard's time range.
Similarly for latency:
histogram_quantile(0.95, sum by (le, service) (rate(http_request_duration_seconds_bucket[1d])))
This will give the 95th percentile latency over the last 1d, and we evaluate every 1d.
For the error rate:
sum by (service) (increase(http_requests_total{status=~"5.."}[1d]))
/
sum by (service) (increase(http_requests_total[1d]))
And set the step to 1d.
Now, for the overall panels (not per service) we remove the by (service).
For the cost per request panel (per service) we need to combine BigQuery and Prometheus.
We can do:
code
In Grafana, we can use transformations to join the two data sources.
Steps:
- Add a BigQuery query that returns: day, service, daily_cost.
- Add a Prometheus query that returns: day, service, request_count (but note: Prometheus returns a time series, and we are using 1d steps).
Then, we can use the "Outer join" transformation on the fields "day" and "service".
Then, create a new field: cost_per_request = daily_cost / request_count.
However, note that the Prometheus query returns a time series with a value for each day and service, and the BigQuery query does the same.
We can set both queries to return the same time range and step.
Then, we can use the "Merge" transformation by "day" and "service".
But Grafana's transformations might not handle this easily.
Alternatively, we can do:
code
Use a single data source if possible. We can export Prometheus data to BigQuery (via Prometheus to BigQuery exporter) and then do the join in BigQuery.
Then, we have one view in BigQuery that has:
day, service, daily_cost, request_count, latency, error_rate, etc.
Then, we can create a single panel that queries that view and computes cost_per_request.
This might be easier.
So, we can set up:
Export Prometheus metrics to BigQuery (using a tool like Prometheus-to-BigQuery, or via a custom exporter).
Then, in BigQuery, we create a materialized view that:
code
a) Aggregates Prometheus metrics by day and service (and model if needed).
b) Joins with the daily_service_cost view on day and service.
Then, we have:
code
day, service, daily_cost, request_count, p95_latency, error_rate, etc.
Then, we can compute:
code
cost_per_request = daily_cost / request_count
And then we can create a dashboard in Grafana that only uses BigQuery.
Steps for exporting Prometheus to BigQuery:
We can use:
code
- Prometheus BigQuery exporter: https://github.com/GoogleCloudPlatform/prometheus-bigquery-exporter
Or:
- Use a Cloud Function that triggers on Prometheus remote write and writes to BigQuery.
But note: Prometheus data is high cardinality and high frequency. We might want to pre-aggregate.
The exporter can be configured to aggregate by day and service.
Alternatively, we can run a daily batch job that reads from Prometheus (via its API) and writes to BigQuery.
Given the volume, we might do:
code
- Hourly aggregates, then daily.
But for our dashboard, we want daily.
We can set up:
code
- A cron job that runs every hour and aggregates the last hour's data by service and writes to a temporary table, then at the end of the day, we aggregate the whole day.
Alternatively, we can use:
code
- Prometheus recording rules to create daily aggregates (but Prometheus doesn't store long-term, so we need to export the aggregates).
We can set up:
code
- A Prometheus rule that writes the daily increase for each service to a separate time series (using the `record` rule) and then export that time series to BigQuery.
This might be the simplest:
code
Step 1: In Prometheus, create a recording rule:
- record: service:daily_requests:increase
expr: sum by (service) (increase(http_requests_total[1d]))
This will create a new time series that has the daily request count for each service.
Then, we export this time series to BigQuery.
Similarly for latency and error rate.
Then, in BigQuery, we have:
code
Table: `prometheus_daily_metrics`
Columns: timestamp, metric, labels (service), value
We can pivot this table to have columns for each metric.
Then, join with the billing view.
Given the complexity, we might start with the two data sources (Prometheus and BigQuery) and use Grafana's transformations to join.
But note: Grafana transformations are done in memory and might be slow for large data.
Let's stick to:
Option A: Two data sources and join in Grafana (if the data volume is low, i.e., few services and 30 days).
Option B: Export Prometheus to BigQuery and do the join in BigQuery.
I think Option B is more scalable and we can run complex queries.
We'll go with Option B.
Steps:
code
a) Set up Prometheus recording rules for daily aggregates:
- service:daily_requests:increase
- service:daily_latency_95:histogram_quantile
- service:daily_error_rate:calculation
b) Export these recording rules to BigQuery.
c) In BigQuery, create a view that:
SELECT
DATE(timestamp) as day,
labels.service as service,
MAX(IF(metric='service:daily_requests:increase', value, NULL)) as request_count,
MAX(IF(metric='service:daily_latency_95:histogram_quantile', value, NULL)) as p95_latency,
MAX(IF(metric='service:daily_error_rate:calculation', value, NULL)) as error_rate
FROM `prometheus_daily_metrics`
WHERE metric IN ('service:daily_requests:increase', 'service:daily_latency_95:histogram_quantile', 'service:daily_error_rate:calculation')
GROUP BY day, service
d) Then, join with the billing view:
SELECT
a.day,
a.service,
b.daily_cost,
a.request_count,
a.p95_latency,
a.error_rate,
b.daily_cost / a.request_count as cost_per_request
FROM `project.dataset.prometheus_daily_aggregates` a
LEFT JOIN `project.dataset.daily_service_cost` b
ON a.day = b.day AND a.service = b.service
e) Then, use this final view in Grafana.
For the error rate recording rule:
We can compute:
code
error_rate = sum by (service) (increase(http_requests_total{status=~"5.."}[1d])) / sum by (service) (increase(http_requests_total[1d]))
But in Prometheus, we can record:
code
record: service:daily_error_rate:calculation
expr: sum by (service) (increase(http_requests_total{status=~"5.."}[1d])) / sum by (service) (increase(http_requests_total[1d]))
This will give a gauge between 0 and 1.
For the latency:
record: service:daily_latency_95:histogram_quantile
expr: histogram_quantile(0.95, sum by (le, service) (rate(http_request_duration_seconds_bucket[1d])))
But note: the rate function is for per second, and we are using [1d] to get the rate over 1 day? Actually, we want the 95th percentile over the last day.
We can do:
code
histogram_quantile(0.95, sum by (le, service) (increase(http_request_duration_seconds_bucket[1d])))
This will give the 95th percentile of the latency distribution over the last day.
We can set these recording rules to run every day and store the result.
A table panel showing all services and these metrics for the selected day.
Time series panels for each metric over time.
We can also break down by model if we add a model label to the recording rules and the billing tags.
This plan is scalable and we can add more metrics easily.
Let's write the final view in BigQuery:
CREATE OR REPLACE VIEW project.dataset.inference_dashboard AS
WITH prometheus_daily AS (
SELECT
DATE(timestamp) as day,
labels.service as service,
MAX(IF(metric='service:daily_requests:increase', value, NULL)) as request_count,
MAX(IF(metric='service:daily_latency_95:histogram_quantile', value, NULL)) as p95_latency,
MAX(IF(metric='service:daily_error_rate:calculation', value, NULL)) as error_rate
FROM project.dataset.prometheus_daily_metrics
WHERE metric IN ('service:daily_requests:increase', 'service:daily_latency_95:histogram_quantile', 'service:daily_error_rate:calculation')
GROUP BY day, service
),
billing_daily AS (
SELECT
DATE(usage_start_time) as day,
service_tags.value as service,
SUM(cost) as daily_cost
FROM project.dataset.gcp_billing_export_v1_001234
CROSS JOIN UNNEST(resource_tags) as service_tags
WHERE service_tags.key = 'service'
GROUP BY day, service
)
SELECT
p.day,
p.service,
b.daily_cost,
p.request_count,
p.p95_latency,
p.error_rate,
b.daily_cost / p.request_count as cost_per_request
FROM prometheus_daily p
LEFT JOIN billing_daily b
ON p.day = b.day AND p.service = b.service
We assume that the billing data and Prometheus data are for the same projects and services.
We also assume that the service tag in billing and the service label in Prometheus are the same.
We might have services that are in Prometheus but not in billing (if they are not tagged or not incurring cost) and vice versa.
We use LEFT JOIN so we keep all Prometheus services.
Now, in Grafana, we can query this view.
Example panel: table of last 7 days for a service:
code
SELECT
day,
daily_cost,
request_count,
p95_latency,
error_rate,
cost_per_request
FROM `project.dataset.inference_dashboard`
WHERE service = '${service}'
AND day BETWEEN TIMESTAMP($__timeFrom()) AND TIMESTAMP($__timeTo())
ORDER BY day
We can also create a time series panel for cost_per_request:
code
SELECT
day,
cost_per_request
FROM `project.dataset.inference_dashboard`
WHERE service = '${service}'
AND day BETWEEN TIMESTAMP($__timeFrom()) AND TIMESTAMP($__timeTo())
ORDER BY day
And similarly for other metrics.
We can also create a panel that shows the top 5 services by cost per request.
SELECT
service,
AVG(cost_per_request) as avg_cost_per_request
FROM project.dataset.inference_dashboard
WHERE day BETWEEN TIMESTAMP(__timeFrom()) AND TIMESTAMP(__timeTo())
GROUP BY service
ORDER BY avg_cost_per_request DESC
LIMIT 5
We can also show:
Total cost for the selected time range.
Total requests for the selected time range.
This dashboard will give us a good overview.
We can extend to:
Break down by model: if we add model label to the recording rules and the billing tags.
Then, in the Prometheus recording rules, we do:
code
sum by (service, model) (increase(http_requests_total[1d]))
and then in the view, we group by service and model.
Similarly, in the billing, we need to have the model tag on the resources.
But if we don't have model tag on resources, we can only break down by service and then by model in the application metrics.
Then, we can allocate the service cost to models by request count.
WITH prometheus_daily AS (
SELECT
DATE(timestamp) as day,
labels.service as service,
labels.model as model,
MAX(IF(metric='service:daily_requests:increase', value, NULL)) as request_count,
...
...
)
Then, we need the service cost (from billing) and then compute:
day, service, model, cost_per_model, request_count, etc.
Given the time, we might start without model breakdown and add later.
Conclusion:
We have designed a system that:
code
- Collects infrastructure and application metrics via Prometheus.
- Collects billing data from cloud provider to BigQuery.
- Uses Prometheus recording rules to pre-aggregate metrics by day and service.
- Exports the recording rules to BigQuery.
- Creates a view in BigQuery that joins the billing and Prometheus data.
- Uses Grafana to visualize the view.
We assume:
code
- Resources are tagged with service.
- Application metrics are labeled with service (and model if needed).
We can extend to:
code
- Model breakdown.
- Shared resource cost allocation.
This dashboard will help us understand:
code
- Which services are expensive per request?
- Which services have high latency?
- Which services have high error rates?
- How do these metrics change over time?
And we can set up alerts on anomalies.
Next steps:
Implement the recording rules in Prometheus.
Set up the export from Prometheus to BigQuery.
Set up the billing export to BigQuery and create the billing view.
Create the final view in BigQuery.
Build the Grafana dashboard.
Then, iterate.
Note: The cost per request might be very small (fractions of a cent) and we might want to show in microdollars.
We can multiply by 1e6 to show in microdollars.
Alternatively, we can show in dollars with more decimal places.
Also, we might want to show:
The breakdown of the cost (compute, storage, network) per service.
We can extend the billing view to break down by cost type.
In the billing data, we have a column for service description (or sku) that tells us what the cost is for.
We can group by that and then show a stacked bar chart of cost by type (compute, storage, network) for each service.
Given the time, we leave that for future work.
This is a solid starting point.
I'll architect a comprehensive runtime cost dashboard that correlates experience quality with infrastructure usage and inference costs. This is a critical system for ML/AI organizations to optimize spending while maintaining performance.