Technical document

Google Cloud FinOps in Practice: Cost Visualization, Anomaly Detection, and Optimization Architecture Based on BigQuery Billing Data Analysis

To solve issues like cross-label allocation and SKU-level root cause identification—which are difficult with the standard billing console—we explain a FinOps architecture based on BigQuery billing exports. We systematically organize the use of three tables, SQL for net cost aggregation and moving average anomaly detection, and strategies to suppress scan costs.
AI Development44 minPublication Date November 23, 2026Update date November 23, 2026
Thumbnail for Google Cloud FinOps in Practice: Cost Visualization, Anomaly Detection, and Optimization Architecture Based on BigQuery Billing Data Analysis

Summary

Key points of this document

  • 1. Background and Challenges: Why FinOps Can't Be Managed with Just the Standard Billing Console
  • 2. BigQuery Billing Export Data Structure and How to Use the 3 Tables
  • 3. FinOps Analysis and Automated Detection Architecture

1. Background and Challenges: Why FinOps Can't Be Managed with Just the Standard Billing Console

The Google Cloud standard billing console is a convenient tool for understanding monthly trends across projects and estimating costs by service. However, when attempting to implement continuous cost optimization (FinOps) in a production environment with multiple environments and teams, limitations in the standard report's aggregation axes, retention period, and external data integration become obstacles. This section will clarify the limitations of the standard console and explain why BigQuery billing export, which allows for flexible breakdown and attribution of billing data using SQL, is essential.

PerspectiveStandard Billing ConsoleBigQuery Billing Data AnalysisPractical Judgment Criteria
Aggregation Axis FlexibilityFixed grouping onlyFree joining and aggregation with SQLBigQuery is essential for cross-cutting allocation and calculating custom KPIs
Granularity for Root Cause AnalysisUp to service or part of SKUUp to resource ID or label unitEffective for isolating specific workloads during spikes
Matching with Development DataNot possible (billing information only)Can be joined with operational logs and deployment historyEssential for measuring unit economics
Anomaly Detection and AutomationPrimarily budget threshold alertsAutomatic detection of moving average deviations and day-over-day changesEnables noise-reduced issue creation and daily notifications

The main reasons why operations are difficult to manage with just the standard console can be summarized into the following four points:

  1. Limitations of Cross-Label Allocation: Standard reports cannot express logic such as prorating common infrastructure costs (shared VPC, common databases, logging infrastructure, etc.) based on the usage ratio of each department or service.
  2. Identifying Spike-Causing SKUs: When a sudden cost increase occurs daily or hourly, multi-faceted filtering with SQL is necessary to quickly drill down into which region, which SKU, and which resource or label caused the increase.
  3. Inability to Match with Workload Metrics: To calculate unit costs such as "cost per million requests" or "cost per batch process," billing data must be combined with application execution logs and metrics, which cannot be done with the console alone.
  4. Long-Term Trends and Credit Scrutiny: To precisely track the impact of annual price revisions and the coverage rate of Committed Use Discounts (CUDs), raw data must be accumulated in a DWH for time-series analysis.

To make Inform (visualization, breakdown, attribution), the first step of FinOps, a reproducible process rather than relying on individual expertise, it is essential to export all billing events to BigQuery and build an analysis platform based on SQL.


2. BigQuery Billing Export Data Structure and How to Use the 3 Tables

Google Cloud's billing data export provides three types of tables with different purposes and recording granularities. A crucial design point is to appropriately use these tables according to the purpose and the balance of scan costs, rather than unconditionally querying all of them. Furthermore, for cost aggregation, it is necessary to accurately understand how to calculate "net cost" after deducting discounts and credits.

Table TypeRecording GranularityMain UseSelection Criteria
Standard Usage CostProject, Service, SKU, HourlyOverall cost visibility, daily anomaly detection, budget managementStandard for daily FinOps dashboards and alert infrastructure
Detailed Usage CostResource name, GKE Pod or Namespace unitDetailed allocation within shared clusters, investigation of specific instancesWhen attribution analysis by GKE or individual resource unit is required
PricingList price per SKU, tier unit price, currency informationMonitoring unit price fluctuations, CUD purchase simulationWhen verifying discount rates or optimizing long-term contracts

The Importance of Correctly Calculating Net Cost

The cost column in billing records exported to BigQuery generally stores amounts based on the list price before discounts (gross cost). Reductions due to Committed Use Discounts (CUD), Sustained Use Discounts (SUD), promotional credits, or free tier are recorded as negative values in the array-type column credits (credits.amount) within the same record.

Therefore, SUM(cost) alone will result in a significantly higher amount than the actual bill. To determine the net cost, which matches the actual payment amount, it is essential to use a calculation formula that adds the total values of cost and credits.amount. By defining one standardized view in the dataset for this calculation and ensuring that subsequent dashboards and anomaly detection queries always refer to that view, you can prevent inconsistencies in aggregation definitions.


3. FinOps Analysis and Automated Detection Architecture

Simply storing billing data in BigQuery does not lead to cost reduction actions. It is necessary to design a consistent pipeline from data collection to the construction of optimized aggregation layers, visualization, anomaly detection, and feedback to development teams. This section organizes the overall data flow, the FinOps cyclical process, and the execution sequence of daily anomaly detection.

3.1 Data Pipeline from Billing Data Collection to Anomaly Detection and Ticket Creation

If visualization tools directly reference raw billing export tables, the scan volume increases, leading to inflated costs for the analysis infrastructure itself. An effective configuration involves inserting an aggregation layer that utilizes date partitioning and clustering, separating visualization purposes from automated detection purposes.

Loading diagram...

In this configuration, BI tools like Looker Studio are set to reference RawTable not directly, but rather AggTable, which is pre-aggregated daily by project, service, and major labels. This prevents the full scanning of huge raw tables every time a filter operation is performed on the dashboard.

3.2 The 3-Phase Cyclical Process of FinOps

After establishing the technical infrastructure, to continuously optimize costs as an organization, it is necessary to design operations that cyclically run the three basic FinOps phases (Inform, Optimize, Operate) rather than treating them as one-off events.

Loading diagram...

In many workplaces, Optimize is only addressed as a one-off when costs surge, but within a few months, costs re-inflate due to neglected new resources or missed configurations. The key to sustained success is to institutionalize BigQuery anomaly detection and budget guardrails as Operate and to cycle this into the next Inform phase.

3.3 Daily Anomaly Detection and Automated Notifications/Issue Creation Sequence

In daily anomaly detection, merely notifying that 'an anomaly has occurred' consumes the person in charge's time investigating the cause. We will build a process that, immediately after detecting a deviation from the moving average with a scheduled query, automatically extracts the affected projects and rapidly increasing SKUs/resource labels, and then notifies or even creates an issue with the information necessary for the initial investigation.

Loading diagram...

By automatically adding "Day-over-day +X yen (+Y%)", "Top 3 contributing SKUs", and "Corresponding resource env / service label" to the notification body, engineers can immediately pinpoint which feature and which change caused the issue upon seeing the notification.


4. Common Cost Overrun Patterns and BigQuery Detection/Optimization Matrix

There are certain tendencies in how costs unintentionally increase during Google Cloud operations. By using BigQuery billing data, we can systematize which columns and metrics to use to capture these signs and what optimization actions should be taken.

Cost Overrun PatternMain Detection Axis in BigQuerySpecific Optimization Actions
Cloud Run Persistent Billingservice.description is Cloud Run and SKUs derived from minimum instance count or always-on CPU allocationmin-instances Zeroing out during non-operational hours, changing to CPU allocation only during request processing
Cloud Storage BloatContinuous monotonic increase in storage capacity SKUs and label aggregation per bucketMigration to Nearline/Coldline via Lifecycle rule settings and automatic deletion of old generation objects
BigQuery Full ScanDaily spikes in BigQuery Analysis SKUs (billed by processed bytes)Introduction of partitioning and clustering, SELECT * deprecation, maximum billed bytes per query limit
Excessive Cloud Logging IngestionRapid increase in Cloud Logging of Log Volume SKUs relative to application scaleStopping debug log output in production, excluding health check logs with exclusion filters
Idle Disks/Static IPsPersistent Disk and Static IP SKUs that continue to incur fixed charges even during periods of zero compute resource operationSnapshotting and deleting unattached disks, releasing unused external static IP addresses

These patterns, while appearing small within a single project, often become non-negligible fixed costs when aggregated across development and testing environments. Even running a monthly BigQuery query to extract "storage and network SKUs that have had no usage fluctuations and have been continuously billed at a fixed rate for the past 30 days" can yield definite cost reduction effects.


5. Practical SQL Patterns and BigQuery's Own Cost Control

This section presents representative BigQuery SQL patterns that can be directly applied in practice, along with design rules to suppress scan charges for BigQuery itself, which is the analytics platform. The table structure assumes standard export (Standard Usage Cost).

5.1 Basic Query for Net Cost Aggregation

This is a basic pattern that combines limiting the scan range by date partition withUNNEST(credits) accurate net cost calculation.

SELECT
  invoice.month AS invoice_month,
  DATE(usage_start_time, "Asia/Tokyo") AS usage_date,
  project.id AS project_id,
  service.description AS service_name,
  ROUND(SUM(cost), 2) AS gross_cost,
  ROUND(
    SUM(cost) + SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) AS c), 0)),
    2
  ) AS net_cost
FROM
  `billing_dataset.gcp_billing_export_v1_XXXXXX_XXXXXX_XXXXXX`
WHERE
  _PARTITIONDATE >= DATE_SUB(CURRENT_DATE("Asia/Tokyo"), INTERVAL 30 DAY)
  AND invoice.month = FORMAT_DATE("%Y%m", CURRENT_DATE("Asia/Tokyo"))
GROUP BY
  invoice_month,
  usage_date,
  project_id,
  service_name
HAVING
  net_cost != 0
ORDER BY
  usage_date DESC,
  net_cost DESC;

5.2 Daily Spike Detection by Deviation from 7-Day Moving Average

Using only a simple "day-over-day comparison" often leads to false positives due to normal traffic increases from weekends to Mondays. By using a 7-day moving average as a baseline and adding both "rate of increase" and "minimum absolute value threshold" as conditions, noise caused by ratio fluctuations in small-amount resources can be suppressed.

WITH daily_cost AS (
  SELECT
    DATE(usage_start_time, "Asia/Tokyo") AS usage_date,
    project.id AS project_id,
    service.description AS service_name,
    SUM(cost) + SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) AS c), 0)) AS net_cost
  FROM
    `billing_dataset.gcp_billing_export_v1_XXXXXX_XXXXXX_XXXXXX`
  WHERE
    _PARTITIONDATE >= DATE_SUB(CURRENT_DATE("Asia/Tokyo"), INTERVAL 10 DAY)
  GROUP BY
    1, 2, 3
),
moving_avg AS (
  SELECT
    usage_date,
    project_id,
    service_name,
    net_cost,
    AVG(net_cost) OVER (
      PARTITION BY project_id, service_name
      ORDER BY usage_date
      ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING
    ) AS avg_7d_cost
  FROM
    daily_cost
)
SELECT
  usage_date,
  project_id,
  service_name,
  ROUND(avg_7d_cost, 2) AS baseline_7d,
  ROUND(net_cost, 2) AS actual_cost,
  ROUND(net_cost - avg_7d_cost, 2) AS diff_amount,
  ROUND(SAFE_DIVIDE(net_cost - avg_7d_cost, avg_7d_cost) * 100, 1) AS increase_pct
FROM
  moving_avg
WHERE
  usage_date = DATE_SUB(CURRENT_DATE("Asia/Tokyo"), INTERVAL 2 DAY)
  AND net_cost - avg_7d_cost >= 1000
  AND SAFE_DIVIDE(net_cost, avg_7d_cost) >= 1.5
ORDER BY
  diff_amount DESC;

The reason the detection target date is set to CURRENT_DATE - 2 DAY is to prevent incorrect underestimation and false alerts due to the previous day's data being unconfirmed, considering the billing data reflection delay described later (if a confirmation delay is acceptable, it is monitored in combination with - 1 DAY).

5.3 Identifying Resources Without Labels

To improve the accuracy of cost allocation (Showback / Chargeback), we regularly extract costs that are missing mandatory labels (e.g., env,service,owner).

SELECT
  project.id AS project_id,
  service.description AS service_name,
  sku.description AS sku_name,
  ROUND(
    SUM(cost) + SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) AS c), 0)),
    2
  ) AS untagged_net_cost
FROM
  `billing_dataset.gcp_billing_export_v1_XXXXXX_XXXXXX_XXXXXX`
WHERE
  _PARTITIONDATE >= DATE_SUB(CURRENT_DATE("Asia/Tokyo"), INTERVAL 7 DAY)
  AND NOT EXISTS (
    SELECT 1 FROM UNNEST(labels) AS l WHERE l.key = "env"
  )
GROUP BY
  1, 2, 3
HAVING
  untagged_net_cost > 100
ORDER BY
  untagged_net_cost DESC;

5.4 Design to Suppress Scan Charges for BigQuery Itself, the Analytics Platform

It would be counterproductive if the analytics platform itself, intended for cost reduction, generated high scan charges. We thoroughly implement the following four controls on the BigQuery side.

  1. Enforcing partition filters: For aggregation tables and derived tables, set require_partition_filter = true to reject full scan queries that do not specify date conditions at the syntax level.
  2. Thorough elimination of SELECT *: Since BigQuery is a columnar storage, specifying only the necessary columns can dramatically reduce the number of scanned bytes. In particular, nested arrays such as credits, labels, and system_labels should not be included in unnecessary queries.
  3. Leveraging pre-aggregated tables and materialized views: To prevent BI tools like Looker Studio from hitting raw tables with every filter operation, refer to daily summary tables (with project.id and service.description specified as clustering keys) generated by a scheduled query once a day.
  4. Upper limit protection with maximum_bytes_billed: Always set the maximum_bytes_billed parameter for automatically executed scripts and data mart update queries to safely interrupt queries if an unexpected large scan occurs.

6. Limitations, Caveats, and Verification Points

BigQuery billing data analysis is an extremely powerful method, but due to the nature of cloud billing data, it is not a panacea. It is necessary to correctly understand the system's limitations, combine complementary measures, and clarify verification points after implementation.

6.1 Data Reflection Lag and the Boundary of Real-time Defense

Google Cloud billing data is not streamed to BigQuery in real-time; there is atime lag of several hours to over 24 hoursfrom the occurrence of usage until it is reflected in the tables. Additionally, the final adjustment credits for Committed Use Discounts (CUD) and Sustained Use Discounts (SUD) at the end of the month may fluctuate until the billing is finalized at the beginning of the following month.

Therefore, while BigQuery billing analysis is ideal for"understanding daily trends," "identifying structural waste," and "post-mortem root cause analysis," it cannot be used for "emergency shutdown of billing within minutes due to runaway queries or infinite loop processing."As a real-time defense, always use the following mechanisms in conjunction.

  • API quota limits per service (request limits per day/minute and BigQuery custom quotas)
  • Anomaly alert notifications linked with Cloud Billing Budget and Pub/Sub
  • Maximum retry attempts and circuit breaker implementation on the application side

6.2 Importance of Pre-label Design

The labels included in BigQuery's billing export records**only records the labels that were attached to the resource at the moment it was running.**Even if labels are added to a resource later via the console or Terraform, they will not be retroactively applied to past billing records.

Therefore, it is important to incorporate rules that enforce minimum common label keys such as env (environment classification),service (service name),owner (responsible team) during project initiation or the module design phase of IaC (Terraform, etc.).

6.3 Verification Points After Implementation

To ensure that the constructed FinOps analysis foundation is functioning correctly, the following three points are regularly verified:

  • Reconciliation with Total Invoice Amount: Verify that the total monthly net cost calculated in BigQuery (invoice.month specified) matches the actual invoice (PDF / confirmed billing amount on the console). It is important to understand minor discrepancies due to VAT handling, foreign exchange rates, and the timing of adjustment credit reflection at the beginning of the month.
  • Cost Monitoring of Analysis Queries Themselves: Regularly refer to INFORMATION_SCHEMA.JOBS to monitor whether the execution costs of FinOps dashboards and scheduled queries are not excessive compared to the overall cost reduction effects.
  • Alert Threshold Tuning: Periodically review whether notifications triggered by anomaly detection queries capture "spikes that truly need investigation," and conversely, whether subtle daily fluctuations are causing alert fatigue (crying wolf). Adjust the balance between monetary thresholds and growth rates.

7. Summary: Decision Criteria for Sustainable FinOps Operations

To ensure that Google Cloud cost optimization does not end as a one-off savings event, but rather becomes an engineering culture that balances development speed and cost efficiency, it is important to design architectures with the following decision criteria.

  1. Design visualization granularity in stages: First, grasp overall trends and daily spikes with the Standard Usage Cost table. Then, when allocation for shared clusters or individual resources becomes necessary, delve into Detailed Usage Cost to avoid excessive complexity.
  2. Separate defense mechanisms according to time axis: We thoroughly divide roles, entrusting real-time runaway prevention to API quotas and application control, while specializing BigQuery analysis in daily anomaly detection, root cause identification, and medium-to-long-term structural optimization.
  3. Be mindful of the cost-effectiveness of the analytics infrastructure itself: By enforcing partitions and introducing pre-aggregated tables, we maintain a state where BI tools and monitoring queries run cheaply and quickly.
  4. Incorporate label governance into automated processes: Since the accuracy of billing data analysis depends on prior label design, we ensure label assignment as a mandatory IaC check rather than relying on manual operations.

Stepping beyond the standard billing console and building a reproducible loop of measurement, detection, and improvement based on SQL provides a solid foundation for predictable and healthy cloud operations.

Technical documents

We will continue to increase technical documentation.

We will continue to organize our thoughts on AI, cloud, business app development, requirements definition, and operational design into documents.

Go to technical documentation list