BigQuery cost query · Cost attribution
BigQuery cost per Airflow DAG and task
This query uses the airflow-dag and airflow-task labels that Airflow's Google provider adds to BigQuery jobs to rank DAGs and tasks by on-demand cost and slot-hours over the last 30 days, on Cloud Composer or any other Airflow.
The query
SELECT
(SELECT value FROM UNNEST(labels) WHERE key = 'airflow-dag') AS dag_id,
(SELECT value FROM UNNEST(labels) WHERE key = 'airflow-task') AS task_id,
COUNT(*) AS jobs,
ROUND(SUM(total_bytes_billed) / POW(1024, 4) * 6.25, 2) AS est_on_demand_usd,
ROUND(SUM(total_slot_ms) / 3600000, 2) AS slot_hours
FROM `region-us`.INFORMATION_SCHEMA.JOBS
WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
AND job_type = 'QUERY'
AND statement_type != 'SCRIPT'
AND EXISTS (SELECT 1 FROM UNNEST(labels) WHERE key = 'airflow-dag')
GROUP BY dag_id, task_id
ORDER BY est_on_demand_usd DESC;How it works
The BigQuery hook in Airflow's Google provider labels the jobs it starts with the DAG ID (airflow-dag) and the task ID (airflow-task). Label values are restricted to lowercase letters, digits, underscores and dashes, so IDs with other characters appear sanitized.
Remove task_id from the SELECT and GROUP BY to rank whole DAGs. A DAG whose cost grows every week while its schedule stays the same is often reprocessing its full history instead of one partition per run.
Output columns
| Column | Meaning |
|---|---|
dag_id | Value of the airflow-dag label. |
task_id | Value of the airflow-task label. |
jobs | BigQuery jobs started by the task in the window. |
Permissions and notes
Needs: bigquery.jobs.listAll on the project, for example through the BigQuery Resource Viewer role (roles/bigquery.resourceViewer). To see only your own jobs, query JOBS_BY_USER instead.
- The
6.25is the on-demand list price per TiB in the US and EU multi-regions. If your projects run on editions, cost follows slot-hours instead: multiplyslot_hoursby your edition's price per slot-hour (see BigQuery pricing). - Older versions of the Google provider don't add these labels. Tasks that run SQL through other operators or plain client code need labels set explicitly.
- dbt run from Airflow is better attributed with cost per dbt model.
FAQ
Does Cloud Composer itself show up in BigQuery cost?
No. Composer's environment is billed separately; this query covers only the BigQuery jobs its tasks start.
How do I add my own labels to Airflow BigQuery jobs?
Pass labels in the job configuration of BigQueryInsertJobOperator, for example a team or cost center, and group by them with the cost by label query.
Related
All BigQuery cost queries · Data FinOps playbook · Pricing calculator
