Cloud Billing API Setup Guide
This guide explains how to set up the Cloud Billing API integration for accurate cost monitoring.
π Overviewβ
The cost monitoring system now uses the Cloud Monitoring API to fetch real usage metrics and calculate costs for:
- Firestore: Document reads, writes, and storage
- Cloud Run (App Hosting): CPU, memory, and request costs
- Firebase Storage: Storage volume costs
π Prerequisitesβ
- Service Account with appropriate permissions
- Cloud Monitoring API enabled
- Project IDs configured
π Setup Stepsβ
Step 1: Enable Cloud Monitoring APIβ
For each Firebase project (toto-f9d2f, toto-bo, toto-ai-hub):
- Go to Google Cloud Console
- Select your project
- Navigate to APIs & Services β Library
- Search for "Cloud Monitoring API"
- Click Enable
Step 2: Configure Service Account Permissionsβ
The service account used by toto-bo needs the following IAM roles:
- Go to IAM & Admin β Service Accounts
- Find your service account (the one used by toto-bo)
- Click Edit β Add Another Role
- Add these roles:
- Monitoring Viewer (
roles/monitoring.viewer) - Cloud Billing Account Viewer (
roles/billing.accountViewer) - Optional, for billing account info - Cloud Monitoring Metrics Reader (
roles/monitoring.metricReader)
- Monitoring Viewer (
Minimum Required Role:
roles/monitoring.viewer- Allows reading monitoring metrics
Step 3: Configure Environment Variablesβ
Add these environment variables to your Firebase App Hosting configuration or .env:
# GCP Project IDs (optional - defaults provided)
GCP_PROJECT_ID_APP=toto-f9d2f
GCP_PROJECT_ID_BO=toto-bo
GCP_PROJECT_ID_AI_HUB=toto-ai-hub
# Billing Account ID (optional - will be auto-detected)
GCP_BILLING_ACCOUNT_ID=XXXXX-XXXXX-XXXXX
For Firebase App Hosting, add to apphosting.yaml:
env:
- variable: GCP_PROJECT_ID_APP
value: toto-f9d2f
availability:
- RUNTIME
- variable: GCP_PROJECT_ID_BO
value: toto-bo
availability:
- RUNTIME
- variable: GCP_PROJECT_ID_AI_HUB
value: toto-ai-hub
availability:
- RUNTIME
Step 4: Verify Service Account Credentialsβ
The system uses the same service account credentials as Firebase Admin:
FIREBASE_PRIVATE_KEYFIREBASE_CLIENT_EMAILFIREBASE_PROJECT_ID
These should already be configured. Verify they have the monitoring permissions listed in Step 2.
π How It Worksβ
Data Flowβ
Cost Monitoring Dashboard
β
/api/cost-monitoring/comprehensive
β
Cloud Monitoring API (fetch usage metrics)
β
Calculate costs using pricing formulas
β
Return real-time cost data
Fallback Behaviorβ
If the Cloud Monitoring API is unavailable or returns errors:
- Firestore: Falls back to estimated costs based on document counts
- Cloud Run: Shows placeholder with error message
- Storage: Shows placeholder with error message
The system gracefully degrades to estimates, so the dashboard always works.
π Metrics Queriedβ
Firestoreβ
firestore.googleapis.com/api/request_count(ReadDocument, WriteDocument)firestore.googleapis.com/database/storage_size
Cloud Runβ
run.googleapis.com/container/cpu/utilizationsrun.googleapis.com/container/memory/utilizationsrun.googleapis.com/request_count
Firebase Storageβ
storage.googleapis.com/storage/total_bytes
β οΈ Important Notesβ
-
Cost Calculation: The system calculates costs from usage metrics using Google Cloud pricing formulas. Actual billing may vary slightly due to:
- Discounts and credits
- Regional pricing differences
- Minimum billing thresholds
-
API Limits: Cloud Monitoring API has rate limits. The system queries metrics efficiently, but if you have many projects, consider:
- Caching results (5-minute TTL recommended)
- Using Cloud Scheduler for periodic updates
-
Permissions: The service account needs access to all projects you want to monitor. If projects are in different GCP organizations, you may need separate service accounts.
-
Time Range: Metrics are aggregated over the selected time range. For accurate costs:
- Use consistent time ranges
- Be aware that some metrics are sampled (e.g., CPU utilization)
π Troubleshootingβ
Error: "Billing API client not available"β
- Cause: Missing service account credentials
- Fix: Ensure
FIREBASE_PRIVATE_KEYandFIREBASE_CLIENT_EMAILare set
Error: "Permission denied" or "403 Forbidden"β
- Cause: Service account lacks monitoring permissions
- Fix: Add
roles/monitoring.viewerrole to service account
Error: "API not enabled"β
- Cause: Cloud Monitoring API not enabled for project
- Fix: Enable Cloud Monitoring API in GCP Console
Costs showing as $0 or placeholdersβ
- Cause: No usage data or API errors
- Fix:
- Check Cloud Monitoring API is enabled
- Verify service account permissions
- Check project IDs are correct
- Review server logs for specific errors
Costs seem inaccurateβ
- Cause: Usage metrics may be sampled or aggregated
- Fix:
- Compare with actual GCP billing dashboard
- Note that calculated costs are estimates based on usage
- For exact costs, use BigQuery billing export (future enhancement)
π Alternative: BigQuery Billing Exportβ
For exact cost data (not estimates), you can set up BigQuery billing export:
- Enable BigQuery billing export in GCP Console
- Export billing data to BigQuery
- Query BigQuery for exact costs
This is more complex but provides 100% accurate billing data. See the roadmap for future implementation.
π Related Documentationβ
β Verification Checklistβ
- Cloud Monitoring API enabled for all projects
- Service account has
roles/monitoring.viewerpermission - Environment variables configured (or defaults are correct)
- Service account credentials are valid
- Cost monitoring dashboard shows real data (not just placeholders)
- Fallback to estimates works if API fails
Last Updated: January 2025
Status: β
Implemented - Ready for testing