Snowflake Provider Integration with Airflow
Architecture Diagram
Formal Definitions
Detailed Explanation
Snowflake Integration Overview
The Snowflake provider enables Airflow to execute SQL, load data, and manage Snowflake resources. It supports COPY INTO operations, Snowpipe management, and data transfer between Snowflake and cloud storage.
âšī¸Keep Airflow out of the continuous-ingest path
Auto-ingest Snowpipe fires on object-create events, so Airflow only has to create the pipe, watch SYSTEM$PIPE_STATUS and alert on backlog. Scheduling a DAG that polls for new files every five minutes duplicates what the notification channel already tells Snowflake.
Operator Selection Guide
| Operator | Use Case | Key Parameters |
|---|---|---|
| SnowflakeOperator | Execute SQL | sql, snowflake_conn_id |
| SnowflakeToGCSOperator | Export to GCS | gcs_bucket, sql |
| GCSToSnowflakeOperator | Load from GCS | bucket, prefix, table |
| SnowflakeCopyFromExternalStage | COPY INTO | table, stage, file_format |
| SnowflakeSensor | Wait for condition | sql, poke_interval |
COPY INTO Options
The options that matter most are FILE_FORMAT for the parser, PATTERN for selecting files, ON_ERROR for failure handling, FORCE to reload a file already ingested, and PURGE to remove files after a successful load. The full set is exercised in the load examples below.
Connection Setup
# Airflow connection for Snowflake
# Connection ID: snowflake_default
# Connection Type: Snowflake
# Host: <account>.snowflakecomputing.com
# Schema: PUBLIC
# Database: ANALYTICS
# Warehouse: COMPUTE_WH
# Account: <account_identifier>
# Login: <username>
# Password: <password> (or use private_key for key-pair auth)
# Extra: {
# "region": "us-east-1",
# "warehouse": "COMPUTE_WH",
# "database": "ANALYTICS",
# "role": "SYSADMIN"
# }
Basic SQL Execution
from datetime import datetime, timedelta
from airflow import DAG
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
with DAG(
dag_id='snowflake_etl',
start_date=datetime(2024, 1, 1),
schedule_interval='@daily',
catchup=False,
tags=['snowflake', 'etl'],
) as dag:
create_schema = SnowflakeOperator(
task_id='create_schema',
snowflake_conn_id='snowflake_default',
sql="""
CREATE SCHEMA IF NOT EXISTS raw;
CREATE SCHEMA IF NOT EXISTS staging;
CREATE SCHEMA IF NOT EXISTS analytics;
""",
)
create_table = SnowflakeOperator(
task_id='create_orders_table',
snowflake_conn_id='snowflake_default',
sql="""
CREATE TABLE IF NOT EXISTS staging.orders (
order_id INTEGER,
customer_id INTEGER,
amount DECIMAL(10,2),
order_date TIMESTAMP_NTZ,
status VARCHAR(20)
)
CLUSTER BY (order_date);
""",
)
load_data = SnowflakeOperator(
task_id='load_orders',
snowflake_conn_id='snowflake_default',
sql="""
COPY INTO staging.orders
FROM @raw_stage/orders/
FILE_FORMAT = (
TYPE = 'PARQUET'
COMPRESSION = 'SNAPPY'
)
PATTERN = '.*\\.parquet'
ON_ERROR = 'SKIP_FILE';
""",
)
transform = SnowflakeOperator(
task_id='transform_orders',
snowflake_conn_id='snowflake_default',
sql="""
MERGE INTO analytics.fct_orders AS target
USING (
SELECT
order_id,
customer_id,
SUM(amount) as total_amount,
COUNT(*) as order_count,
MAX(order_date) as last_order_date
FROM staging.orders
WHERE order_date >= DATEADD(day, -1, CURRENT_DATE())
GROUP BY order_id, customer_id
) AS source
ON target.order_id = source.order_id
WHEN MATCHED THEN UPDATE SET
total_amount = source.total_amount,
order_count = source.order_count,
last_order_date = source.last_order_date
WHEN NOT MATCHED THEN INSERT
(order_id, customer_id, total_amount, order_count, last_order_date)
VALUES (source.order_id, source.customer_id, source.total_amount,
source.order_count, source.last_order_date);
""",
)
create_schema >> create_table >> load_data >> transform
GCS to Snowflake Loading
from airflow.providers.snowflake.operators.snowflake import (
SnowflakeOperator,
)
# Step 1: Create a named stage pointing to GCS
create_stage = SnowflakeOperator(
task_id='create_gcs_stage',
snowflake_conn_id='snowflake_default',
sql="""
CREATE OR REPLACE STAGE raw.raw_stage
URL = 'gcs://data-lake/raw/orders/'
STORAGE_INTEGRATION = gcs_integration;
""",
)
# Step 2: List files in stage
list_files = SnowflakeOperator(
task_id='list_stage_files',
snowflake_conn_id='snowflake_default',
sql="LIST @raw.raw_stage;",
)
# Step 3: Load with COPY INTO
load_from_stage = SnowflakeOperator(
task_id='load_from_stage',
snowflake_conn_id='snowflake_default',
sql="""
COPY INTO staging.orders
FROM @raw.raw_stage
FILE_FORMAT = (
TYPE = 'CSV'
FIELD_DELIMITER = '|'
SKIP_HEADER = 1
NULL_IF = ('NULL', 'null', '')
)
PATTERN = 'orders_.*\\.csv'
ON_ERROR = 'CONTINUE';
""",
)
create_stage >> list_files >> load_from_stage
Pre/Post Operator Pattern
from airflow.providers.snowflake.operators.snowflake import (
SnowflakeOperator,
)
# Pre-task: Set session parameters
pre_task = SnowflakeOperator(
task_id='set_session_params',
snowflake_conn_id='snowflake_default',
sql="""
ALTER SESSION SET TIMEZONE = 'UTC';
ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = 3600;
ALTER SESSION SET QUERY_TAG = 'airflow_etl_{{ ds }}';
""",
)
# Main ETL task
etl_task = SnowflakeOperator(
task_id='run_etl',
snowflake_conn_id='snowflake_default',
sql="CALL run_etl_procedure('{{ ds }}');",
)
# Post-task: Clean up
post_task = SnowflakeOperator(
task_id='cleanup',
snowflake_conn_id='snowflake_default',
sql="""
ALTER SESSION UNSET QUERY_TAG;
TRUNCATE TABLE staging.temp_data;
""",
)
pre_task >> etl_task >> post_task
Multi-Warehouse Pattern
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
warehouses = {
'heavy_etl': 'COMPUTE_WH_HEAVY',
'light_transform': 'COMPUTE_WH_LIGHT',
'ad_hoc': 'COMPUTE_WH_ADHOC',
}
for task_name, warehouse in warehouses.items():
SnowflakeOperator(
task_id=f'task_{task_name}',
snowflake_conn_id='snowflake_default',
sql=f"""
ALTER WAREHOUSE {warehouse} RESUME IF SUSPENDED;
-- ETL logic here
""",
warehouse=warehouse,
)
Session State and Warehouse Billing
Snowflake sessions carry state, and tasks inherit whatever state a connection leaves behind. ALTER SESSION SET TIMEZONE, STATEMENT_TIMEOUT_IN_SECONDS and QUERY_TAG take effect for the current session only, yet hooks borrow sessions from a pool, so a setting applied by one task can still be active when the next task reuses that session. Set the parameters you depend on at the beginning of every task and unset them afterwards, exactly as the pre-task and post-task pair above does, instead of assuming a clean session.
Warehouses bill per second while they run, which makes AUTO_SUSPEND, AUTO_RESUME and the scaling policy the levers that matter. A warehouse that suspends 60 seconds after its last query costs almost nothing between nightly runs and still wakes on the next statement of the following task. The scaling policy is a schedule decision: STANDARD provisions capacity as soon as queries queue, ECONOMY holds back for a while â right for a trickle of ad-hoc work, wrong for a batch window that must start at full width.
| Lever | Effect on the bill | Practical setting |
|---|---|---|
AUTO_SUSPEND | idle seconds before the warehouse stops | 60 seconds for ETL warehouses |
AUTO_RESUME | whether the next statement wakes it | leave enabled for scheduled tasks |
| Scaling policy | when extra clusters join the queue | STANDARD for batch windows, ECONOMY for trickle |
QUERY_TAG | which DAG generated the credits | carry the DAG id and logical date |
Stage, Task or Snowpipe
Three routes move files into Snowflake and each fails differently. A COPY INTO issued from a task runs inside the DAG, so it inherits retries, gates downstream work and holds the warehouse for the length of the load. A pipe with auto-ingest reacts to an object-create event and returns within milliseconds, leaving Airflow to observe rather than to drive. A transfer operator that copies across regions or accounts runs as its own job, so without a bounded poll it can outlive the task that started it.
| Path | Triggered by | Fits when | What you monitor |
|---|---|---|---|
COPY INTO from a task | the DAG schedule | the load must gate what runs after it | rows_loaded together with task retries |
| Snowpipe with auto-ingest | object-create event on the stage | small files arrive continuously | pending bytes in the pipe status |
| Transfer operator | an explicit Airflow task | data has to cross accounts or regions | job state and rows moved |
Confirming the Load Landed
Every COPY INTO answers with a result set rather than a bare status. rows_parsed, rows_loaded and errors_seen describe what the statement did, and querying RESULT_SCAN of the previous statement turns those numbers into an assertion in the next task instead of a line somebody reads after an incident. RETURN_FAILED_ONLY = TRUE narrows the output to the files that failed, and SYSTEM$COPY_LOAD_ERRORS returns the parse errors themselves â the place where a mismatched FIELD_DELIMITER, an unexpected null token or a truncated column first becomes visible.
The ON_ERROR setting decides how much damage one bad file can cause. ABORT_STATEMENT leaves the target exactly as it was, SKIP_FILE discards the whole file and continues, and CONTINUE keeps the rows that parsed and counts the rejects. Pick it before the load: a table with silent rejects costs far more to repair than one that refused the file in the first place.
Best Practices
Data Loading
- Use named stages for reusable external connections â avoid embedded credentials.
- Set
ON_ERRORappropriately:SKIP_FILEfor bad files,CONTINUEfor partial loads. - Partition large COPY INTO operations with
SIZE_LIMITto avoid single large transactions. - Use
PURGE = TRUEto clean up files after successful load.
Monitoring and Cost
- Set
QUERY_TAGfor monitoring and cost attribution per Airflow DAG. - Monitor Snowpipe status with
SHOW PIPESandSYSTEM$PIPE_STATUS.
Security and Performance
- Use key-pair authentication for production â avoid password-based connections.
- Leverage clustering keys for frequently joined/filtered columns.
See Also
- BigQuery Provider â Google BigQuery integration patterns
- Databricks Provider â Databricks cluster and job management
- Operators and Hooks â Operator lifecycle and hook architecture
- XCom Communications â Task communication and data passing