🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Snowflake Provider Integration with Airflow

đŸŸĸ Free Lesson

Snowflake Provider Integration with Airflow

Snowflake Integration ArchitectureAirflowSchedulerSnowflakeHookConnection + SQLSnowflakeData warehouseExternal StageS3 / GCS / AzureSnowpipeAuto-ingestSnowflakeOperatorExecute SQLGCSToSnowflakeLoad from GCSCopyFromStageCOPY INTOTransferOperatorCross-region copyUse key pair auth for production; Snowpipe for continuous data loading

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

OperatorUse CaseKey Parameters
SnowflakeOperatorExecute SQLsql, snowflake_conn_id
SnowflakeToGCSOperatorExport to GCSgcs_bucket, sql
GCSToSnowflakeOperatorLoad from GCSbucket, prefix, table
SnowflakeCopyFromExternalStageCOPY INTOtable, stage, file_format
SnowflakeSensorWait for conditionsql, 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

python
# 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

python
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

python
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

python
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

python
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.

LeverEffect on the billPractical setting
AUTO_SUSPENDidle seconds before the warehouse stops60 seconds for ETL warehouses
AUTO_RESUMEwhether the next statement wakes itleave enabled for scheduled tasks
Scaling policywhen extra clusters join the queueSTANDARD for batch windows, ECONOMY for trickle
QUERY_TAGwhich DAG generated the creditscarry 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.

PathTriggered byFits whenWhat you monitor
COPY INTO from a taskthe DAG schedulethe load must gate what runs after itrows_loaded together with task retries
Snowpipe with auto-ingestobject-create event on the stagesmall files arrive continuouslypending bytes in the pipe status
Transfer operatoran explicit Airflow taskdata has to cross accounts or regionsjob 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

  1. Use named stages for reusable external connections — avoid embedded credentials.
  2. Set ON_ERROR appropriately: SKIP_FILE for bad files, CONTINUE for partial loads.
  3. Partition large COPY INTO operations with SIZE_LIMIT to avoid single large transactions.
  4. Use PURGE = TRUE to clean up files after successful load.

Monitoring and Cost

  1. Set QUERY_TAG for monitoring and cost attribution per Airflow DAG.
  2. Monitor Snowpipe status with SHOW PIPES and SYSTEM$PIPE_STATUS.

Security and Performance

  1. Use key-pair authentication for production — avoid password-based connections.
  2. Leverage clustering keys for frequently joined/filtered columns.

See Also

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Airflow Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement