Snowflake's elastic compute is powerful — until your bill arrives. This deep-dive playbook shows analytics engineering teams how to implement resource monitors, query tagging via dbt macros, and a complete cost observability layer that attributes every dollar of Snowflake spend to a team, pipeline, or model. No more mystery invoices.

It's 9 AM on a Monday and your Slack is already on fire. Someone ran a full table scan against 18 months of raw event data on your production warehouse over the weekend — no filters, no limit, just a SELECT * from a 400-billion-row table that ran for six hours straight. Your Snowflake bill for that single query will show up in next month's invoice as a line item that makes your CFO physically uncomfortable. The worst part? You had no idea it was happening until it was done.
This isn't a hypothetical. It's the kind of event that happens to analytics engineering teams operating in Snowflake without a deliberate cost governance strategy. Snowflake's elastic compute model is genuinely powerful — the ability to spin up a 2X-Large warehouse for a compute-intensive transformation and then suspend it automatically is a capability that would have seemed like magic a decade ago. But that elasticity is a double-edged sword. Without guardrails, your costs scale just as elastically as your query performance. The platform will cheerfully run whatever you throw at it, and it will bill you accordingly.
By the end of this lesson, you'll have a complete, production-grade cost governance framework for Snowflake. You'll understand not just how to configure resource monitors and warehouse budgets, but why Snowflake's billing model creates specific failure modes that each tool is designed to address. You'll be able to implement query tagging that gives you attribution at the team, pipeline, and query level, and you'll know how to build a monitoring layer that catches runaway spend before it becomes a bill.
What you'll learn:
ACCOUNT_USAGE schema to build a real-time cost observability layerYou should be comfortable with:
You'll need ACCOUNTADMIN or SYSADMIN role privileges to create resource monitors and warehouses. Query tag strategy can be implemented by any role with warehouse access.
Before you can govern costs intelligently, you need a precise mental model of where credits go. Most teams have a vague understanding ("big warehouses cost more") but lack the specificity to design effective controls.
Snowflake charges for virtual warehouse compute time in per-second increments (with a 60-second minimum per query). The credit cost depends on the warehouse size:
| Warehouse Size | Credits/Hour |
|---|---|
| X-Small | 1 |
| Small | 2 |
| Medium | 4 |
| Large | 8 |
| X-Large | 16 |
| 2X-Large | 32 |
| 3X-Large | 64 |
| 4X-Large | 128 |
There are several implications here that most teams miss:
The 60-second minimum is a trap for short, frequent queries. If you have a BI tool running 50 queries per minute that each take 3 seconds, you're paying for 60 seconds per query, not 3. That's a 20x billing multiplier. This is why Snowflake's query result caching and clustering matter so much for BI workloads — not just for performance, but for cost.
Multi-cluster warehouses multiply your credit burn. If you configure a warehouse with MIN_CLUSTER_COUNT = 1 and MAX_CLUSTER_COUNT = 4, you can be running four warehouses simultaneously at peak load. A 2X-Large multi-cluster warehouse at max scale costs 128 credits/hour. At $3/credit, that's $384/hour.
Storage, Snowpipe, and data transfer also contribute costs, but for most analytics engineering teams, compute is the dominant cost driver. This lesson focuses primarily on compute governance, though the tagging strategy applies to all cost dimensions.
Key insight
Snowflake does not charge for queries that are served from the result cache — a repeated identical query returns instantly at zero compute cost. This means that for dashboards hitting the same query repeatedly, result cache hit rate is a direct cost metric. You can monitor this in QUERY_HISTORY via the IS_CLIENT_SIDE_FALL_THROUGH and cache-related columns.
The other critical concept is warehouse suspension. A warehouse that is suspended costs nothing. The default auto-suspend is 10 minutes, but most teams leave it there without thinking. For a Large warehouse running idle for 10 minutes, that's 1.3 credits ($4 at typical pricing) burned doing nothing. Set auto-suspend to 60 seconds for interactive/BI warehouses and 5 minutes for transformation warehouses where cold starts are more expensive.
Resource monitors govern warehouses. If your warehouse architecture is a mess, your monitoring will be too. Before implementing any governance tooling, you need a deliberate warehouse topology.
The pattern that works at scale is functional isolation: separate warehouses for separate workload types. At minimum, you want:
PROD_LOADING_WH -- Data ingestion (Fivetran, Airbyte, Snowpipe)
PROD_TRANSFORM_WH -- dbt production runs
PROD_BI_WH -- Looker, Tableau, Metabase
PROD_ADHOC_WH -- Analysts, Jupyter notebooks, ad-hoc SQL
DEV_TRANSFORM_WH -- dbt development runs
This isolation matters for three reasons beyond governance:
PROD_TRANSFORM_WH costs map to your dbt pipeline, so your resource monitor alerts have clear ownersIf you're currently running everything on one or two warehouses, the first governance win is usually just splitting workloads. This alone typically produces 20-30% cost reduction because you can right-size each warehouse independently and set appropriate auto-suspend intervals.
Warning
Don't over-fragment your warehouse topology. Having 15 warehouses because every team wanted their own creates its own governance nightmare — monitors to maintain, roles to manage, and the minimum-credit-per-query tax applies to each warehouse independently. For most teams, 5-7 warehouses is the right number.
Resource monitors are Snowflake's native budget enforcement mechanism. They work by measuring credit consumption against a configurable limit and triggering actions (notify, suspend, or suspend immediately) when thresholds are crossed.
There are two levels of resource monitors: account-level (applies to all warehouses not covered by a warehouse-level monitor) and warehouse-level (applies to a specific warehouse or set of warehouses). You need both, and they serve different purposes.
The account-level monitor is your last line of defense. It should be set at a level that represents genuine financial risk — not a planning target, but a circuit breaker.
-- Create the account-level safety net monitor
-- This runs with ACCOUNTADMIN
USE ROLE ACCOUNTADMIN;
CREATE OR REPLACE RESOURCE MONITOR ACCOUNT_SAFETY_NET
WITH CREDIT_QUOTA = 50000 -- Monthly credit ceiling for the entire account
FREQUENCY = MONTHLY
START_TIMESTAMP = IMMEDIATELY
TRIGGERS
ON 50 PERCENT DO NOTIFY -- Early warning: we're tracking toward limit
ON 75 PERCENT DO NOTIFY -- Elevated alert: review active workloads
ON 90 PERCENT DO NOTIFY -- Critical: imminent budget exhaustion
ON 100 PERCENT DO SUSPEND -- Hard stop: suspend all warehouses
ON 110 PERCENT DO SUSPEND_IMMEDIATE; -- Emergency: kill all running queries
-- Apply it at the account level
ALTER ACCOUNT SET RESOURCE_MONITOR = ACCOUNT_SAFETY_NET;
A few important details about this configuration:
SUSPEND vs SUSPEND_IMMEDIATE: SUSPEND prevents new queries from starting but allows currently-running queries to complete. SUSPEND_IMMEDIATE kills all running queries immediately. For the account-level safety net, you want SUSPEND at 100% — it stops new spend while allowing critical operations to finish. SUSPEND_IMMEDIATE at 110% is your emergency brake if something continues consuming credits despite the initial suspension (which can happen with running queries that were already in flight when the monitor triggered).
The notification target: DO NOTIFY sends an email to all users with the ACCOUNTADMIN role, plus any email addresses configured in the monitor's notification list. This is often insufficient for production teams. You'll want to route these to a Slack channel or PagerDuty via a webhook — we'll cover that in the observability section.
Monthly vs. Weekly resets: Monthly frequency aligns with your Snowflake invoice, which makes budget reconciliation straightforward. For teams with high month-to-month variance, weekly monitors at 25% of monthly budget can provide earlier intervention signals.
Warehouse-level monitors are where your actual governance work happens. Each functional warehouse gets its own monitor, sized according to that warehouse's budget allocation.
-- Analytics transformation warehouse monitor
CREATE OR REPLACE RESOURCE MONITOR PROD_TRANSFORM_MONITOR
WITH CREDIT_QUOTA = 8000 -- ~$24k/month at $3/credit
FREQUENCY = MONTHLY
START_TIMESTAMP = IMMEDIATELY
TRIGGERS
ON 60 PERCENT DO NOTIFY
ON 85 PERCENT DO NOTIFY
ON 95 PERCENT DO SUSPEND
ON 100 PERCENT DO SUSPEND_IMMEDIATE;
ALTER WAREHOUSE PROD_TRANSFORM_WH SET RESOURCE_MONITOR = PROD_TRANSFORM_MONITOR;
-- BI/dashboarding warehouse monitor (lower budget, different thresholds)
CREATE OR REPLACE RESOURCE MONITOR PROD_BI_MONITOR
WITH CREDIT_QUOTA = 3000
FREQUENCY = MONTHLY
START_TIMESTAMP = IMMEDIATELY
TRIGGERS
ON 70 PERCENT DO NOTIFY
ON 95 PERCENT DO NOTIFY
ON 100 PERCENT DO SUSPEND;
ALTER WAREHOUSE PROD_BI_WH SET RESOURCE_MONITOR = PROD_BI_MONITOR;
-- Ad-hoc analysis warehouse — tighter controls, earlier suspension
CREATE OR REPLACE RESOURCE MONITOR PROD_ADHOC_MONITOR
WITH CREDIT_QUOTA = 1500
FREQUENCY = MONTHLY
START_TIMESTAMP = IMMEDIATELY
TRIGGERS
ON 50 PERCENT DO NOTIFY
ON 80 PERCENT DO NOTIFY
ON 95 PERCENT DO SUSPEND;
ALTER WAREHOUSE PROD_ADHOC_WH SET RESOURCE_MONITOR = PROD_ADHOC_MONITOR;
Note
A warehouse can only have one resource monitor assigned at a time. If you reassign a warehouse to a new monitor, the previous monitor no longer tracks that warehouse's consumption. This matters when you're restructuring your warehouse topology — make sure your monitor assignments are updated atomically with warehouse changes.
Notice that the ad-hoc warehouse has earlier notification thresholds (50%, 80%) compared to the BI warehouse (70%, 95%). This is intentional. Ad-hoc queries are inherently unpredictable — a data scientist exploring a new dataset can consume more credits in an afternoon than your dbt pipeline uses in a week. Early warnings give you time to intervene before suspension disrupts analyst workflows.
The built-in email notifications from resource monitors are rarely sufficient for production operations. You want these alerts flowing into your incident management system. The challenge is that Snowflake doesn't natively support webhook notifications from resource monitors.
The practical workaround is to build a lightweight monitoring query that you run on a schedule via Airflow or another orchestrator. Query SNOWFLAKE.ACCOUNT_USAGE.RESOURCE_MONITORS and SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY to calculate current utilization and trigger your alerting system:
-- Current resource monitor utilization
-- Run this via Airflow every hour
WITH monitor_usage AS (
SELECT
name AS monitor_name,
credit_quota,
credits_used,
ROUND((credits_used / NULLIF(credit_quota, 0)) * 100, 2) AS pct_used,
-- Estimate days remaining in period
DATEDIFF('day', start_time, end_time) AS period_days,
DATEDIFF('day', start_time, CURRENT_TIMESTAMP()) AS days_elapsed,
credit_quota - credits_used AS credits_remaining
FROM SNOWFLAKE.ACCOUNT_USAGE.RESOURCE_MONITORS
WHERE
-- Only active monitors in current period
CURRENT_TIMESTAMP() BETWEEN start_time AND end_time
OR end_time IS NULL
)
SELECT
monitor_name,
credit_quota,
credits_used,
pct_used,
credits_remaining,
-- Projected end-of-period usage based on current burn rate
ROUND(
(credits_used / NULLIF(days_elapsed, 0)) * period_days,
0
) AS projected_period_credits,
CASE
WHEN pct_used >= 90 THEN 'CRITICAL'
WHEN pct_used >= 75 THEN 'WARNING'
WHEN pct_used >= 50 THEN 'INFO'
ELSE 'HEALTHY'
END AS status
FROM monitor_usage
ORDER BY pct_used DESC;
This query gives you a live picture of budget utilization across all monitors, plus a simple burn-rate projection. If projected_period_credits significantly exceeds credit_quota, you have a problem that's developing over days, not hours — giving you time to intervene before suspension.
Resource monitors tell you how much you're spending. Query tags tell you who is spending it and why. Without attribution, cost governance is guesswork — you can suspend a warehouse, but you can't have a conversation with the pipeline or the team member responsible.
Snowflake supports query tags at two levels: session-level (all queries in a session inherit the tag) and query-level (individual queries can carry specific tags). Both are set via the ALTER SESSION SET QUERY_TAG command.
Before writing any code, design your tag schema. Query tags in Snowflake are free-form strings, but structuring them as JSON gives you clean parsing in ACCOUNT_USAGE.QUERY_HISTORY. A production tag schema should capture:
{
"team": "analytics_engineering",
"environment": "production",
"tool": "dbt",
"pipeline": "nightly_transform",
"model": "fct_orders",
"git_sha": "a3f8c92",
"run_id": "dbt_run_20240315_020145",
"triggered_by": "airflow_dag_id_123"
}
This schema lets you answer cost questions at multiple granularities:
teampipeline + run_idmodelgit_shaKey insight
The git_sha field is particularly powerful. When a dbt model's cost spikes after a deployment, you can immediately identify which commit introduced the change and diff the SQL. This turns cost anomalies into actionable engineering investigations instead of mysteries.
dbt provides two hook mechanisms that make systematic query tagging straightforward: on-run-start hooks (run once at the beginning of a dbt invocation) and on-run-end hooks (run once at the end). You can also use pre-hook and post-hook at the model level for per-model tagging.
The best approach for session-level tagging is a macro called from on-run-start. Create macros/set_query_tag.sql:
{% macro set_query_tag() %}
{% set query_tag_dict = {
"team": env_var("DBT_TEAM", "unknown"),
"environment": target.name,
"tool": "dbt",
"dbt_version": dbt_version,
"pipeline": env_var("DBT_PIPELINE_NAME", "manual"),
"run_id": invocation_id,
"git_sha": env_var("GIT_SHA", "local"),
"triggered_by": env_var("AIRFLOW_RUN_ID", "manual")
} %}
{% set query_tag_str = tojson(query_tag_dict) %}
{% if execute %}
{% do log("Setting query tag: " ~ query_tag_str, info=True) %}
{% set set_query_tag_sql %}
ALTER SESSION SET QUERY_TAG = '{{ query_tag_str }}';
{% endset %}
{% do run_query(set_query_tag_sql) %}
{% endif %}
{% endmacro %}
Then register it in dbt_project.yml:
on-run-start:
- "{{ set_query_tag() }}"
on-run-end:
- "ALTER SESSION SET QUERY_TAG = ''"
The on-run-end hook clears the query tag so that queries run after the dbt session (by other tools using the same connection pool) don't accidentally inherit the dbt tag.
For model-level granularity, you want to also set the model name on each query. This requires a pre-hook on each model, which you can apply globally via dbt_project.yml:
models:
your_project_name:
+pre-hook:
- "{{ set_model_query_tag(this) }}"
And the corresponding macro in macros/set_model_query_tag.sql:
{% macro set_model_query_tag(model) %}
{% set current_tag_query %}
SELECT CURRENT_SESSION_QUERY_TAG()
{% endset %}
{% if execute %}
{% set current_tag_result = run_query(current_tag_query) %}
{% set current_tag_str = current_tag_result.columns[0].values()[0] %}
{# Parse existing tag and add model info #}
{% if current_tag_str and current_tag_str != '' %}
{% set current_tag = fromjson(current_tag_str) %}
{% else %}
{% set current_tag = {} %}
{% endif %}
{% set _ = current_tag.update({"model": model.name, "schema": model.schema}) %}
{% set updated_tag = tojson(current_tag) %}
{% set update_sql %}
ALTER SESSION SET QUERY_TAG = '{{ updated_tag }}';
{% endset %}
{% do run_query(update_sql) %}
{% endif %}
{% endmacro %}
This pattern reads the existing session tag (set at the start of the dbt run), enriches it with the current model name, and updates the session. The result is that every SQL query dbt emits for a given model carries full context — team, environment, pipeline, run ID, and model name.
Warning
Calling run_query in pre-hooks adds a small overhead per model — typically 10-50ms per model execution. For projects with hundreds of models, this adds up to a few minutes of additional run time. If you're extremely latency-sensitive on your dbt runs, consider tagging only at the session level (which captures run-level attribution) and accepting that model-level attribution comes from joining QUERY_HISTORY to dbt's run_results.json on timestamp ranges.
Your dbt pipeline probably handles 50-70% of your Snowflake compute, but you also have:
For ingestion tools: Fivetran uses a dedicated warehouse and you can identify its queries via QUERY_HISTORY.USER_NAME = 'FIVETRAN_USER'. You don't control the query tags, but you don't need to — the warehouse assignment gives you attribution.
For Airflow pipelines that run raw SQL against Snowflake: implement query tagging in your Snowflake hook connection setup. Create a custom Airflow operator or connection class that sets the query tag before executing any SQL:
# In a custom SnowflakeOperator wrapper or Airflow hook
from airflow.providers.snowflake.hooks.snowflake import SnowflakeHook
import json
from datetime import datetime
class TaggedSnowflakeHook(SnowflakeHook):
"""
Extends SnowflakeHook to automatically set query tags for cost attribution.
"""
def get_conn(self):
conn = super().get_conn()
# Build the query tag from Airflow context
query_tag = {
"tool": "airflow",
"dag_id": self.dag_id if hasattr(self, 'dag_id') else "unknown",
"task_id": self.task_id if hasattr(self, 'task_id') else "unknown",
"run_id": self.run_id if hasattr(self, 'run_id') else "unknown",
"environment": "production",
"team": "data_engineering"
}
cursor = conn.cursor()
cursor.execute(
f"ALTER SESSION SET QUERY_TAG = '{json.dumps(query_tag)}'"
)
cursor.close()
return conn
For BI tools: Most enterprise BI tools have a "query label" or similar feature. In Looker, you can configure custom labels that get appended to queries. In Tableau, the application sends a comment in the query. While these aren't Snowflake QUERY_TAG fields, they appear in the QUERY_TEXT column of QUERY_HISTORY, and you can parse them with regex for attribution.
Resource monitors handle enforcement. Query tags handle attribution. Now you need visibility — a monitoring layer that shows you what's happening before you hit a threshold.
The SNOWFLAKE.ACCOUNT_USAGE schema is your primary data source. It has a lag of approximately 45 minutes to 3 hours for most views, which is good enough for daily cost management but not for real-time intervention. For near-real-time data, use SNOWFLAKE.INFORMATION_SCHEMA.QUERY_HISTORY (no lag, but limited to 7 days and 10,000 rows per call).
The backbone of your cost reporting — run this daily and persist results to a table for trending:
-- Cost attribution by team and pipeline for the current month
-- Persist this result daily to a reporting table
WITH tagged_queries AS (
SELECT
query_id,
query_text,
user_name,
warehouse_name,
warehouse_size,
database_name,
schema_name,
execution_status,
start_time,
end_time,
total_elapsed_time / 1000 AS elapsed_seconds,
-- Parse JSON query tags
TRY_PARSE_JSON(query_tag) AS tag_json,
-- Credit calculation: (seconds / 3600) * credits_per_hour
-- Credits per hour by warehouse size
CASE warehouse_size
WHEN 'X-Small' THEN 1
WHEN 'Small' THEN 2
WHEN 'Medium' THEN 4
WHEN 'Large' THEN 8
WHEN 'X-Large' THEN 16
WHEN '2X-Large' THEN 32
WHEN '3X-Large' THEN 64
WHEN '4X-Large' THEN 128
ELSE 0
END AS credits_per_hour,
-- Actual credits consumed (with 60-second minimum)
(GREATEST(total_elapsed_time, 60000) / 3600000.0) *
CASE warehouse_size
WHEN 'X-Small' THEN 1
WHEN 'Small' THEN 2
WHEN 'Medium' THEN 4
WHEN 'Large' THEN 8
WHEN 'X-Large' THEN 16
WHEN '2X-Large' THEN 32
WHEN '3X-Large' THEN 64
WHEN '4X-Large' THEN 128
ELSE 0
END AS credits_consumed
FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
WHERE
start_time >= DATE_TRUNC('month', CURRENT_DATE())
AND execution_status = 'SUCCESS'
AND warehouse_name IS NOT NULL -- Excludes cached results
),
attributed AS (
SELECT
DATE_TRUNC('day', start_time) AS query_date,
warehouse_name,
-- Extract attribution dimensions from query tag
COALESCE(tag_json:team::VARCHAR, 'untagged') AS team,
COALESCE(tag_json:environment::VARCHAR, 'unknown') AS environment,
COALESCE(tag_json:tool::VARCHAR, 'unknown') AS tool,
COALESCE(tag_json:pipeline::VARCHAR, 'unknown') AS pipeline,
COALESCE(tag_json:model::VARCHAR, 'unknown') AS dbt_model,
-- Aggregate metrics
COUNT(*) AS query_count,
SUM(elapsed_seconds) AS total_elapsed_seconds,
AVG(elapsed_seconds) AS avg_elapsed_seconds,
MAX(elapsed_seconds) AS max_elapsed_seconds,
SUM(credits_consumed) AS total_credits,
SUM(credits_consumed) * 3.0 AS estimated_cost_usd -- Adjust to your contract rate
FROM tagged_queries
GROUP BY 1, 2, 3, 4, 5, 6, 7
)
SELECT
query_date,
warehouse_name,
team,
pipeline,
dbt_model,
query_count,
ROUND(total_credits, 4) AS total_credits,
ROUND(estimated_cost_usd, 2) AS estimated_cost_usd,
ROUND(avg_elapsed_seconds, 2) AS avg_elapsed_seconds,
ROUND(max_elapsed_seconds, 2) AS max_elapsed_seconds
FROM attributed
ORDER BY total_credits DESC;
This query highlights a critical point: GREATEST(total_elapsed_time, 60000) applies the 60-second billing minimum. Many cost analyses omit this and produce credit estimates that are significantly understated for workloads with many short queries.
Note
The credit calculation above approximates per-query cost based on elapsed time and warehouse size. It's a good estimate but not perfectly accurate because Snowflake applies the 60-second minimum at the warehouse billing level (tracking all concurrent queries against the same warehouse), not per-query in isolation. For exact billing figures, use WAREHOUSE_METERING_HISTORY as the source of truth for actual credits consumed.
This query identifies your most expensive queries by absolute credit cost — essential for finding optimization opportunities:
-- Top 25 most expensive queries this month
-- Use this to find optimization candidates
SELECT
query_id,
LEFT(query_text, 200) AS query_preview,
user_name,
warehouse_name,
TRY_PARSE_JSON(query_tag):model::VARCHAR AS dbt_model,
TRY_PARSE_JSON(query_tag):pipeline::VARCHAR AS pipeline,
total_elapsed_time / 1000 AS elapsed_seconds,
bytes_scanned / (1024 * 1024 * 1024) AS gb_scanned,
rows_produced,
-- Credits consumed with 60-second minimum
ROUND(
(GREATEST(total_elapsed_time, 60000) / 3600000.0) *
CASE warehouse_size
WHEN 'X-Small' THEN 1 WHEN 'Small' THEN 2 WHEN 'Medium' THEN 4
WHEN 'Large' THEN 8 WHEN 'X-Large' THEN 16 WHEN '2X-Large' THEN 32
WHEN '3X-Large' THEN 64 WHEN '4X-Large' THEN 128 ELSE 0
END,
4
) AS credits_consumed,
-- Flag potential optimization opportunities
CASE
WHEN bytes_scanned > 10 * 1024 * 1024 * 1024 AND rows_produced < 10000
THEN 'Large scan, small result — check clustering/pruning'
WHEN total_elapsed_time > 3600000
THEN 'Extremely long query — consider materialization or chunking'
WHEN partitions_scanned > partitions_total * 0.9 AND partitions_total > 100
THEN 'Full partition scan — clustering key may be missing or wrong'
ELSE 'Review query plan'
END AS optimization_hint
FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
WHERE
start_time >= DATE_TRUNC('month', CURRENT_DATE())
AND execution_status = 'SUCCESS'
AND warehouse_name IS NOT NULL
ORDER BY credits_consumed DESC
LIMIT 25;
The optimization_hint column is a lightweight rules engine. A query that scans 50GB to return 500 rows has an obvious problem — either clustering is wrong, filters are missing, or the query pattern is fundamentally inefficient. The profiling and optimizing slow dbt models guide dives deep into diagnosing these patterns from query plans.
The queries above give you retrospective visibility. For prospective detection — catching problems before they exhaust your budget — you need a comparison against baseline:
-- Daily spend anomaly detection
-- Compare today's credit consumption to the 7-day moving average
WITH daily_credits AS (
SELECT
DATE_TRUNC('day', start_time) AS query_date,
warehouse_name,
SUM(
(GREATEST(total_elapsed_time, 60000) / 3600000.0) *
CASE warehouse_size
WHEN 'X-Small' THEN 1 WHEN 'Small' THEN 2 WHEN 'Medium' THEN 4
WHEN 'Large' THEN 8 WHEN 'X-Large' THEN 16 WHEN '2X-Large' THEN 32
WHEN '3X-Large' THEN 64 WHEN '4X-Large' THEN 128 ELSE 0
END
) AS daily_credits
FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
WHERE
start_time >= CURRENT_DATE() - 30
AND execution_status = 'SUCCESS'
AND warehouse_name IS NOT NULL
GROUP BY 1, 2
),
with_baseline AS (
SELECT
query_date,
warehouse_name,
daily_credits,
AVG(daily_credits) OVER (
PARTITION BY warehouse_name
ORDER BY query_date
ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING
) AS seven_day_avg,
STDDEV(daily_credits) OVER (
PARTITION BY warehouse_name
ORDER BY query_date
ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING
) AS seven_day_stddev
FROM daily_credits
)
SELECT
query_date,
warehouse_name,
ROUND(daily_credits, 2) AS daily_credits,
ROUND(seven_day_avg, 2) AS seven_day_avg,
ROUND(daily_credits - seven_day_avg, 2) AS delta_from_avg,
ROUND(
(daily_credits - seven_day_avg) / NULLIF(seven_day_stddev, 0),
2
) AS z_score,
CASE
WHEN (daily_credits - seven_day_avg) / NULLIF(seven_day_stddev, 0) > 2
THEN 'ANOMALY — spend significantly above baseline'
WHEN (daily_credits - seven_day_avg) / NULLIF(seven_day_stddev, 0) > 1.5
THEN 'ELEVATED — spend above normal range'
ELSE 'NORMAL'
END AS status
FROM with_baseline
WHERE query_date >= CURRENT_DATE() - 7
ORDER BY z_score DESC NULLS LAST;
A Z-score above 2.0 on a specific warehouse is a meaningful signal. It doesn't necessarily mean something is wrong — month-end reporting, a large backfill, or a new feature launch can all legitimately spike spend. But it means you should know why spend is elevated. If you can't explain the spike, that's when you investigate.
Technical controls are only half of cost governance. The other half is organizational process — who owns what, how budget is allocated, and what happens when a team exceeds their allocation.
The warehouse-based resource monitor strategy maps naturally to a budget allocation model. Each warehouse represents a cost center, and each cost center has an owner:
Warehouse Owner Monthly Budget
--------------------------------------------------------------
PROD_LOADING_WH Data Engineering $8,000
PROD_TRANSFORM_WH Analytics Engineering $24,000
PROD_BI_WH Analytics Engineering $9,000
PROD_ADHOC_WH All Analysts $4,500
DEV_TRANSFORM_WH Analytics Engineering $3,000
--------------------------------------------------------------
Account Safety Net $60,000 (ceiling)
This structure creates accountability. When the PROD_ADHOC_WH monitor triggers at 50%, someone specific is notified and empowered to investigate. Without a designated owner, alerts go to everyone and therefore to no one.
Create a runbook that specifies exactly what happens at each alert threshold. This prevents alert fatigue (where engineers learn to ignore notifications) and ensures consistent response:
## Resource Monitor Alert Response Runbook
### INFO (50% threshold)
- Automated Slack notification to #data-costs channel
- Monitor owner reviews ACCOUNT_USAGE.QUERY_HISTORY for unusual patterns
- No action required unless anomaly detected
- Log review in weekly cost review meeting
### WARNING (75-85% threshold)
- Automated Slack notification with @here to #data-costs
- Monitor owner must respond within 2 business hours
- Run anomaly detection query and identify top cost drivers
- If runaway job identified: coordinate with job owner to terminate or reschedule
- If legitimate business activity: document reason and assess whether budget
ceiling needs to be raised for the month
### CRITICAL (90-95% threshold)
- PagerDuty alert to on-call data engineer
- Review all currently-running queries >10 minutes on affected warehouse
- Terminate non-essential long-running queries with SYSTEM$CANCEL_QUERY
- Notify stakeholders that warehouse may be suspended imminently
- Prepare incident report
### SUSPENSION (100% threshold)
- Immediate incident declared
- Notify all teams using suspended warehouse
- Assess whether temporary credit quota increase is warranted
- Run root cause analysis within 24 hours
- Update budget for following month if spend was legitimate
This runbook makes the resource monitor strategy operational rather than theoretical. It answers the question every engineer asks when they see an alert: "What am I supposed to do about this?"
Tip
Store this runbook as a code comment in the same Terraform or dbt macro file that creates your resource monitors. When someone updates the monitor configuration, they'll see the runbook and understand the operational context. Runbooks that live in wikis get stale; runbooks that live next to the code they describe tend to stay current.
Your dbt project is probably responsible for the majority of your Snowflake compute spend. That makes it both your biggest cost risk and your biggest governance opportunity. Beyond query tags (which we've already covered), there are several dbt-native patterns that directly reduce or control costs.
dbt's +snowflake_warehouse configuration lets you route specific models to specific warehouses. This is powerful for cost control — your largest, most expensive models can run on a dedicated warehouse with its own resource monitor, separate from interactive queries:
# dbt_project.yml
models:
your_project_name:
# Default all models to the standard transform warehouse
+snowflake_warehouse: PROD_TRANSFORM_WH
# Override for large marts that need more compute
marts:
core:
+snowflake_warehouse: PROD_TRANSFORM_WH
# This mart does heavy aggregation across 2 years of events
# Route it to a temporary X-Large warehouse
event_aggregates:
+snowflake_warehouse: PROD_HEAVY_TRANSFORM_WH
# Staging models are lightweight — use a smaller warehouse
staging:
+snowflake_warehouse: PROD_TRANSFORM_SM_WH
This pattern lets you scale compute dynamically based on the actual needs of different model tiers rather than sizing your warehouse for the worst case across all models.
Incremental models are fundamentally a cost governance pattern. By processing only new or changed data rather than rebuilding full tables, you reduce the compute required per dbt run dramatically. If you're not already using incremental models for your high-volume fact tables, you're leaving significant cost savings on the table. The incremental models at scale guide covers the implementation details, but the cost implications deserve emphasis: switching a 400GB fact table from full-refresh to incremental can reduce per-run compute cost by 95%.
One underappreciated governance gap is CI/CD pipelines. If your CI pipeline runs dbt test and potentially dbt build against full production data, you're paying production-scale compute for every pull request. This adds up fast in teams with active development.
The fix is Slim CI — using dbt ls --select state:modified+ to identify only the models changed in a PR and running those against a development warehouse with a sample dataset. See Automating dbt Environment Promotion with CI/CD Pipelines, Slim CI, and State-Aware Deployments for full implementation details.
The cost governance addition is to give your CI warehouse its own resource monitor with a strict daily budget:
CREATE OR REPLACE RESOURCE MONITOR CI_MONITOR
WITH CREDIT_QUOTA = 100 -- $300/month maximum for CI
FREQUENCY = MONTHLY
START_TIMESTAMP = IMMEDIATELY
TRIGGERS
ON 50 PERCENT DO NOTIFY
ON 90 PERCENT DO SUSPEND;
ALTER WAREHOUSE CI_WH SET RESOURCE_MONITOR = CI_MONITOR;
If your CI is consuming 50 credits before mid-month, that's a signal that your CI pipeline is running against full data or running too frequently — both worth investigating.
In this exercise, you'll implement a complete cost governance foundation for a hypothetical mid-size analytics team. Work through each step in order against a Snowflake account where you have SYSADMIN access.
Setup: You're the analytics engineering lead for a 20-person team. Your Snowflake account runs dbt production jobs, Looker, and analyst queries. You've been asked to implement cost governance before the company's Series B audit.
Step 1: Audit your current warehouse topology
Run this query to see what warehouses exist and how they're currently used:
-- Current warehouse inventory and usage
SELECT
w.name AS warehouse_name,
w.warehouse_size,
w.auto_suspend,
w.auto_resume,
w.resource_monitor,
-- Credits consumed last 30 days
COALESCE(SUM(wm.credits_used), 0) AS credits_last_30_days,
ROUND(COALESCE(SUM(wm.credits_used), 0) * 3.0, 2) AS estimated_cost_usd
FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSES w
LEFT JOIN SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY wm
ON w.name = wm.warehouse_name
AND wm.start_time >= CURRENT_DATE() - 30
WHERE w.deleted IS NULL
GROUP BY 1, 2, 3, 4, 5
ORDER BY credits_last_30_days DESC;
Document your findings. How many warehouses have no resource monitor assigned (resource_monitor = NULL)? What's the auto-suspend interval on each?
Step 2: Create your warehouse structure if needed
If you're running everything on one or two warehouses, create the functional separation:
USE ROLE SYSADMIN;
CREATE WAREHOUSE IF NOT EXISTS PROD_TRANSFORM_WH
WAREHOUSE_SIZE = 'LARGE'
AUTO_SUSPEND = 300 -- 5 minutes for transform workloads
AUTO_RESUME = TRUE
INITIALLY_SUSPENDED = TRUE
COMMENT = 'Production dbt transformation jobs';
CREATE WAREHOUSE IF NOT EXISTS PROD_BI_WH
WAREHOUSE_SIZE = 'MEDIUM'
AUTO_SUSPEND = 60 -- 1 minute for BI (many short queries)
AUTO_RESUME = TRUE
INITIALLY_SUSPENDED = TRUE
COMMENT = 'Looker and Tableau dashboards';
CREATE WAREHOUSE IF NOT EXISTS PROD_ADHOC_WH
WAREHOUSE_SIZE = 'SMALL'
AUTO_SUSPEND = 120
AUTO_RESUME = TRUE
INITIALLY_SUSPENDED = TRUE
COMMENT = 'Analyst ad-hoc queries and exploration';
Step 3: Implement resource monitors
Using the ACCOUNTADMIN role, create monitors as described in the main lesson. Set the credit quota for each warehouse based on your historical usage from Step 1 — target 120% of your 30-day average as the monthly quota (giving headroom for legitimate growth while catching runaway spend).
Step 4: Implement query tagging in your dbt project
Add the set_query_tag macro from the main lesson. Add these environment variables to your dbt invocation (via .env file for local runs, via Airflow/CI configuration for automated runs):
export DBT_TEAM="analytics_engineering"
export DBT_PIPELINE_NAME="nightly_transform"
export GIT_SHA=$(git rev-parse --short HEAD)
Run dbt run and then verify tagging is working:
-- Verify query tags are appearing correctly
SELECT
query_id,
query_tag,
TRY_PARSE_JSON(query_tag) AS parsed_tag,
start_time,
total_elapsed_time / 1000 AS elapsed_seconds
FROM SNOWFLAKE.INFORMATION_SCHEMA.QUERY_HISTORY
WHERE
start_time >= CURRENT_TIMESTAMP() - INTERVAL '1 hour'
AND query_tag != ''
ORDER BY start_time DESC
LIMIT 20;
Step 5: Build your cost dashboard
Create a table to store daily cost attribution results:
CREATE TABLE IF NOT EXISTS analytics.admin.daily_cost_attribution (
report_date DATE,
warehouse_name VARCHAR,
team VARCHAR,
pipeline VARCHAR,
dbt_model VARCHAR,
query_count INTEGER,
total_credits FLOAT,
estimated_cost_usd FLOAT,
avg_elapsed_seconds FLOAT,
inserted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP()
);
Schedule the daily cost attribution query from the main lesson to insert into this table via an Airflow DAG (see Orchestrating dbt Runs with Airflow for Airflow setup patterns). After a week of data accumulates, you'll have your first cost trend report.
Teams new to resource monitors often set quotas at their current spending level, then get surprised when legitimate workloads trigger suspension at the end of the month. The result is a cascade of "why is Snowflake down?" Slack messages right when your CFO wants that report.
Fix: Set initial quotas at 150% of current 30-day average spend. Tighten over 2-3 months as you understand your baseline better. The goal of initial monitors is visibility and emergency protection, not optimization.
A single account-level monitor tells you that someone is spending money, but not who or why. When it triggers at 90%, you can't take targeted action.
Fix: Always implement warehouse-level monitors as your primary governance layer. The account-level monitor is a safety net, not a management tool.
If env_var("DBT_TEAM") is called without a default value and that environment variable isn't set, your dbt run will fail with a confusing error about a missing variable — not a missing query tag.
Fix: Always use env_var("VARIABLE_NAME", "default_value") with a sensible default. The example above uses "unknown" as the default, which at least preserves the JSON structure even if attribution is incomplete.
Teams sometimes build dashboards against ACCOUNT_USAGE.QUERY_HISTORY and then wonder why their monitoring doesn't catch problems in real time.
Fix: For real-time alerting (catching a runaway query in progress), use SNOWFLAKE.INFORMATION_SCHEMA.QUERY_HISTORY which has no lag. For historical analysis and attribution reporting, use ACCOUNT_USAGE.QUERY_HISTORY which is complete and has no row limits.
Here's a subtle one: if your multi-cluster warehouse scales from 1 to 4 clusters, the resource monitor measures credits consumed by all clusters combined. But the warehouse size shown in QUERY_HISTORY.WAREHOUSE_SIZE is the size of a single cluster, not the total. Your per-query credit calculation in ACCOUNT_USAGE queries will underestimate cost by a factor of up to 4 for queries that ran during peak multi-cluster scale-out.
Fix: For true billing accuracy, always use WAREHOUSE_METERING_HISTORY as your source for warehouse-level credit consumption. Cross-reference query timing from QUERY_HISTORY with metering intervals to understand per-query cost within multi-cluster contexts.
If your dbt session's connection is reused by another tool (common in connection pooling scenarios), queries from that other tool will inherit your dbt session's query tag. This pollutes your attribution data — your BI tool's queries will appear to be dbt models.
Fix: The on-run-end hook in the dbt configuration above sets the tag to empty string. Verify this is running by checking INFORMATION_SCHEMA.QUERY_HISTORY for the ALTER SESSION SET QUERY_TAG = '' statement after your runs.
Warning
Snowflake query tags are stored as strings and have a maximum length of 2000 characters. If you're tempted to include verbose metadata like full SQL text or long branch names in your tags, be careful. JSON tags that exceed 2000 characters are silently truncated, which will break TRY_PARSE_JSON() and cause your attribution queries to return NULL for affected records. Keep tags concise — IDs and short strings, not full text blobs.
You now have all the components of a production cost governance system for Snowflake. Let's consolidate the architecture:
Structural layer: A deliberate warehouse topology that maps workloads to dedicated warehouses, enabling clean cost attribution and independent sizing. Each warehouse has an owner and a purpose.
Enforcement layer: Account-level and warehouse-level resource monitors that act as circuit breakers. Account-level provides emergency protection; warehouse-level provides team-specific budget accountability with graduated alerting thresholds.
Attribution layer: Systematic query tagging via dbt macros and session-level SQL that captures team, pipeline, model, environment, and run context on every query. This turns your ACCOUNT_USAGE.QUERY_HISTORY data from a log into a cost accounting ledger.
Observability layer: SQL-based cost queries that surface daily attribution, top cost drivers, and statistical anomaly detection. These run on a schedule and feed dashboards and alerting systems, giving you a continuous view of spend before it hits thresholds.
Process layer: A governance runbook that specifies ownership and response procedures for each alert level, turning technical signals into organizational accountability.
The specific numbers in this lesson (credit quotas, alert thresholds, budget allocations) are examples. Your actual values should be calibrated to your team's historical usage, your organization's financial structure, and your risk tolerance. Start with conservative monitoring configurations and tune them over the first few months as you observe how your workloads actually behave.
Recommended next steps:
The goal of all this work isn't to minimize spend — it's to make spend predictable, attributable, and proportional to value. When you can point to a dbt model and say "that model costs $400/month to run and powers the revenue dashboard that drives $2M in business decisions," you're not fighting for budget; you're demonstrating ROI.
Modern Data Stack