Author: Sainath Reddy

  • The Problem with Zero-Copy Cloning in Snowflake That Nobody Talks About

    The Problem with Zero-Copy Cloning in Snowflake That Nobody Talks About

    Every time I demo Snowflake to someone new, zero-copy cloning gets the biggest reaction. You type one line and get an instant copy of a table, or an entire database, with no data duplication and no storage cost at the moment of creation. It feels like magic.

    And it is impressive engineering. I’m not here to tell you it’s a bad feature. It’s one of my favourite things about Snowflake and I use it constantly.

    But I’ve watched teams get badly surprised by it. A dev environment clone that started silently inflating the storage bill. A cloned database used for UAT that bypassed data masking policies on PII columns. A Time Travel query on a clone that returned nothing because the source table’s retention window had already expired.

    None of these are edge cases. They’re predictable consequences of how zero-copy cloning works, and the marketing language around “instant, free copies” tends to hide them. If you use clones for dev, UAT or migrations, this post walks through how cloning works under the hood, five places where it catches teams out, and how to use it without it becoming a liability.


    How zero-copy cloning actually works

    When you clone a table in Snowflake, you’re not copying data. You’re creating a new metadata pointer that references the same underlying micro-partitions as the source object.

    -- Instant. No data movement. No storage cost at this moment.
    CREATE TABLE orders_clone CLONE orders;
    
    -- Works for schemas too
    CREATE SCHEMA dev_schema CLONE prod_schema;
    
    -- And entire databases
    CREATE DATABASE dev_db CLONE prod_db;

    At the moment of creation, the clone costs you nothing in storage. Both the original and the clone point to the same micro-partitions. The moment either side changes, Snowflake uses copy-on-write: the modified micro-partition is written fresh for whichever side made the change.

    Think of it like a fork of a Git repo. At fork time, both repos share the same commit history. The moment either side commits, they diverge, and the more they diverge, the more independent storage you accumulate. Zero-copy cloning works the same way, except the “commits” are DML operations and the cost is real money.


    Problem 1: Storage costs that creep up invisibly

    A team clones production to create a development environment. The dev team runs experiments, updates records and backfills some columns. Six weeks later, storage is up 40%. Every modified micro-partition in the dev database is now independent storage. Production kept its micro-partitions too, so you’re paying for both.

    The cost also compounds with Time Travel. If production has 90-day retention and you clone it for dev, the clone also starts with 90-day retention, so DML in dev accumulates 90 days of write history.

    -- Clone with reduced Time Travel for non-production environments
    CREATE DATABASE dev_db CLONE prod_db;
    
    -- Immediately reduce Time Travel on the clone
    ALTER DATABASE dev_db SET DATA_RETENTION_TIME_IN_DAYS = 1;
    
    -- Or set it at schema level for finer control
    ALTER SCHEMA dev_db.analytics SET DATA_RETENTION_TIME_IN_DAYS = 0;

    Audit the clone storage footprint regularly:

    -- CLONE_GROUP_ID lives in TABLE_STORAGE_METRICS; a table is a clone when ID <> CLONE_GROUP_ID.
    SELECT
        m.table_catalog,
        m.table_schema,
        m.table_name,
        m.clone_group_id,
        m.active_bytes / POWER(1024, 3)               AS size_gb,
        m.retained_for_clone_bytes / POWER(1024, 3)   AS retained_for_clone_gb,
        t.row_count,
        m.table_created                               AS clone_created_at
    FROM snowflake.account_usage.table_storage_metrics m
    LEFT JOIN snowflake.account_usage.tables t
           ON t.table_id = m.id
    WHERE m.id <> m.clone_group_id
      AND m.deleted = FALSE
    ORDER BY m.active_bytes DESC;

    This lists cloned tables that still exist, largest first, with their size in GB and when they were created. Run it on a schedule rather than once.

    This kind of invisible cost creep comes up a lot with Snowflake features that look free until you read the bill. I covered a similar case in Why I Stopped Using Snowflake Tasks for Orchestration.


    Problem 2: Governance policies don’t follow the clone

    Dynamic data masking policies are not automatically inherited by clones. The clone is a new object with no masking policies applied.

    -- On prod table — email is masked for non-PII roles
    SELECT email FROM prod_orders LIMIT 5;
    -- Result: ***@***.com (masked)
    
    -- On the clone without explicit policy assignment
    SELECT email FROM orders_clone LIMIT 5;
    -- Result: [email protected] (unmasked raw PII)

    The same applies to row access policies. A user restricted to one region in production can see all regions on the clone.

    The fix — make policy application part of your clone process:

    -- Step 1: Clone the table
    CREATE TABLE dev_db.analytics.orders CLONE prod_db.analytics.orders;
    
    -- Step 2: Re-apply masking policies immediately
    ALTER TABLE dev_db.analytics.orders
        MODIFY COLUMN email
        SET MASKING POLICY prod_db.security.email_mask;
    
    ALTER TABLE dev_db.analytics.orders
        MODIFY COLUMN phone_number
        SET MASKING POLICY prod_db.security.phone_mask;
    
    -- Step 3: Re-apply row access policy
    ALTER TABLE dev_db.analytics.orders
        ADD ROW ACCESS POLICY prod_db.security.region_access_policy
        ON (region_code);

    The policies stay in prod_db.security and are attached to the cloned table’s email, phone_number and region_code columns. Replace the column and policy names with your own.

    Better still, wrap it in a stored procedure so policy application is part of the clone operation itself:

    CREATE OR REPLACE PROCEDURE create_governed_clone(
        source_table      VARCHAR,
        target_table      VARCHAR,
        masking_policies  ARRAY
    )
    RETURNS STRING
    LANGUAGE JAVASCRIPT
    AS
    $$
        var clone_stmt = snowflake.execute({
            sqlText: `CREATE TABLE ${TARGET_TABLE} CLONE ${SOURCE_TABLE}`
        });
    
        for (var i = 0; i < MASKING_POLICIES.length; i++) {
            var policy = MASKING_POLICIES[i];
            snowflake.execute({
                sqlText: `ALTER TABLE ${TARGET_TABLE}
                          MODIFY COLUMN ${policy.column}
                          SET MASKING POLICY ${policy.policy_name}`
            });
        }
    
        return 'Clone created with governance policies applied: ' + TARGET_TABLE;
    $$;

    The procedure clones the source table, then loops over the masking_policies array, where each element is an object with a column and a policy_name, and applies each policy to the new table. Note that JavaScript procedures refer to arguments in upper case (TARGET_TABLE, MASKING_POLICIES), and this version handles masking policies only, not row access policies.

    A clone without its governance policies re-applied is a compliance gap, not a convenience feature. If you run dbt on top of Snowflake, the same mindset applies; see The Problem with dbt Tests Nobody Talks About.

    Problem 3: Time Travel on clones isn’t what you think

    A clone’s Time Travel history starts from its creation date. On the clone object, you cannot go back to a point before the clone was created.

    -- Source table: exists since 2024-01-01, 90-day retention
    -- Clone created: 2024-03-01
    
    -- This works — within the clone's own history
    SELECT * FROM orders_clone
    AT (TIMESTAMP => '2024-03-15 10:00:00'::TIMESTAMP_TZ);
    
    -- This FAILS — before the clone existed
    SELECT * FROM orders_clone
    AT (TIMESTAMP => '2024-02-01 10:00:00'::TIMESTAMP_TZ);
    -- Error: Statement time travel is not available for this object
    
    -- For pre-clone history, query the SOURCE table
    SELECT * FROM orders
    AT (TIMESTAMP => '2024-02-01 10:00:00'::TIMESTAMP_TZ);

    The first query reads the clone at a point after it was created and works. The second asks the clone for a point before it existed and fails. For that history, go back to the source table, as in the third query.

    Also watch the source’s retention window: if you clone a table near the end of it, any history that expires on the source is gone, and the clone can’t reach it.


    Problem 4: Clone sprawl and the invisible cost problem

    Cloning is so easy that people create clones for everything: UAT, load testing, feature branches, one-off investigations that were supposed to be deleted on Friday. Three months later, nobody knows what exists or how far it has diverged.

    Full clone audit query:

    SELECT
        t.table_catalog                                   AS database_name,
        t.table_schema                                    AS schema_name,
        t.table_name,
        t.clone_group_id,
        t.row_count,
        ROUND(t.bytes / POW(1024, 3), 3)                  AS size_gb,
        t.created                                         AS created_at,
        t.last_altered                                    AS last_modified_at,
        DATEDIFF('day', t.created, CURRENT_TIMESTAMP())   AS age_days,
        CASE
            WHEN DATEDIFF('day', t.last_altered, CURRENT_TIMESTAMP()) > 30
            THEN 'STALE — review for deletion'
            ELSE 'Active'
        END AS staleness_flag
    FROM snowflake.account_usage.tables t
    WHERE t.clone_group_id IS NOT NULL
      AND t.deleted IS NULL
    ORDER BY t.bytes DESC;

    This extends the earlier query with age in days and a staleness flag for any clone not altered in the last 30 days. Change the 30-day threshold to suit how long your UAT and test clones normally live.

    Tag every clone at creation with expiry metadata:

    CREATE DATABASE uat_db CLONE prod_db
        COMMENT = '{"purpose": "UAT for v2.4 release", "owner": "[email protected]", "expires": "2024-04-30", "ticket": "JIRA-1234"}';
    
    -- Query clones past their expiry date
    SELECT
        table_catalog,
        table_schema,
        table_name,
        TRY_PARSE_JSON(comment):expires::DATE AS expiry_date,
        TRY_PARSE_JSON(comment):owner::STRING AS owner
    FROM snowflake.account_usage.tables
    WHERE clone_group_id IS NOT NULL
      AND deleted IS NULL
      AND TRY_PARSE_JSON(comment):expires::DATE < CURRENT_DATE();

    The comment is plain JSON, so you can parse it with TRY_PARSE_JSON and filter on the expires date to find clones that should already be gone, along with who owns them.

    Problem 5: Cloning streams and tasks doesn’t work how you expect

    Streams are not cloned when you clone a table or schema. The clone contains the data but has no streams attached.

    -- Prod table has a stream attached
    SHOW STREAMS ON TABLE prod_db.analytics.orders;
    -- Returns: orders_cdc_stream
    
    -- Clone the table
    CREATE TABLE dev_db.analytics.orders CLONE prod_db.analytics.orders;
    
    -- Check streams on clone
    SHOW STREAMS ON TABLE dev_db.analytics.orders;
    -- Returns: (empty)

    If you need CDC streams on cloned tables, create them explicitly after cloning:

    CREATE OR REPLACE STREAM dev_db.analytics.orders_cdc_stream
        ON TABLE dev_db.analytics.orders
        APPEND_ONLY = FALSE
        SHOW_INITIAL_ROWS = FALSE;
    
    CREATE OR REPLACE TASK dev_db.analytics.process_orders_changes
        WAREHOUSE = dev_wh
        SCHEDULE = '5 minute'
        WHEN SYSTEM$STREAM_HAS_DATA('dev_db.analytics.orders_cdc_stream')
    AS
        CALL dev_db.analytics.process_orders_sp();

    This recreates the stream on the cloned table and a task that runs every five minutes, but only when the stream has new data. Point WAREHOUSE at a dev warehouse, never a production one.

    Tasks are cloned, but they start in a SUSPENDED state and don’t auto-resume. That is the correct behaviour (you don’t want dev tasks firing against prod targets), but it surprises teams expecting a live copy of the pipeline. If your pipeline relies on dbt incremental models consuming from those streams, the failure compounds further; see The Problem with Incremental Models in dbt Nobody Talks About.


    When zero-copy cloning is the right tool

    Before risky migrations — clone first, get an instant rollback point:

    BEGIN
      CREATE OR REPLACE TEMPORARY TABLE ORDERS (ORDER_ID NUMBER, CUSTOMER_NAME VARCHAR, ORDER_STATUS VARCHAR, AMOUNT NUMBER(10,2));
      INSERT INTO ORDERS VALUES (1,'ABC Financial','shipped',1200.50),(2,'XYZ Investments','pending',540.00),(3,'Global Bank','delivered',9800.75);
      CREATE OR REPLACE TEMPORARY TABLE ORDERS_PRE_MIGRATION CLONE ORDERS;
      ALTER TABLE ORDERS ADD COLUMN NEW_COLUMN VARCHAR;
      UPDATE ORDERS SET NEW_COLUMN = UPPER(ORDER_STATUS);
      DROP TABLE ORDERS;
      ALTER TABLE ORDERS_PRE_MIGRATION RENAME TO ORDERS;
      DROP TABLE ORDERS;
      RETURN 'ok';
    END;

    Instant dev environments, UAT cycles and zero-downtime data fixes are all excellent use cases. The feature is great. Using it without understanding the lifecycle is where teams get into trouble.
    If you want to go further on cost reduction for dev workloads, pairing a clone strategy with DuckDB is worth exploring: How to Query Snowflake in DuckDB and Cut Your Bill While Doing It.


    Frequently asked questions

    Does zero-copy cloning in Snowflake really cost nothing?

    At creation, yes. The cost begins the moment either side is modified, through copy-on-write. In active dev environments that change frequently, storage costs can grow significantly over weeks, and Time Travel retention on the clone compounds this.

    Do data masking policies transfer when you clone a table?

    No. Masking policies are not inherited by clones. Sensitive columns are exposed in plain text on the clone unless you explicitly re-apply policies after creation. Treat clone creation and policy application as a single atomic operation.

    Can I use Time Travel on a clone to go back before it was created?

    No. A clone’s Time Travel history starts at its creation date. For history before the clone was created, query the source table directly.

    Are Snowflake streams copied when you clone a table?

    No. Streams are not part of the clone operation. Create them explicitly on the clone if your pipeline depends on CDC. Tasks are cloned but start suspended.

    How do I audit all clones in my Snowflake account?

    Query snowflake.account_usage.tables filtering on clone_group_id IS NOT NULL. Tag clones at creation with JSON metadata in the COMMENT field (owner, expiry, purpose) to make audits actionable.

    What’s the best practice for cloning production for dev?

    Clone, then immediately: reduce Time Travel retention to 0 or 1 day, re-apply all masking and row access policies, set a resource monitor on dev warehouses, and tag the clone with an expiry date in the COMMENT field.

    Further reading

  • Claude Code Power User Guide: Stop Using It Like Autocomplete

    Claude Code Power User Guide: Stop Using It Like Autocomplete

    Most developers use Claude Code like a fancy autocomplete: paste a bug, get a fix, repeat, never building on anything. This guide is for developers who already use Claude Code and want more from it. It covers CLAUDE.md setup, plan mode, slash commands, skills, path-specific rules, CI/CD integration, and the daily habits that build on each other over time.


    Why Most Developers Underuse Claude Code

    You are probably wasting Claude Code. Not because you are lazy, but because nobody told you how it actually works.

    The default pattern most developers fall into is paste-and-pray. You drop in a bug and get a fix. You paste in a feature request and get some code. One question, one answer, repeat forever. It is transactional and shallow, and it leaves probably 80% of Claude Code’s capability untouched.

    That is how most people start, and that is fine. But if you are still working that way six months in, it is a problem. Claude Code is not a code suggestion engine. It is an autonomous engineering partner that can read your entire codebase, understand your architecture, execute multi-step plans, run your test suite, debug failures and ship features end to end.

    The difference between a casual user and a power user is not talent or experience. It is configuration, workflow, and knowing which features make a real difference.

    The File You Should Have Created on Day One

    One file at the root of your project will affect your Claude Code results more than anything else you do, and most people have never created it: CLAUDE.md.

    Without it, Claude Code is making educated guesses. It does not know that your team uses camelCase for variables and PascalCase for components. It does not know you prefer functional components over class components, that your API naming convention is verb-first, or that you never use any-typed variables and have strong feelings about it.

    With a well-written CLAUDE.md, Claude Code follows your team’s standards automatically. Every file it touches, every function it writes and every test it generates stays consistent, without you correcting it each time.

    What belongs in yours:

    • Your tech stack and the specific versions that matter
    • Coding conventions and naming patterns your team actually uses
    • File structure: where things go and why
    • Testing requirements, and what a “good test” looks like in your context
    • The error handling patterns you have standardized on
    • Pitfalls specific to your codebase (the things that only make sense after you have been burned)
    • Hard rules: things Claude should never do in this project

    Spend 30 minutes writing this file. That time will save you thousands of manual corrections over the next year, and it keeps a new team member’s Claude Code aligned with yours from day one.

    The three-level hierarchy, and where most teams go wrong

    CLAUDE.md is not one file. It is a hierarchy, and the level matters.

    User level: ~/.claude/CLAUDE.md. This is personal: your own preferences and style. It is not version controlled and your teammates never see it. It is the right place for things like “I prefer verbose variable names” or “always add JSDoc comments to exported functions.”

    Project level: .claude/CLAUDE.md in your repo root. This is shared with the whole team through git. Team standards, architectural decisions and universal rules live here. If it affects how anyone on the team should use Claude Code in this project, it goes here.

    Directory level: a CLAUDE.md inside a specific directory only applies when Claude Code is working on files in that location. It is useful for sub-projects or modules with genuinely different conventions.

    The mistake I see constantly: teams put shared rules in their user-level config, then wonder why a new developer’s Claude Code produces code that does not match team standards. The fix is always the same. Move those rules to the project level and commit them.

    Choose the Mode Before You Send the Message

    This is the change that most quickly improves output quality on complex work.

    There are two modes: direct execution and plan mode. Most people default to direct execution for everything, and that is a mistake.

    Direct execution makes sense for tasks with a clear, limited scope: fix this specific bug, add this validation, rename this variable across the codebase. When the scope is narrow and the risk is contained, let Claude Code work.

    Plan mode is for everything bigger: refactoring a module, adding a feature that touches multiple files, migrating from one pattern to another, restructuring your test suite. Anything with architectural decisions baked into it.

    In plan mode, Claude Code first writes a plan: which files it will touch, what changes it will make, and in what order. You review that plan before a single line of code is written. You can adjust steps, remove something you disagree with, or catch a misunderstanding before it spreads across a dozen files.

    The rule I use: if the task touches more than two files or requires any architectural decision, use plan mode. If you skip it on complex tasks, you will spend more time undoing changes than you saved by starting fast.

    Built-In Tools You Are Probably Not Using Correctly

    Claude Code ships with a set of tools that most people either do not know exist or misuse.

    Grep vs Glob

    These are not interchangeable. Grep searches file contents. Glob matches file paths. If you are looking for where a function is called, use Grep. If you are looking for all test files in a project, use Glob. Using the wrong one wastes time and gives confusing results.

    Read, Write and Edit

    Edit makes targeted changes by matching a unique piece of text. It is fast and precise. When Edit fails because the match is not unique, fall back to Read plus Write: read the full file, then write the complete modified version. Reaching for Write when Edit would work is wasteful; reaching for Edit when the match is ambiguous causes silent bugs.

    The /memory command

    /memory shows which memory files Claude Code has loaded in the current session. If Claude Code is behaving inconsistently or ignoring rules you have set, run /memory before assuming anything else. Nine times out of ten, the right context simply is not loaded.

    Custom Slash Commands: Stop Typing the Same Prompt Twice

    If you have typed the same prompt more than three times, it should be a slash command.

    Create them in .claude/commands/ for shared team commands or in ~/.claude/commands/ for personal ones.

    Some examples: a /review command that runs your team’s code review checklist, a /test command that generates tests following your patterns and coverage requirements, and a /deploy-check command that verifies everything is ready before you push to production.

    Each takes about 10 minutes to create. The return is hours per month of prompting you never have to do again, and because they live in .claude/commands/, the whole team gets them automatically.

    Skills vs CLAUDE.md: Putting Context in the Right Place

    This distinction trips up most intermediate users.

    CLAUDE.md is always loaded: every session, every task, no exceptions. Universal standards go here.

    Skills are loaded on demand. They activate when invoked, so task-specific workflows belong there.

    The common mistake is putting task-specific procedures into CLAUDE.md. The file gets bloated, Claude Code gets distracted by irrelevant context, and you spend tokens on instructions that do not apply to the current task.

    The rule is simple. If it applies to every task, it belongs in CLAUDE.md. If it applies to one type of work, such as “here’s how we generate database migrations” or “here’s the process for writing integration tests”, make it a skill.

    Path-Specific Rules: Conventions by File Type

    This one consistently surprises developers who have been using Claude Code for months.

    Create rule files in .claude/rules/ with YAML frontmatter that lists glob patterns:

    ---
    paths: ["**/*.test.tsx"]
    ---
    All tests must use the arrange-act-assert pattern. Never mock the database layer directly. Use factory functions for test data, never inline object literals.

    These rules load automatically, and only when Claude Code is editing files that match the pattern. Every test file in your codebase, whichever directory it lives in, gets the same testing conventions without you doing anything.

    This is more useful than a directory-level CLAUDE.md because it works on what the file is, not where it lives. You write the rule once and it applies everywhere the pattern matches.

    CI/CD Integration: Automate the Work That Should Not Be Manual

    At some point Claude Code stops being a tool you use and becomes infrastructure that runs without you.

    The key flag is -p, which runs Claude Code in non-interactive mode. Without it, your CI job hangs waiting for input that will never come. If you are putting Claude Code into any pipeline, this flag is required.

    Pair it with --output-format json and --json-schema to get structured, machine-parseable output. Your CI system can then post findings as inline PR comments automatically, with no human in the loop.

    One principle matters here: the same Claude Code session that generated the code is less effective at reviewing it. It carries reasoning context that biases it towards its own decisions. For code review in CI, always use an independent review instance. This is a meaningful quality difference, not a quirk.

    In practice this looks like automated security review on every PR, test generation for uncovered code paths, and documentation updates when the implementation changes. All of it is posted as comments your team can review, without anyone having to remember to run anything.

    What a Power User Day Looks Like

    Morning: you open your terminal. Claude Code loads your CLAUDE.md and the relevant path-specific rules automatically. You describe the first feature in plain English. Claude Code creates a plan. You review it, adjust one step and approve. It works across eight files, writes tests, runs them, fixes two failures and commits.

    Afternoon: you are reviewing a PR. Instead of reading every line yourself, you run /review. Claude Code checks the change against your team’s standards and flags three issues, explaining why each matters. You address the one real issue and approve the rest.

    End of day: your CI pipeline runs Claude Code with -p on every new PR. The review happens automatically, PR comments appear, and your team sees them in the morning.

    That is not a vision of the future. Developers who have done this setup are running it today.

    The Bottom Line

    Claude Code is one of the most capable developer tools available right now, and one of the most underused. That is not because of its limitations but because of how most people approach it.

    The gap between casual use and power use is not months of learning. It is a few days of deliberate setup and practice.

    Configure your CLAUDE.md. Learn plan mode. Build custom commands. Use path-specific rules. Integrate it into CI. Each of these makes the others more effective.

    Most developers will keep pasting one-off questions and getting one-off answers. The ones who build a real system around it will be working at a different level within 30 days.

    FAQ

    What is CLAUDE.md and why does it matter?

    CLAUDE.md is a configuration file in your project that tells Claude Code about your codebase conventions, patterns and rules. Without it, Claude Code makes generic assumptions. With a well-written one, it follows your team’s standards automatically in every file it touches.

    What is the difference between plan mode and direct execution?

    Direct execution is for narrow, well-defined tasks like fixing a specific bug. Plan mode first produces a step-by-step plan for you to review before any code is written. Use plan mode whenever a task touches more than two files or involves architectural decisions.

    How do path-specific rules work?

    You create rule files in .claude/rules/ with YAML frontmatter containing glob patterns. The rules load automatically whenever Claude Code edits a file that matches, anywhere in the codebase.

    What is the -p flag in Claude Code?

    -p runs Claude Code in non-interactive (headless) mode. It is required for CI/CD integration; without it, automated jobs hang waiting for user input.

    Should I use CLAUDE.md or skills for task-specific workflows?

    Use CLAUDE.md for universal rules that apply to every task in the project. Use skills for specific workflows, like generating migrations or writing integration tests, that only apply in certain contexts. Mixing them up leads to a bloated CLAUDE.md and confused output.

    Can Claude Code review its own code in CI?

    Technically yes, but it is less effective. A session keeps the reasoning context from the code it generated, which introduces bias. For CI code review, use an independent instance with no context from the generation session.

    Further Reading

  • How to Query Snowflake in DuckDB (and Cut Your Bill While Doing It)

    How to Query Snowflake in DuckDB (and Cut Your Bill While Doing It)

    This post is for data engineers and analytics leads whose Snowflake bill is driven by lots of short queries rather than heavy batch jobs. It explains why Snowflake’s 60-second minimum makes those queries expensive, shows two ways to get Snowflake data into DuckDB (Iceberg tables on S3, and ADBC for native tables), and gives a simple way to decide which workloads belong on which engine.

    I’ve been building on Snowflake long enough to know the ritual. Warehouse wakes up. Query runs in three seconds. Warehouse idles. You get billed for sixty seconds anyway. Multiply that by every analyst, every BI dashboard refresh and every dbt run in your dev environment, and you end up with a bill that feels disconnected from the work that actually happened.

    For a long time I assumed this was just the price of using a best-in-class cloud warehouse. What I didn’t realise until I started taking DuckDB seriously is that a meaningful part of that bill doesn’t have to exist at all.


    The real problem: you pay for compute you didn’t use

    Snowflake bills compute per second, but only after a 60-second minimum each time a warehouse resumes from suspension. A query that takes five seconds gets billed for a full minute. You paid for 55 seconds of nothing.

    It gets worse at scale. When a BI dashboard fires 20 queries on load, each taking three seconds, that single page view triggers 1,200 seconds of billed compute time. The actual work is one minute.

    Warehouse sizing compounds it further. Each size increase in Snowflake doubles credit consumption, so teams defaulting to Medium or Large for everything pay a 4x to 8x premium for workloads that would run fine on X-Small.

    I’ve seen this exact pattern on almost every Snowflake environment I’ve worked in: oversized warehouse, auto-suspend set to ten minutes, no resource monitors, and nobody looking at query history.


    Quick wins inside Snowflake first

    Before touching the architecture, fix the obvious things. These alone can cut spend by 20 to 40%.

    Set AUTO_SUSPEND to exactly 60 seconds. Not lower: setting it below 60 is counterproductive, because a query arriving in that first minute triggers another 60-second minimum. Not higher: every idle second past 60 is wasted money.

    Default to X-Small warehouses. Only scale up when a specific workload has a documented SLA that needs it.

    Add resource monitors:

    CREATE OR REPLACE RESOURCE MONITOR monthly_etl_monitor
    WITH CREDIT_QUOTA = 5000
    TRIGGERS ON 75 PERCENT DO NOTIFY
            ON 100 PERCENT DO SUSPEND;
    
    ALTER WAREHOUSE etl_heavy_wh 
    SET RESOURCE_MONITOR = monthly_etl_monitor;

    This notifies at 75% of a 5,000-credit quota and suspends the warehouse at 100%. Set the quota and the warehouse name to match your own account.

    Method 1: Query Snowflake Iceberg tables directly in DuckDB

    If your organisation has moved to Iceberg tables with the underlying data in S3, you can read those tables directly in DuckDB. No Snowflake warehouse runs and no credits are consumed.

    Install the extensions

    INSTALL httpfs;
    LOAD httpfs;
    INSTALL iceberg;
    LOAD iceberg;

    Configure AWS credentials:

    CREATE SECRET (
        TYPE S3,
        PROVIDER CREDENTIAL_CHAIN
    );

    Find the metadata file and query it

    In Snowflake, find the current metadata file for your Snowflake-managed Iceberg table:

    SELECT PARSE_JSON(
      SYSTEM$GET_ICEBERG_TABLE_INFORMATION('YOUR_DB.YOUR_SCHEMA.YOUR_TABLE')
    )['metadataLocation']::varchar;

    Then point DuckDB at that file:

    SELECT
        customer_id,
        COUNT(*)
    FROM iceberg_scan('s3://your-bucket/path/to/metadata/00001-xxxx.metadata.json')
    GROUP BY 1;

    Materialise once for fast repeated queries

    CREATE TABLE payments AS 
    SELECT * FROM iceberg_scan('s3://your-bucket/.../metadata.json');

    After this, the same aggregation runs in 1.5 seconds instead of 54.

    One benchmark: a SELECT * on a 110-million-row table finished in 29 seconds in DuckDB on an M1 MacBook. The same query on an X-Small Snowflake warehouse took 72 seconds.


    The limitation

    DuckDB’s Iceberg support is still maturing. You need direct S3 access, and you have to point DuckDB at a specific metadata file rather than a catalog. This will improve over time, but it works today.

    Method 2: Query native Snowflake tables through ADBC

    Not on Iceberg yet? ADBC (Arrow Database Connectivity) is the right tool here.

    Why ADBC rather than ODBC

    Apache Arrow is a columnar memory format. When you connect Snowflake to DuckDB through ADBC, data stays columnar the whole way. Traditional ODBC makes Snowflake convert columnar data to rows for transfer, and then DuckDB converts the rows back to columnar for processing. DuckDB’s benchmarks show ADBC is up to 38x faster than ODBC.

    Install the packages:

    pip install adbc_driver_snowflake pyarrow duckdb cryptography

    Connect to Snowflake and pull data as an Arrow table:

    import adbc_driver_snowflake.dbapi
    import duckdb
    import os
    from read_private_key import read_private_key
    
    SNOWFLAKE_CONFIG = {
        'adbc.snowflake.sql.account': os.getenv('SNOWFLAKE_ACCOUNT'),
        'adbc.snowflake.sql.warehouse': os.getenv('SNOWFLAKE_WAREHOUSE'),
        'adbc.snowflake.sql.role': os.getenv('SNOWFLAKE_ROLE'),
        'adbc.snowflake.sql.database': os.getenv('SNOWFLAKE_DATABASE'),
        'username': os.getenv('SNOWFLAKE_USER'),
        'adbc.snowflake.sql.client_option.jwt_private_key_pkcs8_value': pem_key,
        'adbc.snowflake.sql.auth_type': 'auth_jwt'
    }
    
    snowflake_conn = adbc_driver_snowflake.dbapi.connect(
        db_kwargs={**SNOWFLAKE_CONFIG}
    )
    
    snowflake_cursor = snowflake_conn.cursor()
    snowflake_cursor.execute("SELECT * FROM SANDBOX_DB.MY_SCHEMA.RAW_ORDERS")
    
    # Fetch as Arrow table — stays columnar, no serialisation overhead
    arrow_table = snowflake_cursor.fetch_arrow_table()
    
    # Persist locally in DuckDB
    duckdb_conn = duckdb.connect('demo.db')
    duckdb_conn.execute("""
        CREATE TABLE IF NOT EXISTS raw_orders AS 
        SELECT * FROM arrow_table
    """)

    The script reads the account, warehouse, role, database and user from environment variables, authenticates with a key pair (JWT), runs one query through a Snowflake warehouse, fetches the result as an Arrow table and writes it into a local DuckDB file called demo.db. Swap in your own table name and file path. pem_key has to be set before the config dictionary is built, using the read_private_key helper in the next section.

    Encode the private key as PEM

    One heads-up: working out the connection parameters for a private key is not straightforward, and the docs aren’t great on this point. The private key needs to be re-encoded into PEM format before you pass it to the ADBC driver:

    from cryptography.hazmat.primitives import serialization
    
    def read_private_key(private_key_path: str, private_key_passphrase: str = None) -> str:
        with open(private_key_path, 'rb') as key_file:
            private_key = serialization.load_pem_private_key(
                key_file.read(),
                password=private_key_passphrase.encode() if private_key_passphrase else None
            )
            pem_key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption()
            )
            return pem_key.decode('utf-8')

    The function loads your key file (using the passphrase if there is one) and returns it as an unencrypted PKCS8 PEM string, which is the format the jwt_private_key_pkcs8_value option expects.

    Once that’s sorted, the workflow is clean: pull data from Snowflake through ADBC once, materialise it locally in DuckDB, and query it as many times as you want. No Snowflake credits are consumed after the initial pull.


    Method 3: Route workloads by type

    The two methods above are great for development and ad-hoc analysis. For production BI workloads, the cleanest solution I’ve seen is a hybrid architecture where you triage queries by workload type.

    What made this click for me was using Snowflake’s query_history to categorise what is actually running:

    WITH query_stats AS (
        SELECT
            warehouse_name,
            user_name,
            query_id,
            execution_time / 1000 AS execution_seconds
        FROM snowflake.account_usage.query_history
        WHERE
            start_time &gt;= DATEADD('day', -30, CURRENT_TIMESTAMP())
            AND warehouse_name IS NOT NULL
            AND execution_status = 'SUCCESS'
    )
    SELECT
        warehouse_name,
        user_name,
        COUNT(query_id) AS query_count,
        MEDIAN(execution_seconds) AS median_execution_seconds,
        CASE
            WHEN query_count &gt; 1000 AND median_execution_seconds &lt; 30 
                THEN 'Interactive BI / High Frequency'
            WHEN query_count &lt;= 1000 AND median_execution_seconds &lt; 60 
                THEN 'Ad-Hoc Exploration'
            WHEN median_execution_seconds &gt;= 300 
                THEN 'Batch ETL / Heavy Analytics'
            ELSE 'General Purpose'
        END AS workload_category
    FROM query_stats
    GROUP BY warehouse_name, user_name
    ORDER BY query_count DESC;

    The query looks at the last 30 days of successful queries, groups them by warehouse and user, and labels each group by how often it runs and how long its typical query takes. The thresholds (1,000 queries, 30, 60 and 300 seconds) are the cut-offs to adjust for your own account.

    Use MEDIAN, not AVG. Outlier queries skew the average and give a misleading picture of typical duration.

    Routing logic

    • Short, bursty BI (under 30 seconds, high frequency): move to a usage-based engine such as MotherDuck. The math: $528/month on a Snowflake X-Small running continuously vs $5.87/month on per-second billing for the same workload.
    • Dev and CI/CD: local DuckDB, zero cloud credits.
    • Heavy batch ETL, multi-TB: keep on Snowflake. The 60-second minimum is irrelevant for hour-long jobs.

    This is the same principle I apply to orchestration: use the right tool for the job, not the most powerful tool for everything. I wrote about a similar decision in why I stopped using Snowflake Tasks for orchestration. The short version is that mature orchestration tools give you far more control over exactly this kind of workload routing.

    When to stay on Snowflake

    Multi-terabyte batch processing. Predictable provisioned compute matters more than idle cost savings when a job runs for hours.

    Enterprise governance. Complex data masking, RBAC at scale and data residency requirements. Snowflake’s security surface is mature; DuckDB isn’t designed for this.

    Already-efficient workloads. If a warehouse runs at high utilisation for eight hours straight, there’s no idle tax to remove. Don’t fix what isn’t broken.

    What real cost savings look like

    • One SaaS company: 70%+ reduction in warehousing costs after moving to a DuckDB-based solution.
    • Okta: $60,000/month of Snowflake spend for threat detection reduced substantially using parallel DuckDB instances.
    • A data engineering team: 79% immediate reduction in Snowflake BI spend using DuckDB as a caching layer, with 7x faster queries.

    None of these required abandoning Snowflake. They required deciding which workloads actually needed it. If you’re earlier in that journey, the rest of the data engineering articles on this site cover the Snowflake side in more depth.

    Frequently asked questions

    Can you query Snowflake data in DuckDB without a Snowflake warehouse running?

    Yes, in two ways: Iceberg tables through the iceberg extension (no warehouse), or native tables through ADBC. ADBC needs a brief initial connection, but once the data is materialised locally, every later query is free.

    What is ADBC and why is it faster than ODBC?

    ADBC keeps data in columnar format throughout. ODBC forces a columnar to row to columnar conversion. DuckDB’s benchmarks show ADBC up to 38x faster for transfers.

    How much can I realistically save?

    For short, high-frequency dashboard queries, 70 to 90% is consistent across documented cases. The 60-second minimum means a 4-second query costs 15x what it should.

    Is DuckDB production-ready?

    For single-node analytical workloads under a few terabytes, yes. For multi-user concurrency at scale and enterprise governance, not yet.

    Do I need Iceberg?

    No. ADBC works with native Snowflake tables. The main friction is private key encoding, which the docs don’t explain well.

    Will this work with dbt?

    Yes. dbt-duckdb lets you run your full dbt project locally against DuckDB. Pull source data from Snowflake once, develop and test for free, and deploy to Snowflake only in production. That removes cloud compute costs from the whole development loop. I’ve written about dbt native projects and pipeline patterns if you want more context on how this fits into a Snowflake-first stack.

    Further reading

  • The Problem with dbt Tests Nobody Talks About — They Pass and You Still Ship Bad Data

    The Problem with dbt Tests Nobody Talks About — They Pass and You Still Ship Bad Data

    I’ve been running dbt in production for a while now. And I’ll be honest — there was a phase where I genuinely believed that if my dbt tests were green, I was good. Green means clean, right?

    Wrong.

    This is the quiet failure mode that nobody in the dbt community writes about loudly enough. Your tests pass. Your CI/CD pipeline goes green. Your DAG runs without errors. And somewhere downstream, an analyst is staring at a revenue number that’s off by 30% and has no idea why.


    TL;DR: dbt’s built-in tests (not_null, unique, accepted_values, relationships) validate data structure, not data correctness. Your pipeline goes green and you still ship wrong numbers. This post breaks down exactly why that happens, what the real gaps are, and what custom tests, volume monitoring, and source-layer checks actually fix


    Let me walk you through exactly how this happens — because I’ve lived it.


    What Are dbt Tests Actually Checking?

    Before we get to the failure modes, let’s be precise about what dbt’s generic tests actually do — because I think the confusion starts here.

    dbt gives you four built-in generic tests out of the box:

    • not_null — checks that a column has no null values
    • unique — checks that all values in a column are distinct
    • accepted_values — checks that a column only contains values from a predefined list
    • relationships — checks referential integrity between two models

    These are constraint tests. They validate the shape of your data — grain, nullability, referential integrity. They do not validate whether the values are correct, whether the volume is expected, or whether the business logic in your SQL is actually right.

    That distinction is everything.

    models:
      - name: fct_daily_revenue
        columns:
          - name: transaction_id
            tests:
              - not_null
              - unique
          - name: revenue_amount
            tests:
              - not_null

    This test suite passes even if every revenue_amount is 100x too large. It passes if your join silently drops 40% of records because a key format changed upstream. It passes if a currency unit changed after a vendor migration and nobody touched the schema.

    None of that is a bug in dbt. It’s working exactly as designed. The problem is the mental model we build around it.


    The Scenario That Broke Me

    We had a pipeline pulling sales transaction data from an API. The dbt model joined it against a product dimension, aggregated daily revenue, and pushed it to a reporting layer. All four generic tests — passing. Every single day.

    What was actually happening: the upstream API started returning amounts in a different currency unit after a vendor migration. No schema change. No new nulls. No duplicate keys. Just the values silently shifting by a factor of 100.

    Our not_null test on revenue_amount? Passed. Our unique test on transaction_id? Passed. Our downstream revenue dashboard was off by two orders of magnitude for three weeks before an analyst caught it during a QBR.

    Three weeks. All green tests. All wrong data.

    That’s when I stopped treating dbt tests as a data quality guarantee and started treating them as what they actually are: a contract enforcement layer.


    The Three Gaps Nobody Talks About

    1. Volume Drift — Records Disappear and Nothing Breaks

    If your fct_orders model typically produces 50,000 rows a day and one morning it produces 12,000 — no generic test will catch that. The data that is there is perfectly valid. You just lost 38,000 records somewhere in your pipeline and dbt has no idea.

    This is one of the most common real-world pipeline failures I see, and it’s completely invisible to constraint-based tests.

    The fix is a custom singular test or a dbt_utils recency/row-count assertion:

    -- tests/assert_row_count_within_threshold.sql
    {% set threshold = 0.2 %}
    select 1
    from (
      select count(*) as today_count
      from {{ ref('fct_orders') }}
      where order_date = current_date
    ) today
    cross join (
      select avg(daily_count) as avg_count
      from (
        select order_date, count(*) as daily_count
        from {{ ref('fct_orders') }}
        where order_date between current_date - 14 and current_date - 1
        group by order_date
      ) history
    ) baseline
    where abs(today_count - avg_count) / nullif(avg_count, 0) > {{ threshold }}

    This returns a row — which dbt interprets as a test failure — when today’s row count deviates more than 20% from the 14-day average. Simple, practical, catches real failures. I also wrote about a similar pattern in how dbt integrates natively with Apache Airflow for pipeline orchestration — the combination of orchestration visibility and volume tests gives you a much more honest picture of pipeline health than either alone.

    2. Business Logic Correctness — The Math Can Still Be Wrong

    dbt tests validate columns in isolation. They don’t validate relationships between columns, or whether the calculations in your model are actually right.

    Take something simple:

    select
      order_id,
      unit_price,
      quantity,
      unit_price * quantity as line_total
    from {{ source('orders', 'order_lines') }}

    You can have not_null on all three columns, accepted_values on quantity to ensure it’s positive — and still ship models where line_total is wrong because unit_price was populated in cents from one source and dollars from another. No generic test catches that unless you explicitly write:

    -- tests/assert_line_total_matches_components.sql
    select *
    from {{ ref('fct_order_lines') }}
    where abs(line_total - (unit_price * quantity)) > 0.01

    Writing that test requires you to already know the business rule. Which means data quality at this layer requires domain knowledge, not just dbt knowledge. If you’re using Snowflake, pairing this with Cortex-based automated data quality checks can flag anomalies in derived metrics that pure SQL assertion tests would miss — something I covered in depth when building Snowflake Cortex accelerators for automated data quality.

    3. Silent Join Fan-Out and Record Loss

    This one has bitten me more than once. A many-to-one join accidentally becomes many-to-many because a dimension table you assumed was unique… wasn’t. Or a left join silently drops records because a key format changed from integer to string somewhere upstream.

    The result: your fact table either fans out (double-counting revenue) or silently loses records, and every generic test still passes because the columns that remain are perfectly valid.

    The safeguard is writing uniqueness tests on your dimension tables and asserting that your fact-to-dimension join doesn’t increase row count:

    -- tests/assert_no_join_fanout.sql
    with before_join as (
      select count(*) as row_count from {{ ref('fct_orders') }}
    ),
    after_join as (
      select count(*) as row_count
      from {{ ref('fct_orders') }} o
      left join {{ ref('dim_customers') }} c on o.customer_id = c.customer_id
    )
    select 1
    from before_join b
    cross join after_join a
    where a.row_count > b.row_count

    What Actually Helps

    Write custom singular tests for critical models. Don’t rely only on generic column-level tests for anything that feeds a financial or executive dashboard. If the number matters, test the business rule explicitly.

    Add volume and freshness monitoring at source. Whether you use dbt_utils.recency, Elementary, or a hand-rolled SQL assertion — track volume. It’s the cheapest signal you have that something went wrong upstream.

    sources:
      - name: raw_transactions
        tables:
          - name: transactions
            tests:
              - dbt_utils.recency:
                  datepart: hour
                  field: created_at
                  interval: 3
            columns:
              - name: amount
                tests:
                  - dbt_utils.accepted_range:
                      min_value: 0
                      max_value: 1000000

    Test at source, not just at the model layer. If an upstream format changes, you want the failure at ingestion, not after three transformation layers have already propagated it downstream.

    Use dbt_utils and Elementary seriously. The dbt_utils package has range tests, expression tests, and recency checks that fill a lot of the structural gaps. Elementary adds anomaly detection on top of that, which gets you closer to actual data observability rather than just constraint validation.

    Review your SQL, not just your CI badge. Every model that feeds a critical metric should have a comment explaining the expected grain, the join logic, and the expected value ranges. Future you — and the next engineer — will thank you when something breaks at 2am.


    The Mindset Shift

    I had to reframe how I think about dbt tests. They’re not a data quality guarantee. They’re a contract enforcement layer. They ensure your data meets its structural promises. That’s genuinely useful — but it’s not the same as ensuring your data is correct.

    Real data quality requires a combination of:

    • Structural tests — what dbt gives you natively (constraint validation)
    • Business logic tests — custom singular tests you write based on domain knowledge
    • Volume and freshness monitoring — dbt_utils, Elementary, or your own row count assertions
    • Code review culture — someone actually looks at the SQL, not just whether CI passed

    The green checkmark in your pipeline is not permission to stop thinking. It’s permission to look at the next layer of potential failure.

    I spent a long time treating dbt tests as a safety net. They’re more like a fence — useful, visible, and completely ineffective against threats that don’t come through the gate.


    Frequently Asked Questions

    Do dbt tests guarantee data quality?

    No. dbt’s built-in generic tests — not_null, unique, accepted_values, relationships — validate structural constraints on your data. They confirm that a column has no nulls, that keys are unique, or that values fall within an expected set. They do not verify whether the actual values are correct, whether business logic in your SQL is right, or whether record volumes are within expected ranges. For genuine data quality coverage, you need custom singular tests, volume monitoring, and source-layer assertions alongside dbt’s native tests.

    What is the difference between dbt generic tests and singular tests?

    Generic tests in dbt are reusable, schema-defined checks applied to columns across multiple models — not_null and unique are the most common. Singular tests are standalone SQL queries that you write specifically for a model or business rule: they return rows when something is wrong and pass when they return no rows. Singular tests are where you validate business logic — things like “line_total should always equal unit_price × quantity” or “today’s row count should be within 20% of the 14-day average.” Both types live in your tests/ directory and run with dbt test.

    Can dbt catch silent record loss in joins?

    Not automatically. If a join accidentally drops records — due to a key format change, a null key, or a mismatched data type — dbt’s generic tests won’t flag it unless you’ve explicitly written a test to assert row count consistency before and after the join. This is one of the most common silent failure modes in production dbt pipelines. Writing a custom singular test that compares pre- and post-join row counts is the most reliable way to catch it.

    How do I monitor row count changes in dbt?

    There are a few approaches. The dbt_utils package includes a recency test for freshness monitoring. For volume, you can write a custom singular test that compares today’s row count against a rolling average from the past 14 days — any deviation beyond a threshold (say 20%) triggers a failure. For more automated anomaly detection across all your models, Elementary integrates directly with dbt and adds statistical monitoring without requiring you to write individual volume tests for every model.

    What is the best way to test business logic in dbt?

    Write singular tests that encode the business rule explicitly in SQL. For example, if your model calculates revenue = quantity × unit_price, write a test that queries the model and returns rows where abs(revenue - (quantity * unit_price)) > 0.01. If there are cross-column invariants — like a refund amount should never exceed the original transaction amount — write that as a test too. The key insight is that these tests require domain knowledge: you need to know what correct looks like before you can assert it. That’s a conversation between data engineers and the business teams who own the metrics.

    Does dbt have built-in anomaly detection?

    dbt itself does not include statistical anomaly detection. The core framework focuses on constraint-based testing. For anomaly detection — flagging unexpected spikes, drops, or distribution shifts in your data — you need either the Elementary package, which sits on top of dbt and adds automated monitoring, or a dedicated data observability platform like Monte Carlo, Soda, or Bigeye. In Snowflake environments specifically, combining dbt with Cortex-based quality checks can add an AI-assisted layer on top of your existing test suite.


    The Honest Closing

    The reason nobody talks loudly about this is that it’s uncomfortable. We build testing frameworks because they give us confidence. Admitting that green tests can coexist with broken data means admitting that the confidence was partly false.

    But I’d rather have that honest conversation in a blog post than explain to a VP why the quarterly revenue numbers were wrong — and then pull up a CI pipeline that was green the whole time.

    Write the custom tests. Monitor the volumes. Test the business rules. Trust the process, not just the color of the badge.


    Related reading from the blog:

  • Automation in Data Engineering: It’s Not AI You Should Worry About

    Automation in Data Engineering: It’s Not AI You Should Worry About

    I still remember the afternoon I burned four hours debugging a production pipeline, convinced the problem was in the model logic, only to find the real culprit was a manual data prep step where someone had quietly introduced a column name inconsistency. No alerts. No schema validation. Just silent failure downstream.

    That incident changed how I think about data engineering. The problem was not the AI model. The problem was that we had automated the interesting parts and left the boring, error-prone parts to humans.

    I have spent four years building and maintaining data pipelines as part of a 10-person team processing millions of records at varying frequencies. This post is for data engineers who want fewer silent failures. It covers event-based triggers, where AI actually helps in ETL, the automation mistakes I have made, testing and CI/CD for pipelines, and how to decide what to automate first. My short answer: automation is not about replacing engineers, it is about removing the conditions where human error is inevitable.


    Why Reliable Pipelines Are a Business Problem, Not Just a Technical One

    A data pipeline that fails silently is worse than one that fails loudly. When records go missing or get duplicated without anyone noticing, downstream reports become unreliable, and the teams using that data stop trusting it. Once trust breaks, people start keeping their own spreadsheets, which creates more data problems.

    In my experience, most pipeline fragility comes from three places:

    1. Manual handoffs between systems (someone exports a CSV, someone else imports it)
    2. Implicit assumptions about schema or data format that nobody documented
    3. Scheduled pipelines that run whether or not the upstream data is ready

    Automating these touch points, not just the processing logic, is what actually improves reliability.


    Beyond Scheduling: Event-Based Triggers Are Underused

    Most teams start pipeline automation with scheduling: run this DAG at 6am every day. That is a reasonable starting point, but it becomes fragile when upstream systems are delayed, incomplete or unavailable.

    Event-based triggers solve this. Instead of running on a fixed schedule, the pipeline fires when the upstream condition is actually met: a new file lands, a table’s row count crosses a threshold, or an API returns a success status.

    Here is a simple example using Apache Airflow’s HttpSensor to wait for an upstream API to signal readiness before processing:

    from airflow import DAG
    from airflow.operators.bash import BashOperator
    from airflow.sensors.http_sensor import HttpSensor
    from datetime import datetime, timedelta
    
    dag = DAG(
        'event_based_trigger',
        default_args={
            'owner': 'airflow',
            'depends_on_past': False,
            'start_date': datetime(2024, 1, 1),
            'retries': 2,
            'retry_delay': timedelta(minutes=5),
        },
        schedule_interval=timedelta(days=1),
    )
    
    wait_for_api = HttpSensor(
        task_id='wait_for_upstream_api',
        method='GET',
        http_conn_id='upstream_api',
        endpoint='/api/data-ready',
        response_check=lambda response: response.json().get('status') == 'ready',
        poke_interval=60,
        timeout=600,
        dag=dag,
    )
    
    process_data = BashOperator(
        task_id='process_data',
        bash_command='python /opt/scripts/process_records.py',
        dag=dag,
    )
    
    wait_for_api >> process_data

    The sensor calls /api/data-ready on the upstream_api connection every 60 seconds (poke_interval) and only succeeds when the response JSON has status set to ready. If that does not happen within 600 seconds (timeout), the sensor fails instead of letting process_data run. Change the connection ID, endpoint, check and script path to match your upstream system.

    This pattern means your pipeline will not process stale or incomplete data just because the clock hit 6am. That single change has prevented more production incidents on my team than any other automation improvement.

    Where AI Actually Fits in Data Engineering

    AI augments specific parts of the ETL process. It does not change the fundamentals of building reliable pipelines.

    Where I have seen AI add real value:

    • Anomaly detection in incoming data: catching unexpected distributions or null-rate spikes before they propagate
    • Schema drift detection: flagging when source columns change in ways that will break transformations
    • Natural language to SQL: useful for ad hoc queries, not for production pipeline logic
    • Log summarization: when a pipeline failure produces walls of logs, AI can surface the root cause faster

    Where AI does not help as much as vendors claim:

    • Replacing pipeline orchestration logic
    • Making architectural decisions about partitioning, incremental loads or SCD handling
    • Writing production-grade dbt models without human review

    Here is a simple automated data quality check you can add to any pipeline with pandas before records move downstream:

    import pandas as pd
    
    def validate_records(filepath: str) -> pd.DataFrame:
        df = pd.read_csv(filepath)
    
        original_count = len(df)
        df = df.drop_duplicates()
        duplicate_count = original_count - len(df)
    
        null_rates = df.isnull().mean()
        high_null_cols = null_rates[null_rates > 0.1].index.tolist()
    
        if duplicate_count > 0:
            print(f"Warning: Removed {duplicate_count} duplicate rows")
    
        if high_null_cols:
            raise ValueError(f"High null rate in columns: {high_null_cols}")
    
        return df

    The function drops exact duplicate rows and prints how many it removed, then raises a ValueError if any column is more than 10% null, which stops the pipeline rather than passing bad data on. Adjust the 0.1 threshold to suit each source.

    This is not AI, it is automation. But it is exactly the kind of check that catches problems before they reach your warehouse.

    ApproachBest forWatch out for
    AI-enhanced anomaly detectionCatching statistical drift in high-volume pipelinesNeeds a baseline period to calibrate; false positives early on
    Rule-based data quality checksSchema validation, null checks, referential integrityNeeds manual updates when business rules change
    Traditional scheduled ETLPredictable, low-complexity sourcesFragile when upstream systems are delayed or unavailable
    Event-triggered ETLFewer unnecessary runs, fresher dataMore complex to set up; needs reliable event signaling

    Automation Mistakes I Have Made (and Watched Others Make)

    Treating monitoring as an afterthought

    I once shipped an Airflow pipeline with zero alerting. It ran daily for three weeks before anyone noticed a misconfigured DAG was processing the same partition repeatedly. The error, AirflowException: DAG not found, was buried in logs nobody was watching. Now I treat alerting as part of the definition of done, not a follow-up ticket.

    [ADD YOUR OWN: the alerting you added after that incident, for example the on_failure_callback or Slack/email alert config]

    Confusing “automated” with “tested”

    You can automate a broken process. Automation without test coverage just means your broken process runs faster and at scale.

    Using retries to mask real failures

    Setting retries=5 is not a reliability strategy. It is a way to delay your on-call notification by 25 minutes. Retries should handle transient infrastructure issues, not cover up data problems.

    Skipping idempotency

    If your pipeline fails halfway through and re-runs from the beginning, it should produce the same result, not double-insert records. Idempotent pipelines take more effort up front but prevent some of the worst production incidents I have seen.

    Testing and CI/CD for Data Pipelines

    Data pipelines deserve the same testing rigor as application code. That means:

    • Unit tests for transformation logic (test dbt macros and Python functions in isolation)
    • Integration tests that run a pipeline end to end against a sample dataset
    • Schema validation tests that fail loudly if column types or names change unexpectedly
    • CI checks that run on every pull request before code reaches production

    On one project, we set up GitLab CI/CD to run dbt tests and a full DAG parse check on every merge request. The DAG parse check alone caught misconfigured imports that would have failed silently at runtime. The time spent setting it up paid back within the first month.

    A simple GitLab CI stage for dbt testing looks like this:

    test_dbt_models:
      stage: test
      script:
        - dbt deps
        - dbt compile --profiles-dir ./profiles
        - dbt test --profiles-dir ./profiles
      only:
        - merge_requests

    The principle is simple: treat pipeline code as production software. Version control it, test it, and do not deploy it by hand.

    DataOps: The Operational Layer People Skip

    DataOps is a term that gets used loosely, but the core idea is useful: apply the collaboration, automation and continuous delivery practices of software engineering to data workflows.

    In practice, this is what it meant for my team:

    • All DAGs and dbt models live in Git, with PR reviews before anything merges.
    • A staging environment mirrors production so we can test pipeline changes before they touch live data.
    • Incident retrospectives are documented, and recurring failure patterns get automated checks.
    • Data quality issues are tracked like bugs, not dismissed as “one-off data problems”.

    The shift from “we schedule jobs and monitor them loosely” to “we treat pipelines as production software” is what DataOps actually means. It is not a tool purchase. It is a way of working.

    When to Automate and When Not To

    Not everything should be automated on day one. This is how I prioritize.

    Automate immediately

    • Data validation and quality checks
    • Alerting and failure notifications
    • Idempotent full or incremental loads on stable sources
    • Schema change detection

    Automate after you understand the pattern

    • Complex transformation logic (understand it manually first)
    • Backfill processes (get the logic right before you automate it)

    Be careful automating

    • Anything that writes to production without a dry-run option
    • Business rule changes that need stakeholder input
    • Pipeline logic that varies significantly by source

    The goal of automation in data engineering is not to remove humans from the process. It is to remove humans from the steps where they are most likely to make mistakes.

    Frequently Asked Questions

    What does automation in data engineering actually mean?

    It means replacing manual, repetitive steps in your data pipeline (file transfers, data quality checks, schema validation, deployment) with code and tooling that runs reliably without human intervention. It goes beyond scheduling jobs to include monitoring, alerting, testing and CI/CD.

    Which tasks in a data pipeline should I automate first?

    Start with data validation checks (null rates, duplicate detection, schema consistency) and alerting. These give the best return on reliability because they catch problems early and make failures surface loudly rather than silently.

    Can AI replace data engineers?

    No. AI can automate specific tasks, like anomaly detection, log summarization or schema drift alerts, but building reliable pipelines needs architectural decisions, business context and judgment that AI tools do not provide. AI augments the work; it does not replace it.

    What is the difference between DataOps and traditional data engineering?

    Traditional data engineering focuses on building pipelines. DataOps adds the operational layer: version control, CI/CD, testing standards, monitoring and incident management. It is the difference between writing code and running it reliably in production.

    How do I make my Airflow pipelines more reliable?

    Use event-based triggers instead of pure scheduling where possible, make tasks idempotent so re-runs are safe, add schema validation before transformations, alert on task failure (not just at DAG level), and use a proper staging environment to test DAG changes before production.

  • Why I Stopped Using Snowflake Tasks for Orchestration

    Why I Stopped Using Snowflake Tasks for Orchestration


    I want to be clear about something before I say anything critical: Snowflake Tasks are genuinely good. I used them for months. I recommended them to people. I wrote internal documentation about how to set them up.

    And then, slowly, quietly, I stopped reaching for them — and started reaching for Airflow instead.

    This isn’t a hit piece on Snowflake Tasks. It’s an honest look at where they work beautifully, where they start to crack, and the specific moment I realised I was fighting the tool instead of using it. If you’re in that same place right now — Tasks running fine on paper, increasingly painful in practice — this is for you.


    Why I Started With Tasks in the First Place

    The pitch for Snowflake Tasks is genuinely compelling: schedule and orchestrate your data pipelines without leaving Snowflake. No extra infrastructure. No Airflow server to maintain. No Docker containers. No YAML config files. Just SQL.

    For a solo data engineer or a small team running straightforward ELT pipelines that live entirely inside Snowflake, this is actually a great deal. You write a Task, you chain a few of them together, you set a cron schedule on the root, and the whole thing runs on serverless compute that Snowflake manages for you. Clean. Simple. Zero ops overhead.

    I built my first Task tree on a customer dimension pipeline — about 6 tasks chained together to handle raw landing, staging, SCD2 merge, and a downstream mart refresh. It worked perfectly. I was genuinely impressed.

    So I built more of them. And that’s where things started to get interesting.


    The First Sign Something Was Off

    The thing about Snowflake Tasks is that they look fine at small scale. Five tasks. Eight tasks. Even fifteen tasks chained together works reasonably well.

    The cracks start showing when your pipelines grow, when requirements get more complex, and when something goes wrong at 7am and you need to figure out what happened and why.

    My first real frustration was observability. When a Task fails, Snowflake logs it — but finding that log, understanding the full execution context, and connecting it to what came before and after requires digging through TASK_HISTORY in ACCOUNT_USAGE or calling INFORMATION_SCHEMA.TASK_HISTORY(). There’s no single screen that shows you, visually, what ran, what passed, what failed, and what the downstream impact was.

    Compare that to opening the Airflow UI, clicking into a DAG run, and seeing every task coloured green or red with full logs one click away. The difference in time-to-diagnosis is not small. I once spent 40 minutes reconstructing a failed task tree execution from TASK_HISTORY queries that would have taken me 3 minutes in Airflow.

    -- How you debug a failed Snowflake Task
    SELECT
        name,
        state,
        scheduled_time,
        completed_time,
        error_code,
        error_message
    FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(
        SCHEDULED_TIME_RANGE_START => DATEADD('hour', -6, CURRENT_TIMESTAMP()),
        RESULT_LIMIT => 100
    ))
    WHERE name ILIKE '%customer_dim%'
    ORDER BY scheduled_time DESC;

    That query works. But it’s not a dashboard. It’s archaeology.


    The Retry Problem

    This one hurt me in production.

    Snowflake Tasks have basic retry configuration — you can set SUSPEND_TASK_AFTER_NUM_FAILURES to pause a task after repeated failures, which is useful. But what you can’t do natively is retry a specific failed task in the middle of a tree and resume from that point forward.

    If Task 6 in a 10-task chain fails, you fix the problem, and you want to re-run from Task 6 onwards — you’re doing it manually. You can resume the root task, but it re-runs everything from the beginning on the next scheduled tick. Or you run Task 6’s SQL manually, then manually kick off Task 7, Task 8… you see where this is going.

    In Airflow, you right-click the failed task node, click “Clear”, and it re-runs that task and everything downstream. That’s it. One click. No manual intervention, no risk of accidentally re-running something upstream that already completed correctly and shouldn’t run twice.

    For pipelines with expensive upstream tasks — large MERGE operations, heavy aggregations — re-running from the beginning when only a downstream step failed is both wasteful and risky. Wasteful because you’re burning compute credits on work already done. Risky because some operations are not safely idempotent and running them twice produces wrong results.


    The Conditional Logic Wall

    Here’s the limitation that finally pushed me to switch.

    My pipelines started needing branching logic. Specifically: run the full pipeline on weekdays, run a lighter version on weekends. Or: if the row count from the previous step is zero, skip the downstream merge and send an alert instead of running an empty MERGE that silently succeeds.

    In Airflow, this is a BranchPythonOperator. Three lines of Python. Clean, explicit, version-controlled.

    In Snowflake Tasks, this requires workarounds. You can use a stored procedure with SYSTEM$TASK_DEPENDENTS_ENABLE logic, or try to simulate branching with conditional stored procedures that check a flag and decide whether to execute. It works — technically — but it’s brittle, hard to read, and the logic is buried inside a stored procedure rather than visible in the orchestration layer where it belongs.

    Snowflake Tasks can only execute SQL statements and stored procedures. For more complex logic in Python, Java, or other languages, external schedulers are required. Flexera

    When your pipeline logic is entirely SQL, Tasks are fine. The moment you need to make an orchestration decision based on runtime data — not just “did this succeed or fail” but “what did this return, and what should I do about it” — you’re working against the grain.


    The Scale Limit Nobody Mentions

    There is a hard limit of 1,000 Tasks per data pipeline. For very large implementations this is an issue and you need to split out the data pipeline into multiple separate data pipelines as a workaround. Sonra

    Most teams won’t hit 1,000 tasks. But if you’re building a platform for multiple teams — separate pipelines per business domain, each with their own task trees — you will eventually bump into governance and management complexity that a 1,000-task-per-pipeline limit doesn’t help with.

    More practically: managing dozens of separate task trees, each owned by a different role, with different schedules, different failure behaviours, and no unified view across all of them — is hard. There’s no Snowflake-native equivalent of Airflow’s DAG list view where you can see all pipelines, their last run status, and their next scheduled run in one place.


    What I Use Instead — And Why

    I switched to Airflow with the SQLExecuteQueryOperator for Snowflake, and I’ve written about this setup in depth in my post How I Wired Snowflake’s Native dbt Projects to Airflow. The short version of why it works better for me:

    Airflow owns orchestration. Snowflake owns execution. That’s the right division of responsibility. Airflow is purpose-built for DAG management, dependency handling, retries, branching, alerting, and observability. Snowflake is purpose-built for data processing at scale. Letting each tool do what it’s best at — instead of asking Snowflake Tasks to be a general-purpose orchestrator — is the cleaner architecture.

    Here’s the pattern I use for a typical pipeline:

    from airflow import DAG
    from airflow.providers.snowflake.operators.snowflake import SQLExecuteQueryOperator
    from airflow.operators.python import BranchPythonOperator
    from datetime import datetime, timedelta
    
    with DAG(
        dag_id='customer_dimension_pipeline',
        schedule_interval='0 6 * * *',
        start_date=datetime(2024, 1, 1),
        catchup=False,
    ) as dag:
    
        load_raw = SQLExecuteQueryOperator(
            task_id='load_raw_customers',
            conn_id='snowflake_analytics',
            sql="CALL raw.sp_load_customers();",
        )
    
        validate_raw = SQLExecuteQueryOperator(
            task_id='validate_raw_row_count',
            conn_id='snowflake_analytics',
            sql="""
                SELECT CASE
                    WHEN COUNT(*) = 0 THEN 1/0  -- Forces task failure if no rows
                    ELSE COUNT(*)
                END FROM raw.customers_staging
                WHERE load_date = CURRENT_DATE();
            """,
        )
    
        run_scd2_merge = SQLExecuteQueryOperator(
            task_id='run_scd2_merge',
            conn_id='snowflake_analytics',
            sql="CALL transforms.sp_customer_scd2_merge();",
        )
    
        refresh_mart = SQLExecuteQueryOperator(
            task_id='refresh_customer_mart',
            conn_id='snowflake_analytics',
            sql="CALL marts.sp_refresh_customer_summary();",
        )
    
        load_raw >> validate_raw >> run_scd2_merge >> refresh_mart

    If validate_raw fails because there are zero rows, the pipeline stops. run_scd2_merge never runs. I get an Airflow alert. I can clear and rerun just validate_raw and everything downstream once the issue is fixed — without touching load_raw again.

    That conditional validation step alone — stopping a pipeline when upstream data is missing — was nearly impossible to implement cleanly with Tasks. With Airflow it’s a forced division by zero in the validation SQL. Ugly, but effective. There are cleaner ways with ShortCircuitOperator too.


    To Be Fair: When Snowflake Tasks Are Still the Right Choice

    I don’t want this to read as “never use Tasks.” That’s not what I’m saying.

    Tasks are still my first choice for:

    Micro-refresh patterns. A Task + Stream combination for near-real-time SCD2 updates — triggering only when the stream has data — is elegant and genuinely hard to replicate cleanly in Airflow. I covered exactly this pattern in my post Snowflake Streams and Tasks for SCD2 — How I Actually Use Them.

    Simple scheduled SQL. A single SQL statement that needs to run every 30 minutes with no dependencies? Task all the way. Zero ops overhead for maximum simplicity.

    Snowflake-only pipelines with no external context. If your pipeline never needs to know anything about the outside world — no API calls, no file system checks, no cross-system dependencies — Tasks keep everything in one place.

    Small teams with no existing orchestration infrastructure. If you’re a team of two data engineers and setting up Airflow feels like overkill, Tasks get you 80% of the way there with 10% of the setup cost.

    The honest decision framework:

    ScenarioUse
    Simple scheduled SQL, no branchingSnowflake Tasks
    Stream-triggered incremental loadsSnowflake Tasks + Streams
    Multi-step pipeline with retry requirementsAirflow
    Conditional branching based on row countsAirflow
    Pipelines touching external systemsAirflow
    Cross-team pipelines needing unified observabilityAirflow
    Large task trees (50+ steps)Airflow

    The Honest Summary

    I didn’t stop using Snowflake Tasks because they’re bad. I stopped using them as my primary orchestration layer because that’s not what they’re optimised for — and I was asking them to do a job they weren’t built to do well.

    Snowflake Tasks handle most data orchestration patterns, but the real question is who actually plays well with Snowflake as more than just a place to send SQL. Monte Carlo Tasks are Snowflake’s answer to simple scheduling. Airflow is the answer to complex orchestration. Knowing which problem you actually have is the whole game.

    If your pipelines are growing, your failure debugging is getting slower, and you’ve found yourself writing stored procedures to simulate branching logic — that’s the sign. That’s the moment I had. The switch to Airflow was a weekend of setup and a week of migration, and I haven’t looked back.

  • Snowflake Cortex Code Cost Control: Setting Per-User Credit Limits

    Snowflake Cortex Code Cost Control: Setting Per-User Credit Limits

    This post is for Snowflake admins and data engineering leads whose teams use Cortex Code. It explains how Cortex Code is billed on each surface, the per-user credit limit parameters Snowflake provides, how to set account defaults and per-user overrides, how to audit overrides, and how to watch actual usage.

    When I first started using Cortex Code, cost was the last thing on my mind. It’s right there in the Snowsight UI, it feels like a built-in feature, and nothing in the interface tells you that tokens are being consumed behind the scenes.

    Then I read the official docs properly, not just the feature overview but the cost controls section, and found something I hadn’t seen covered anywhere: Snowflake has a native, dedicated cost control system for Cortex Code that most people don’t know exists. Two parameters, per user, per surface, which an ACCOUNTADMIN can configure in seconds. If you run Cortex Code in your account, especially with a team, you need to set these up.

    Tracking Cortex Code consumption before applying per-user credit limits.

    How Cortex Code Billing Works

    If you’re new to Cortex Code, read my earlier post What Is Snowflake Cortex Code and How I Taught Myself to Use It first. It covers what the tool does and how to access it in Snowsight. This post picks up at the cost control layer.

    Cortex Code runs on two surfaces, each with its own billing model:

    • Cortex Code in Snowsight, the browser-based UI. Token-based billing tied to your existing Snowflake account. Snowflake will notify users before charges formally begin, but AI service costs are already accumulating underneath.
    • Cortex Code CLI, the command-line agent. Already billing on token consumption: pay-as-you-go for existing Snowflake accounts, or a subscription for individual sign-ups.

    The key point: unlike virtual warehouses, where you can set a Resource Monitor with a credit quota, Cortex Code has its own cost control parameters that Resource Monitors don’t cover. You have to set them explicitly.

    For the full official breakdown, see Snowflake’s Cortex Code billing documentation.

    The two parameters

    Snowflake provides exactly two parameters for Cortex Code cost control. Both are set by ACCOUNTADMIN only, work on a rolling 24-hour window per user, and are independent of each other.

    ParameterSurface ControlledDefault
    CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USERCortex Code CLI-1 (unlimited)
    CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USERCortex Code in Snowsight-1 (unlimited)

    What the values mean:

    ValueBehaviour
    -1 (default)No limit, unlimited access
    0Access blocked entirely for that user
    Any positive numberAccess blocked once estimated credits exceed that number in the past 24 hours

    Full parameter reference: Cost controls for Cortex Code (Snowflake docs).


    Setting the limits

    Account-level limits

    This is the first thing I’d do: set a sensible default for every user at the account level. Anyone who goes over it is blocked until the rolling window resets. No silent runaway spend.

    -- Cap all users at 20 credits per day for CLI
    ALTER ACCOUNT SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 20;
    
    -- Cap all users at 20 credits per day in Snowsight
    ALTER ACCOUNT SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 20;

    To remove an account-level limit and restore unlimited access:

    ALTER ACCOUNT UNSET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER;
    ALTER ACCOUNT UNSET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER;

    For the full syntax, see ALTER ACCOUNT (Snowflake docs).

    Per-user overrides

    A user-level setting overrides the account-level setting for that user. Everyone else keeps the account default.

    -- Power user gets a higher CLI limit than the account default
    ALTER USER power_user SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 50;
    
    -- Junior analyst gets a tighter Snowsight limit
    ALTER USER junior_analyst SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 5;
    
    -- Block a service account or contractor from Snowsight entirely
    ALTER USER contractor_account SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 0;

    Setting the value to 0 blocks that user completely on that surface, which is useful for service accounts that should never use Cortex Code interactively.

    To remove a user-level override and fall back to the account default:

    ALTER USER junior_analyst UNSET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER;

    For the full syntax, see ALTER USER (Snowflake docs).

    A Practical Setup for a Team

    Here’s how I’d configure this for a typical data engineering team with senior engineers, analysts and a few service accounts. The script sets a 20-credit default on both surfaces, raises the CLI limit to 50 for named senior engineers, and blocks the Airflow and dbt service users on both surfaces. Replace the user names with your own.

    -- Step 1: Set sensible defaults for the whole account
    ALTER ACCOUNT SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 20;
    ALTER ACCOUNT SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 20;
    
    -- Step 2: Give senior engineers more headroom on CLI
    ALTER USER senior_eng_1 SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 50;
    ALTER USER senior_eng_2 SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 50;
    
    -- Step 3: Block service accounts from both surfaces
    ALTER USER airflow_svc SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 0;
    ALTER USER airflow_svc SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 0;
    
    ALTER USER dbt_svc SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 0;
    ALTER USER dbt_svc SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 0;

    If you run dbt projects natively inside Snowflake, you’ll already have dedicated service accounts; I covered that setup in How I Wired Snowflake’s Native dbt Projects to Airflow. Those same service accounts should be blocked from Cortex Code with a 0 limit.

    Service accounts should never use Cortex Code. Setting them to 0 explicitly means that even if someone accidentally grants CORTEX_AGENT_USER to a service role, the credit limit acts as a safety net.


    Auditing who has custom limits

    The official docs include a script that lists every user with a per-user override, which is what you need for a quarterly governance review. It runs SHOW USERS, loops over each user, runs SHOW PARAMETERS for the CLI limit in that user’s scope, and keeps only rows where the level is USER, meaning a real override rather than the inherited account value.

    -- Audit all users with a custom CLI credit limit override
    EXECUTE IMMEDIATE $$
    DECLARE
      current_user STRING;
      rs_users RESULTSET;
      res      RESULTSET;
    BEGIN
      CREATE OR REPLACE TEMPORARY TABLE _param_overrides (user_name STRING, param_value STRING);
    
      SHOW USERS;
      rs_users := (SELECT "name" FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())));
    
      FOR record IN rs_users DO
        current_user := record."name";
    
        EXECUTE IMMEDIATE
          'SHOW PARAMETERS LIKE ''CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER'' IN USER "' || :current_user || '"';
    
        INSERT INTO _param_overrides (user_name, param_value)
          SELECT :current_user, "value"
          FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
          WHERE "level" = 'USER';
      END FOR;
    
      res := (SELECT * FROM _param_overrides);
      RETURN TABLE(res);
    END;
    $$;

    To audit Snowsight overrides instead, swap CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER for CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER in the SHOW PARAMETERS LIKE clause. Run both regularly. The script is taken directly from the official Snowflake cost controls page; I haven’t modified it.


    What happens when a user hits the limit

    When a user’s rolling 24-hour usage goes over the threshold, that surface returns an error saying the daily credit limit has been reached. They can’t use it again until enough time passes for their usage to drop below the limit. The other surface is unaffected: hitting the CLI limit doesn’t lock them out of Snowsight.

    Admins can raise or remove the limit at any time to restore access immediately, without waiting for the window to roll.

    Tell your team before you set limits, because nobody likes a sudden block mid-workflow. Set the limits, tell people what they are, and tell them who to contact for a temporary increase.


    Monitoring actual usage

    The credit limits control access and stop runaway spend. You also want visibility into consumption before anyone hits a limit, so pair the limits with a monitoring query:

    SELECT
        DATE_TRUNC('day', start_time)   AS usage_day,
        function_name,
        model_name,
        SUM(tokens_used)                AS total_tokens,
        SUM(credits_used)               AS total_credits
    FROM snowflake.account_usage.cortex_functions_usage_history
    WHERE start_time >= CURRENT_DATE - 30
    GROUP BY 1, 2, 3
    ORDER BY usage_day DESC, total_credits DESC;

    This shows which models and functions are driving cost across the account over the last 30 days, by day. The credit limits stop the bleeding; this query tells you where it’s coming from.

    For more on how Snowflake bills AI functions in general (token rates, model pricing differences, and what output tokens mean for your bill), see my post Snowflake Cortex Pricing: What Every Data Engineer Should Know and the official Snowflake Service Consumption Table, which is the source of truth for current credit rates.


    The setup in five steps

    A sensible Cortex Code cost control setup takes about 10 minutes:

    1. Set account-level daily limits for both CLI and Snowsight. 20 credits is a reasonable starting default.
    2. Override upward for power users who need more headroom.
    3. Override to 0 for all service accounts.
    4. Run the audit script quarterly to catch drift as people join or leave the team.
    5. Monitor cortex_functions_usage_history for spend patterns alongside your limits.

    The alternative is the default: -1 for every user, unlimited spend, and a bill that arrives before anyone realized the meter was running.

  • Snowflake Interview Questions — Expert Level

    Snowflake Interview Questions — Expert Level

    After all of this, the real tell at the senior level isn’t whether you know all these answers. It’s whether you can connect them.

    The best signal a senior candidate gives is when they answer one question and naturally reference another. “That’s the same clustering depth issue I mentioned earlier — the root cause is the same even though the symptoms look different.” That kind of connected thinking is what separates someone who’s read about Snowflake from someone who’s been debugging production issues at midnight.

    These aren’t different topics. They’re the same platform, looked at from different angles. That’s what the senior interview is actually testing.

    Good luck — and if any of these scenarios show up in your interview and you crack it, come back and let me know.

    I’ve been on both sides of the Snowflake interview table now. I’ve been the nervous one trying to remember what CLUSTER_BY actually does under pressure, and I’ve been the one reviewing candidates who clearly memorized a blog post instead of actually understanding the platform.

    There’s a massive gap between what the generic “Top 50 Snowflake Interview Questions” articles prepare you for and what a senior data engineering interview actually feels like. This article is about that gap.

    Nobody at the senior level is going to ask you “what is a virtual warehouse.” What they’re going to do is describe a production scenario — something that went wrong, or a design problem they’re genuinely wrestling with — and see how you think through it. They want to know if you’ve actually been inside the query profile. If you’ve ever had a Snowpipe backlog and had to figure out why. If you understand what “spilling to remote storage” means for your credit bill.

    This is the article I wish existed when I was preparing. I’m writing it from everything I’ve learned building real things on Snowflake — not from documentation tabs.


    How to Read This Article

    I’ve organized questions into six categories that match how real interviews are structured:

    1. Architecture & Internals
    2. Performance Tuning & Query Optimization
    3. Cost Management & Credits
    4. Data Ingestion & Pipelines
    5. Security, Governance & RBAC
    6. Real-World Scenario Questions (the hardest ones)

    Each question comes with what a strong answer actually sounds like — not bullet points you memorize, but the kind of connected thinking that signals you’ve done this for real.


    Category One: Architecture & Internals

    These questions separate people who’ve read the docs from people who understand the engine.


    Q1. Walk me through what actually happens when a query hits Snowflake — from the moment I press Run to the moment results appear.

    This is the architecture question that trips up even experienced people because they know the three layers but can’t connect them into a real execution story.

    A strong answer: When you submit a query, it first hits the Cloud Services layer — this is Snowflake’s brain. It authenticates you, parses the SQL, checks metadata in the global metadata store (which knows exactly which micro-partitions hold your data without touching a warehouse), and builds a query execution plan. This whole step runs without your virtual warehouse even waking up.

    If the results of this exact query are already in the result cache — and the underlying data hasn’t changed — Snowflake returns those results instantly from Cloud Services. Zero warehouse credits consumed. This is why identical repeated queries on unchanged data are free.

    If there’s no cached result, the query gets dispatched to your virtual warehouse — the compute layer. The warehouse spins up worker nodes (if suspended, there’s a small cold-start cost), and each node fetches the relevant micro-partitions from cloud storage — S3, Azure Blob, or GCS. This data gets loaded into the warehouse’s local SSD cache (the local disk cache). The workers process it in parallel using MPP (Massively Parallel Processing), and results flow back to the Cloud Services layer, which caches them in the result cache, then returns them to you.

    The key insight: storage is completely decoupled from compute. Multiple warehouses can read the same data simultaneously without contention. This is the fundamental reason Snowflake handles concurrent workloads better than traditional MPP databases.


    Q2. Explain micro-partitioning. How does it actually affect query performance and what can go wrong?

    Snowflake automatically divides table data into micro-partitions — immutable, compressed columnar files, typically between 50 and 500 MB of uncompressed data. Each micro-partition stores metadata: min and max values for each column, number of distinct values, null counts.

    When a query runs with a WHERE clause, Snowflake uses this metadata to prune micro-partitions — skipping any partition where the filter condition can’t possibly match. If your query is WHERE order_date = '2024-01-15', Snowflake checks the min/max metadata on order_date for each micro-partition and skips any partition where 2024-01-15 is outside that range. It never reads those partitions.

    The failure mode: if data is poorly clustered — meaning order_date values are scattered randomly across hundreds of micro-partitions — pruning becomes ineffective. Snowflake has to read most of the table to find your rows. This is when you see large “Bytes scanned” numbers in the query profile despite a tight filter.

    Check clustering health with:

    SELECT SYSTEM$CLUSTERING_INFORMATION(
        'orders',
        '(order_date)'
    );

    Look at average_depth. A value close to 1.0 means excellent pruning. Higher values mean data is scattered and clustering is poor.

    What can make clustering degrade over time: heavy DML operations (lots of individual INSERTs or UPDATEs) scatter data across new micro-partitions without regard to clustering order. For tables that receive continuous small inserts, consider a Clustering Key with automatic reclustering enabled.


    Q3. What is the difference between Automatic Clustering and manually running CLUSTER BY?

    When you define a clustering key on a table, Snowflake can maintain it in two ways.

    Manually triggering ALTER TABLE orders CLUSTER BY (order_date) runs a one-time reclustering operation. It reorganizes existing micro-partitions to improve clustering depth on the specified column. It costs credits and is a point-in-time fix.

    Automatic Clustering is a continuous background service. Once enabled, Snowflake monitors clustering depth and automatically triggers reclustering operations when it detects degradation — typically after significant DML activity. You pay for the compute, but you don’t manage it.

    When should you use automatic clustering vs. not? Automatic clustering makes sense for large tables (generally multi-TB+) that receive continuous writes and are frequently queried with filters on a high-cardinality column. For smaller tables, or tables that are mostly read-only after initial load, the cost of continuous clustering may not justify the query performance improvement. Always benchmark before enabling it.

    A practical note: clustering keys should have high cardinality (lots of distinct values) but not too high — date columns, category columns with dozens of values, and region columns are good candidates. Using a UUID or primary key as a clustering key is usually a mistake — too many distinct values means micro-partitions can’t contain meaningful ranges.


    Q4. Describe the three types of caching in Snowflake and the situations where each one helps you — or fails you.

    This is a question where depth matters more than breadth.

    Result Cache (Cloud Services layer): Stores the complete output of recent queries for up to 24 hours. If you run the same query and the underlying data hasn’t changed, you get the result back instantly with zero warehouse compute. The “data hasn’t changed” check is metadata-based — if any DML touched the relevant tables, the result cache is invalidated.

    Where it fails: if your query uses non-deterministic functions like CURRENT_TIMESTAMP(), RANDOM(), or CURRENT_USER() — or if a WHERE clause references CURRENT_DATE() — the result cache is bypassed entirely because the result could differ on each execution. This is a common gotcha: wrapping a query in a scheduled task that adds WHERE load_date = CURRENT_DATE() means the result cache never kicks in.

    Local Disk Cache (Warehouse layer): When worker nodes fetch micro-partitions from cloud storage, they cache them on local SSD. Subsequent queries that touch the same micro-partitions within the same warehouse session can read from local disk rather than going back to object storage — significantly faster. This cache is per-warehouse and is lost when the warehouse suspends.

    Where it fails: if you suspend your warehouse and resume it, the local cache is cold. For dashboards or BI tools that run queries on a fixed schedule against a specific warehouse, keeping that warehouse running between query bursts (or using auto-resume with a short suspend timeout) preserves the local cache and makes repeated runs faster.

    Metadata Cache (Cloud Services layer): Snowflake maintains metadata about table structure, row counts, min/max values, and partition information entirely in memory in the Cloud Services layer. Many COUNT(*), MIN(), and MAX() queries on simple tables can be answered from metadata alone — without engaging a warehouse at all.

    Where it helps the most: SELECT COUNT(*) FROM large_table that would cost credits on any other platform is often free on Snowflake.


    Category 2: Performance Tuning & Query Optimization


    Q5. You inherit a query that takes 45 minutes. Walk me through your exact diagnostic process.

    A senior candidate’s answer is a structured diagnostic process, not a list of tips.

    Step 1: Open the Query Profile. In Snowsight, find the query in query history and click into the profile. The profile shows you a DAG of query operators — where time was spent, which operator consumed the most credits, and critically: whether there was spillage.

    Step 2: Check for spillage first. Look for “Bytes spilled to local storage” or “Bytes spilled to remote storage” in the query profile. Spillage means the warehouse ran out of memory and had to write intermediate results to disk. Remote spillage is particularly expensive — it means even local SSD wasn’t enough. This is your first escalation trigger. If you see remote spillage, the warehouse is too small for this query. Upsizing the warehouse (SMALL → MEDIUM → LARGE) doubles memory at each step and can eliminate spillage entirely. Upsizing isn’t always the right long-term answer, but it tells you quickly whether memory is the constraint.

    Step 3: Check partition pruning. Look at “Partitions scanned” vs “Partitions total.” If the ratio is high (e.g., 2.4M / 2.5M partitions scanned), the query is doing a near-full table scan. This means either no clustering key, wrong clustering key, or the filter column isn’t selective. Add a filter on a well-clustered column, or reconsider the clustering key.

    Step 4: Check for cartesian joins or bad join order. In the profile DAG, look at the row counts flowing between join operators. If an intermediate join is exploding rows to billions before a later filter reduces them, the query logic needs rewriting — push filters earlier or restructure CTEs.

    Step 5: Check for repeated subqueries. A correlated subquery inside a CASE statement or a nested SELECT that re-executes per row is a classic SQL performance killer. Rewrite using window functions or pre-aggregated CTEs.

    Step 6: Check the warehouse size vs. the data volume. Snowflake’s query optimizer makes different decisions at different warehouse sizes. An XL warehouse processes 16x the data per unit time as an XS. For one-off heavy queries, temporarily bumping to a larger warehouse is often cheaper (faster completion = fewer total credits) than running a smaller warehouse for much longer.


    Q6. Scenario: A dbt model that was running in 8 minutes is now taking 35 minutes. Nothing in the SQL changed. What do you investigate?

    This is the scenario that makes senior candidates shine because it forces them to think about things outside the SQL.

    The first question I’d ask: did anything change in the data, even if the SQL didn’t change? If row volume doubled (new data source onboarded, historical backfill ran), the same query legitimately takes longer. Check row counts in the source tables against last month.

    Second: did the warehouse change? If the warehouse was downsized or its MAX_CLUSTER_COUNT was reduced, the same query runs with less compute. Check warehouse history.

    Third: clustering degradation. If the table receives continuous inserts and has a clustering key, clustering depth degrades over time as new micro-partitions are added in insertion order rather than cluster order. Run SYSTEM$CLUSTERING_INFORMATION and compare to a baseline. If average_depth climbed significantly, reclustering is overdue.

    Fourth: check if a new index of activity appeared in QUERY_HISTORY around the same time the slowdown started. Sometimes a new workload hitting the same warehouse — a new analyst running heavy queries during your pipeline window — causes credit contention that slows your job. The fix is workload isolation: move the pipeline to a dedicated warehouse.

    Fifth: run the query on a larger warehouse and compare. If it’s proportionally faster, it’s a compute-bound problem. If it’s not faster, it’s a data or SQL problem.


    Q7. What is a multi-cluster warehouse, and when would you specifically choose NOT to use one?

    A multi-cluster warehouse allows Snowflake to spin up additional warehouse clusters automatically when queuing occurs — concurrency scaling for a single warehouse. Instead of queries waiting in line because the single-cluster warehouse is at max concurrency, a second (or third, up to your max setting) cluster spins up to serve additional queries.

    When to use it: high-concurrency workloads where many users or processes are querying simultaneously. BI tools with dozens of dashboards refreshing at the same time. ETL pipelines that run many parallel tasks. Anything where queries are frequently queuing.

    When NOT to use it: for a single-user or low-concurrency workload, multi-cluster adds cost with no benefit — you’re paying for cluster management overhead. Also: multi-cluster doesn’t help a single slow query. One 45-minute query does not benefit from a second cluster spinning up because the bottleneck is compute for that one query, not concurrency. For that scenario, you want a larger single-cluster warehouse, not more clusters.

    The billing nuance: each active cluster in a multi-cluster warehouse is billed separately. A MEDIUM warehouse running 3 clusters simultaneously costs 3x a single MEDIUM warehouse. This is appropriate and expected for high-concurrency workloads — but if multi-cluster is accidentally enabled on a warehouse that doesn’t need it, you’ll see credits spike unnecessarily.


    Category 3: Cost Management & Credits


    Q8. Scenario: Your Snowflake credits spiked 3x last Tuesday vs. the previous Tuesday. How do you diagnose this?

    This is a real operational scenario and interviewers love it because it tests whether you know ACCOUNT_USAGE views.

    -- Step 1: Identify which warehouses drove the spike
    SELECT
        warehouse_name,
        DATE(start_time)            AS usage_date,
        SUM(credits_used)           AS total_credits
    FROM snowflake.account_usage.warehouse_metering_history
    WHERE start_time >= DATEADD('day', -14, CURRENT_TIMESTAMP())
    GROUP BY warehouse_name, DATE(start_time)
    ORDER BY usage_date, total_credits DESC;

    This immediately tells you which warehouse(s) were responsible.

    -- Step 2: Drill into queries on that warehouse during the spike window
    SELECT
        query_id,
        query_text,
        user_name,
        warehouse_name,
        execution_time / 1000       AS execution_seconds,
        bytes_spilled_to_remote_storage,
        bytes_scanned,
        credits_used_cloud_services
    FROM snowflake.account_usage.query_history
    WHERE warehouse_name = 'TRANSFORM_WH'
      AND DATE(start_time) = '2024-01-16'
    ORDER BY execution_time DESC
    LIMIT 20;

    Look for: unusually long execution times, massive bytes_scanned values, or high bytes_spilled_to_remote_storage — all signals of expensive queries. Also check if the number of queries is simply higher (new pipeline deployed, more users added).

    -- Step 3: Check if a new pipeline or user caused the spike
    SELECT
        user_name,
        COUNT(*) AS query_count,
        SUM(execution_time) / 1000 AS total_execution_seconds
    FROM snowflake.account_usage.query_history
    WHERE DATE(start_time) = '2024-01-16'
    GROUP BY user_name
    ORDER BY total_execution_seconds DESC;

    Once you identify the culprit, add a Resource Monitor to prevent recurrence:

    CREATE OR REPLACE RESOURCE MONITOR transform_wh_monitor
      WITH CREDIT_QUOTA = 500
      FREQUENCY = MONTHLY
      START_TIMESTAMP = IMMEDIATELY
      TRIGGERS
        ON 80 PERCENT DO NOTIFY
        ON 100 PERCENT DO SUSPEND_IMMEDIATE;
    
    ALTER WAREHOUSE transform_wh SET RESOURCE_MONITOR = transform_wh_monitor;

    Q9. What’s the practical difference between Transient and Permanent tables, and when would misusing them burn you?

    Permanent tables have full Time Travel (up to 90 days) and a 7-day Fail-safe period after Time Travel expires. Both features consume storage — Snowflake keeps the historical micro-partitions for the retention window.

    Transient tables have Time Travel capped at 1 day, and zero Fail-safe. They cost less storage because there’s no extended historical data being maintained.

    When transient tables make sense: staging tables and intermediate transformation tables that you rebuild completely each run. If a table is truncated and reloaded daily, paying for 90 days of Time Travel on that data is pure waste.

    The burn scenario: someone creates all their core business tables as transient to save costs. Then a developer runs DELETE FROM customer_dim WHERE segment = 'Enterprise' with a bug in the WHERE clause — and instead of filtering to test accounts, it deletes 40,000 live customer records. With a permanent table, you’d recover with a Time Travel query in 5 minutes. With a transient table, if this happened 2 days ago, that data is gone. Fail-safe doesn’t exist for transient tables. Recovery now means a full source-system re-extract and reload.

    The right pattern: transient for staging and scratch tables. Permanent for anything that is a source of truth.


    Category #4: Data Ingestion & Pipelines


    Q10. You set up Snowpipe to ingest data from an S3 bucket. After two weeks it stops loading new files. Files are landing in S3 but not appearing in Snowflake. Walk me through your debugging process.

    Snowpipe is event-driven — it relies on S3 event notifications (or Snowflake’s AUTO_INGEST) to trigger. If notifications stop firing, files pile up silently.

    Step 1: Check the pipe status.

    SELECT SYSTEM$PIPE_STATUS('my_schema.my_pipe');

    Look at pendingFileCount, lastIngestedTimestamp, and executionState. If executionState is PAUSED or STOPPED, that’s your immediate answer.

    Step 2: Check for load errors.

    SELECT *
    FROM TABLE(INFORMATION_SCHEMA.COPY_HISTORY(
        TABLE_NAME => 'target_table',
        START_TIME => DATEADD('day', -3, CURRENT_TIMESTAMP())
    ))
    WHERE STATUS != 'Loaded'
    ORDER BY LAST_LOAD_TIME DESC;

    If files attempted to load and failed — schema mismatch, malformed JSON, wrong delimiter — Snowpipe silently skips them after the error threshold. Files that fail repeatedly get quarantined and stop triggering new notifications.

    Step 3: Check SQS queue (for S3 auto-ingest).

    For S3-triggered Snowpipe, Snowflake creates an SQS queue that receives S3 event notifications. If that SQS queue fills up (it has limits) or the S3 event notification configuration was accidentally removed, events stop flowing.

    Step 4: Check file format.

    If someone modified the source system’s file format — added a column, changed the delimiter from comma to pipe, switched from gzip to uncompressed — and the Snowpipe file format definition wasn’t updated, every new file fails silently.

    Prevention: set up a monitoring query as a scheduled Snowflake Task that alerts when lastIngestedTimestamp hasn’t updated in more than X hours. Don’t wait for a stakeholder to notice missing data.


    Q11. What is the difference between Streams and Tasks in Snowflake, and give me a real scenario where you’d use them together?

    A Stream is a change data capture object. It sits on top of a table and tracks INSERT, UPDATE, and DELETE operations that occurred since the stream was last consumed. It doesn’t store data — it stores metadata about what changed and where those changed rows are. Querying a stream returns the rows that changed and a METADATA$ACTION column telling you whether they were INSERTed, UPDATEd (shows as DELETE + INSERT), or DELETEd.

    A Task is a scheduled SQL executor. It runs a SQL statement on a schedule (cron-style) or as part of a task tree (dependency-based). Tasks can be configured to run only if a stream has data — this is the key integration.

    Real scenario — SCD Type 2 on a customer dimension:

    -- Stream on the raw customer table to capture changes
    CREATE OR REPLACE STREAM customer_changes_stream
      ON TABLE raw.customers;
    
    -- Task that runs every 15 minutes but only if stream has data
    CREATE OR REPLACE TASK apply_scd2_changes
      WAREHOUSE = transform_wh
      SCHEDULE = '15 MINUTE'
      WHEN SYSTEM$STREAM_HAS_DATA('customer_changes_stream')
    AS
      MERGE INTO dim_customers AS target
      USING (
          SELECT
              customer_id,
              customer_name,
              email,
              segment,
              METADATA$ACTION,
              METADATA$ISUPDATE
          FROM customer_changes_stream
          WHERE METADATA$ACTION = 'INSERT'
      ) AS changes
      ON target.customer_id = changes.customer_id
         AND target.is_current = TRUE
      WHEN MATCHED AND changes.METADATA$ISUPDATE = TRUE THEN
          UPDATE SET target.end_date = CURRENT_DATE(),
                     target.is_current = FALSE
      WHEN NOT MATCHED THEN
          INSERT (customer_id, customer_name, email, segment,
                  start_date, end_date, is_current)
          VALUES (changes.customer_id, changes.customer_name,
                  changes.email, changes.segment,
                  CURRENT_DATE(), NULL, TRUE);
    
    ALTER TASK apply_scd2_changes RESUME;

    The WHEN SYSTEM$STREAM_HAS_DATA() condition is critical — it means the task doesn’t consume warehouse credits on runs where nothing changed. The task wakes up, checks the condition, finds the stream empty, and goes back to sleep. Only on runs where actual customer data changed does it spin up the warehouse and execute the MERGE.


    Category Five: Security, Governance & RBAC


    Q12. Your security team asks you to ensure that the analytics team can see a salary column in aggregate reports but cannot see individual employee salaries. How do you implement this in Snowflake?

    This is a column-level security scenario. Snowflake has two tools here: Dynamic Data Masking and Secure Views.

    The cleaner approach for this scenario is Dynamic Data Masking:

    -- Create a masking policy
    CREATE OR REPLACE MASKING POLICY mask_salary
      AS (val NUMBER) RETURNS NUMBER ->
        CASE
            WHEN CURRENT_ROLE() IN ('HR_ADMIN', 'SYSADMIN') THEN val
            ELSE NULL   -- Or return 0, or a rounded bucket
        END;
    
    -- Apply it to the salary column
    ALTER TABLE employees
      MODIFY COLUMN salary
      SET MASKING POLICY mask_salary;

    Now anyone in HR_ADMIN sees actual salaries. Everyone else sees NULL in that column. The table structure is the same — no separate view to maintain, no duplication of logic across multiple views. The policy travels with the column.

    For the aggregate-only requirement (they can see AVG(salary) but not individual values), a Secure View is the right tool:

    CREATE OR REPLACE SECURE VIEW employee_salary_summary AS
    SELECT
        department,
        job_grade,
        COUNT(*) AS headcount,
        ROUND(AVG(salary), -3) AS avg_salary_rounded,  -- rounds to nearest 1000
        MIN(salary) AS min_salary,
        MAX(salary) AS max_salary
    FROM employees
    GROUP BY department, job_grade
    HAVING COUNT(*) >= 5;  -- don't expose groups with fewer than 5 employees

    The HAVING COUNT(*) >= 5 clause is deliberate — without it, a determined analyst could infer individual salaries by filtering to groups of one. This is basic statistical disclosure control, and senior candidates who mention it unprompted stand out.

    The SECURE keyword on the view hides the view definition from users who don’t own it — they can’t inspect the SQL to reverse-engineer what’s being hidden.

    Q13. Walk me through how you’d structure Snowflake RBAC for a mid-sized company — say 3 teams: Data Engineering, Analytics, and Finance BI.

    This is an architecture question. A weak answer lists roles. A strong answer describes a hierarchy.

    The Snowflake recommendation is a functional role hierarchy:

    ACCOUNTADMIN (Snowflake admin only — almost never used day-to-day)
        └── SYSADMIN
                ├── DE_ADMIN (Data Engineering admin role)
                │       ├── DE_DEVELOPER (read/write on raw + staging)
                │       └── DE_READER (read-only on staging)
                ├── ANALYTICS_ADMIN
                │       ├── ANALYTICS_DEVELOPER (read/write on marts)
                │       └── ANALYTICS_READER (read-only on marts)
                └── FINANCE_BI_ADMIN
                        └── FINANCE_BI_READER (read-only on finance mart)

    Each human user gets a user role (e.g., user_bug) which is granted the appropriate functional role. Users never log in as SYSADMIN or ACCOUNTADMIN. Those are break-glass roles used only for admin operations, and any use of them should generate an alert via ACCOUNT_USAGE.LOGIN_HISTORY.

    Object ownership matters: every object should be owned by a functional role (like DE_ADMIN), not by a personal user account. If the person who created the table leaves, their user is disabled — and if they owned the objects, those objects become inaccessible until ownership is transferred. This is a real operational problem that catches teams who didn’t plan RBAC carefully.

    Service accounts (Airflow, dbt, Fivetran) get dedicated roles scoped to exactly what they need. An Airflow service account does not need SYSADMIN. It needs USAGE on specific schemas, CREATE TABLE in specific schemas, and EXECUTE TASK if it manages Tasks. Nothing more.


    Category six: Real-World Scenario Questions

    These are the ones that show up in final-round interviews and engineering manager panels.


    Q14. A finance stakeholder tells you that a revenue number in their Snowflake dashboard changed retroactively — last Tuesday it showed $4.2M, today it shows $3.8M for the same date. How do you investigate and what do you tell the stakeholder?

    The first thing I’d do is use Time Travel to find out what the data actually looked like at the time they reported $4.2M:

    -- See what the table looked like when they saw 4.2M
    SELECT SUM(order_amount) AS total_revenue
    FROM orders
      AT (TIMESTAMP => '2024-01-16 09:00:00')  -- time they saw the report
    WHERE DATE(order_date) = '2024-01-09';
    
    -- Compare to current value
    SELECT SUM(order_amount) AS total_revenue
    FROM orders
    WHERE DATE(order_date) = '2024-01-09';

    If there’s a difference, the data changed between those two timestamps. Now find out what changed:

    -- Use a stream-style comparison or Time Travel diff
    SELECT order_id, order_amount
    FROM orders
      AT (TIMESTAMP => '2024-01-16 09:00:00')
    
    MINUS
    
    SELECT order_id, order_amount
    FROM orders;

    This gives you the rows that existed in the old version but were removed or changed. Cross-reference these order IDs with the source system — were they returns? Cancelled orders? A pipeline bug that incorrectly deleted records?

    What to tell the stakeholder: be transparent and specific. “The revenue figure changed because X orders were retroactively cancelled/corrected in the source system between Tuesday and today. Here are the specific order IDs. The current figure is correct.” Don’t just tell them the number changed — give them the reason and the evidence. Stakeholders who trust your data trust your investigative process.

    Q15. You’re designing a Snowflake data platform for a company that has data analysts, data scientists, and BI developers all sharing the same account. Each group runs different query patterns. How do you structure warehouses?

    Workload isolation is the core principle. Different query patterns compete for the same resources if they share a warehouse — and they do so invisibly, making debugging harder and degrading everyone’s experience.

    My recommended structure:

    Analysts warehouse (ANALYTICS_WH — MEDIUM, multi-cluster max 3): Handles ad-hoc analyst queries. These are typically medium-length, moderately complex, need fast turnaround. Multi-cluster handles concurrency spikes when everyone runs queries at once. Auto-suspend after 5 minutes.

    BI/Reporting warehouse (BI_WH — SMALL, auto-suspend 1 minute): Serves Tableau/Power BI dashboard queries. These are typically fast, repetitive, and benefit heavily from result cache. Small warehouse is fine because result cache handles most of the work. Short auto-suspend because dashboards tend to query in bursts.

    Data Science warehouse (DS_WH — LARGE or XL, auto-suspend 10 minutes): Data scientists run long-running exploratory queries, training feature pipelines, and large aggregations. These need raw compute power. Larger warehouse, longer suspend time to preserve local cache between iterative runs.

    Pipeline/ELT warehouse (TRANSFORM_WH — MEDIUM or LARGE, no auto-suspend during pipeline window): Dedicated to dbt, Airflow, and scheduled tasks. Isolated from user-facing workloads so a heavy pipeline run doesn’t slow down analyst queries. Configure Resource Monitor here to prevent runaway pipeline credits.

    The key point for interviewers: I explicitly call out that the BI warehouse is small because of result cache behavior. Most candidates say “make BI bigger for performance.” The correct answer is: BI workloads are naturally cache-friendly, so a small warm warehouse outperforms a large cold one for dashboard queries.


    Q16. Describe a time Snowflake’s architecture surprised you — either positively or negatively.

    I’ll give you a real one from my experience.

    I inherited a data pipeline where someone had set up a Snowflake Task tree — about 12 tasks chained together to run a nightly data quality suite. Each task ran a SQL check and wrote results to a DQ log table. The whole tree was supposed to complete in about 25 minutes.

    It was taking 3 hours.

    When I investigated, I found that the task tree was configured with a 1-minute schedule on the root task but the individual tasks had their dependencies set up as AFTER relationships. What nobody had realized: each task in the chain was waiting for its predecessor to complete AND for the next 1-minute schedule tick before executing. With 12 tasks, each waiting 30-45 seconds plus a 1-minute tick, the chain took enormously longer than expected.

    The fix was switching the root task to a scheduled trigger and ensuring the child tasks had AFTER relationships correctly configured as true dependencies (not schedule-based). The tree went from 3 hours to 22 minutes.

    What I learned: Snowflake’s Task scheduling documentation is clear, but the interaction between schedule-based and dependency-based triggers is easy to misconfigure in ways that aren’t immediately obvious. Test task trees with short intervals first, watch the execution history, and validate that the AFTER relationships are actually working as dependencies rather than just ordering constraints.


    Q17. How would you implement row-level security so that regional sales managers can only see data for their region?

    Row-level security in Snowflake is implemented with Row Access Policies.

    -- Create a mapping table: which role sees which regions
    CREATE OR REPLACE TABLE region_access_map (
        role_name  VARCHAR,
        region     VARCHAR
    );
    
    INSERT INTO region_access_map VALUES
        ('SALES_APAC', 'APAC'),
        ('SALES_EMEA', 'EMEA'),
        ('SALES_AMER', 'AMER'),
        ('SALES_ADMIN', 'APAC'),   -- Admin sees everything
        ('SALES_ADMIN', 'EMEA'),
        ('SALES_ADMIN', 'AMER');
    
    -- Create the row access policy
    CREATE OR REPLACE ROW ACCESS POLICY region_row_policy
      AS (row_region VARCHAR) RETURNS BOOLEAN ->
        CURRENT_ROLE() = 'SYSADMIN'
        OR EXISTS (
            SELECT 1 FROM region_access_map
            WHERE role_name = CURRENT_ROLE()
              AND region = row_region
        );
    
    -- Apply to the sales table
    ALTER TABLE sales_transactions
      ADD ROW ACCESS POLICY region_row_policy
      ON (region);

    Now when SALES_APAC queries sales_transactions, Snowflake invisibly adds a filter to every query on that table — they only see APAC rows. They can’t bypass it. They can’t see the policy definition if it’s secured.

    Important senior-level detail: Row Access Policies apply at query time, not at storage time. The data is stored together. The filter happens when Snowflake executes the query. This means you can’t accidentally expose data through joins to other tables — the policy applies to the base table regardless of how it’s joined.

    One gotcha: if a user’s role changes mid-session, the new policy takes effect on the next query. There’s no session-level snapshot of the policy evaluation.

    What Interviewers Are Really Looking For

    After all of this, the real tell at the senior level isn’t whether you know all these answers. It’s whether you can connect them.

    The best signal a senior candidate gives is when they answer one question and naturally reference another. “That’s the same clustering depth issue I mentioned earlier — the root cause is the same even though the symptoms look different.” That kind of connected thinking is what separates someone who’s read about Snowflake from someone who’s been debugging production issues at midnight.

    These aren’t different topics. They’re the same platform, looked at from different angles. That’s what the senior interview is actually testing.

    Good luck — and if any of these scenarios show up in your interview and you crack it, come back and let me know.

  • Orchestrating Snowflake dbt Projects with Airflow: An End-to-End Pipeline

    Orchestrating Snowflake dbt Projects with Airflow: An End-to-End Pipeline

    This post is for teams that already run Airflow and want their dbt transformations to run inside Snowflake instead of on a separate server. It shows how I wired Snowflake’s native dbt Projects into Airflow: the permissions, deploying the project, the DAG, versioning, monitoring, and the gotchas I hit along the way.

    I’ll be honest with you: for a long time I ran dbt the way most people run it. dbt Core installed on a server, a profiles.yml file I kept updating by hand, a cron job (yes, a cron job) doing the scheduling, and Airflow somewhere nearby doing the “real” orchestration while dbt lived in its own separate corner of the infrastructure.

    It worked. It was fine. It was also quietly annoying in ways I’d stopped noticing. Managing the dbt server separately. Keeping the Snowflake credentials synced in two places. Debugging failures by jumping between the Airflow UI, SSH logs on the dbt server and Snowsight, all at once.

    Then Snowflake went GA with dbt Projects in November 2025, and I spent a weekend rebuilding the whole thing. This article is what I learned.

    What we’re building is a genuine end-to-end pipeline: raw data lands in Snowflake, Airflow orchestrates the entire flow, and the dbt transformations run as a native DBT PROJECT object inside Snowflake. Not on an external box, not in a container, but inside Snowflake itself. The monitoring, the scheduling trigger and the execution logs are all in one place.

    What a dbt Project on Snowflake actually is

    The terminology can trip you up, and I don’t want you 45 minutes into setup before the confusion hits.

    dbt Projects on Snowflake let you create, edit, test, run and manage dbt Core projects with Snowflake’s own tools. You work on the project files in Snowsight Workspaces, then deploy the project as a schema-level dbt PROJECT object.

    The key word is object. DBT PROJECT is a first-class, schema-level object: a file container that holds one or more dbt Core projects. It is versioned, so every change made through ALTER adds a new version.

    That means your dbt project (the models, the sources YAML, dbt_project.yml) lives inside Snowflake as a versioned, native object. Not on a VM. Not in an S3 bucket somewhere.

    Out of the box you get a file-based IDE in Workspaces that integrates with Git, a DAG view for inspecting lineage and dependencies in the UI, deployment and scheduling with native Snowflake Tasks, and the ability to run dbt commands such as compile, test and run from Workspaces.

    So yes, you can schedule and run it purely with Snowflake Tasks and never touch Airflow. But if your organization already runs Airflow, or your dbt pipeline is one piece of a larger flow that includes ingestion, validation, downstream alerts and reporting, you want Airflow in charge, calling into Snowflake to execute the DBT PROJECT object. That hybrid approach is what this article covers.

    The architecture we’re building

    Before I show you any code, here is the full picture, because I think this is where most blog posts let you down: they show you a piece without the whole.

    [Source System / S3 / API]
            ↓
    [Airflow DAG starts]
            ↓
      Task 1: Load raw data → Snowflake staging table (via COPY INTO or S3 stage)
            ↓
      Task 2: Run data quality checks on raw data (SQLExecuteQueryOperator)
            ↓
      Task 3: EXECUTE DBT PROJECT → runs dbt build on your native Snowflake dbt project
            ↓
      Task 4: Post-run row count validation (SQLExecuteQueryOperator)
            ↓
      Task 5: Trigger downstream alert / Slack notification / refresh BI layer
            ↓
    [Pipeline complete]

    Airflow owns the orchestration. Snowflake owns the execution of the dbt transformations. The DBT PROJECT object bridges them, because you can trigger it with a SQL command, and Airflow’s SQLExecuteQueryOperator can fire that SQL command.

    That SQL command is simple:

    EXECUTE DBT PROJECT my_database.my_schema.my_dbt_project
      ARGS = 'dbt build'
      VERSION = 'LAST';

    EXECUTE DBT PROJECT runs a dbt project object (or a project in a workspace) with the dbt command and options you pass in ARGS (Snowflake documentation).

    One SQL statement is all Airflow needs to fire. Here is the full setup to make that work.

    Step 1: Snowflake setup (roles, warehouse and permissions)

    I always start here, because bad permissions cause the most confusing failures, and they surface late in the process when you’re tired and frustrated.

    USE ROLE ACCOUNTADMIN;
    
    -- Create a dedicated role for dbt execution
    CREATE OR REPLACE ROLE dbt_executor_role;
    GRANT ROLE dbt_executor_role TO ROLE SYSADMIN;
    
    -- Create the service user Airflow will use
    CREATE OR REPLACE USER airflow_svc_user
      PASSWORD = 'YourStrongPassword123!'
      DEFAULT_ROLE = dbt_executor_role
      DEFAULT_WAREHOUSE = dbt_transform_wh
      COMMENT = 'Airflow service user for dbt orchestration';
    
    GRANT ROLE dbt_executor_role TO USER airflow_svc_user;
    
    -- Create a dedicated warehouse for dbt runs
    USE ROLE SYSADMIN;
    CREATE OR REPLACE WAREHOUSE dbt_transform_wh
      WITH WAREHOUSE_SIZE = 'SMALL'
      AUTO_SUSPEND = 120
      AUTO_RESUME = TRUE
      INITIALLY_SUSPENDED = TRUE;
    
    GRANT ALL ON WAREHOUSE dbt_transform_wh TO ROLE dbt_executor_role;
    
    -- Grant database and schema privileges
    GRANT USAGE ON DATABASE analytics_db TO ROLE dbt_executor_role;
    GRANT USAGE, CREATE TABLE, CREATE VIEW ON SCHEMA analytics_db.staging TO ROLE dbt_executor_role;
    GRANT USAGE, CREATE TABLE, CREATE VIEW ON SCHEMA analytics_db.marts TO ROLE dbt_executor_role;
    
    -- Grant the ability to execute dbt project objects
    GRANT EXECUTE DBT PROJECT ON SCHEMA analytics_db.transforms TO ROLE dbt_executor_role;

    This creates a dedicated role, a service user for Airflow, a Small warehouse that suspends after two minutes, and the grants dbt needs to build into the staging and marts schemas. The dbt project object itself lives in a third schema, transforms. Replace the password and the database and schema names with your own.

    I made a mistake my first time through: I granted object-level access but forgot the schema-level EXECUTE DBT PROJECT privilege, which is separate. The error message wasn’t obvious. Save yourself that 20-minute debugging session.

    Step 2: Deploy your dbt project as a native Snowflake object

    This is the step that feels most different from a traditional dbt Core setup. You’re not installing dbt on a server; you’re registering your project inside Snowflake.

    Option A: Snowsight Workspaces (recommended the first time)

    Log into Snowsight, go to Workspaces and connect it to your Git repository:

    -- First, create an API integration for GitHub
    CREATE OR REPLACE API INTEGRATION github_integration
      API_PROVIDER = git_https_api
      API_ALLOWED_PREFIXES = ('https://github.com/yourorg/')
      ENABLED = TRUE;
    
    -- Create the Git repository object in Snowflake
    CREATE OR REPLACE GIT REPOSITORY dbt_project_repo
      API_INTEGRATION = github_integration
      GIT_CREDENTIALS = my_github_secret
      ORIGIN = 'https://github.com/yourorg/your-dbt-project.git';

    The API integration allows Snowflake to reach your GitHub organization, and the Git repository object points at the repo itself. my_github_secret is a Snowflake secret holding your Git credentials, which you need to create first.

    Option B: Deploy with SQL (good for CI/CD)

    -- Create the DBT PROJECT object from your connected Git repo
    CREATE OR REPLACE DBT PROJECT analytics_db.transforms.sales_dbt_project
      FROM GIT REPOSITORY dbt_project_repo
      REF = 'main'
      TARGET_PATH = 'models/'
      WAREHOUSE = dbt_transform_wh;

    Install dbt dependencies

    You populate the dbt_packages folder by running dbt deps, either in a Snowflake workspace, on your local machine or in your Git-based CI:

    -- Run this once after creating the project, or include in CI/CD
    EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
      ARGS = 'dbt deps'
      VERSION = 'LAST';

    A heads-up: running dbt deps inside Snowflake Workspaces needs an external access integration, because the runtime has to reach external package repositories. The alternative is to run dbt deps locally or in CI and ship the populated dbt_packages folder with your deployment.

    I found it cleaner to run dbt deps in my GitHub Actions pipeline and commit the dbt_packages folder, rather than configuring external access integrations for every environment. Your call; both approaches work.

    Verify the deployment

    -- Check your dbt project versions
    SHOW DBT PROJECTS IN SCHEMA analytics_db.transforms;
    
    -- Test execute manually before wiring Airflow
    EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
      ARGS = 'dbt compile'
      VERSION = 'LAST';

    If dbt compile completes without error, your project is live and ready for Airflow to call.

    Step 3: Set up a real dbt project structure

    Here is what the project actually looks like. I’m using a sales pipeline as the example: raw orders come in, we stage them, and we build a daily summary fact table.

    dbt_project.yml

    name: 'sales_pipeline'
    version: '1.0.0'
    config-version: 2
    
    profile: 'snowflake_prod'
    
    model-paths: ["models"]
    test-paths: ["tests"]
    seed-paths: ["seeds"]
    
    models:
      sales_pipeline:
        staging:
          +schema: staging
          +materialized: view
        marts:
          +schema: marts
          +materialized: table

    Staging models build as views in the staging schema and marts build as tables in the marts schema, which matches the grants from Step 1.

    models/staging/stg_orders.sql

    -- Staging model: clean and type-cast raw orders
    WITH raw AS (
        SELECT * FROM {{ source('raw', 'orders_raw') }}
    ),
    
    cleaned AS (
        SELECT
            order_id::VARCHAR           AS order_id,
            customer_id::VARCHAR        AS customer_id,
            order_date::DATE            AS order_date,
            UPPER(TRIM(status))         AS order_status,
            amount::DECIMAL(18, 2)      AS order_amount,
            region::VARCHAR             AS region,
            CURRENT_TIMESTAMP()         AS _loaded_at
        FROM raw
        WHERE order_id IS NOT NULL
          AND order_date >= '2023-01-01'
    )
    
    SELECT * FROM cleaned

    The staging model casts each column to its proper type, normalizes the status text, drops rows without an order ID and keeps orders from 2023 onwards.

    models/marts/fct_daily_orders.sql

    -- Fact table: daily order summary by region
    WITH staged AS (
        SELECT * FROM {{ ref('stg_orders') }}
    )
    
    SELECT
        order_date,
        region,
        order_status,
        COUNT(DISTINCT order_id)                    AS total_orders,
        COUNT(DISTINCT customer_id)                 AS unique_customers,
        SUM(order_amount)                           AS total_revenue,
        AVG(order_amount)                           AS avg_order_value,
        SUM(CASE WHEN order_status = 'RETURNED' 
                 THEN order_amount ELSE 0 END)      AS returned_amount,
        CURRENT_TIMESTAMP()                         AS _refreshed_at
    FROM staged
    GROUP BY order_date, region, order_status
    ORDER BY order_date DESC, region

    The fact table aggregates staged orders by day, region and status, including the value of returned orders.

    models/staging/sources.yml

    version: 2
    
    sources:
      - name: raw
        database: analytics_db
        schema: raw_landing
        tables:
          - name: orders_raw
            description: "Raw orders from the source system"
            columns:
              - name: order_id
                tests:
                  - not_null
                  - unique
              - name: customer_id
                tests:
                  - not_null
              - name: order_date
                tests:
                  - not_null
              - name: amount
                tests:
                  - not_null

    models/marts/schema.yml

    version: 2
    
    models:
      - name: fct_daily_orders
        description: "Daily order summary by region and status"
        columns:
          - name: order_date
            tests:
              - not_null
          - name: total_orders
            tests:
              - not_null
          - name: total_revenue
            tests:
              - not_null

    This gives us a clean, testable project with source tests and column-level tests. When Airflow executes dbt build, all of it runs (models and tests) in dependency order.

    Step 4: Wire it together in Airflow

    Now the fun part: a complete Airflow DAG that:

    1. Validates that raw data arrived in Snowflake
    2. Fires the native dbt project execution
    3. Validates row counts on the output marts
    4. Marks the pipeline complete, with email alerts on failure

    First, install the Snowflake provider if you haven’t:

    pip install apache-airflow-providers-snowflake

    Set up your Snowflake connection in the Airflow UI (Admin → Connections):

    Connection ID : snowflake_analytics
    Connection Type : Snowflake
    Account  : yourorg.us-east-1
    Login    : airflow_svc_user
    Password : YourStrongPassword123!
    Schema   : transforms
    Database : analytics_db
    Warehouse: dbt_transform_wh
    Role     : dbt_executor_role

    Now the DAG, dags/sales_pipeline_dag.py:

    from airflow import DAG
    from airflow.providers.snowflake.operators.snowflake import SQLExecuteQueryOperator
    from airflow.operators.python import PythonOperator, BranchPythonOperator
    from airflow.operators.empty import EmptyOperator
    from airflow.utils.dates import days_ago
    from datetime import datetime, timedelta
    import logging
    
    # ── Default args ────────────────────────────────────────────────
    default_args = {
        'owner': 'data-engineering',
        'depends_on_past': False,
        'retries': 1,
        'retry_delay': timedelta(minutes=5),
        'email_on_failure': True,
        'email': ['[email protected]'],
    }
    
    SNOWFLAKE_CONN = 'snowflake_analytics'
    
    # ── SQL snippets ─────────────────────────────────────────────────
    RAW_DATA_CHECK_SQL = """
    SELECT COUNT(*) AS raw_row_count
    FROM analytics_db.raw_landing.orders_raw
    WHERE order_date = CURRENT_DATE() - 1;
    """
    
    EXECUTE_DBT_SQL = """
    EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
      ARGS = 'dbt build --select staging.stg_orders+ --vars "{\\"run_date\\": \\"{{ ds }}\\"}"'
      VERSION = 'LAST';
    """
    
    MART_VALIDATION_SQL = """
    SELECT
        COUNT(*) AS mart_row_count,
        MAX(order_date) AS latest_date,
        SUM(total_revenue) AS total_revenue
    FROM analytics_db.marts.fct_daily_orders
    WHERE order_date = CURRENT_DATE() - 1;
    """
    
    ROW_COUNT_GUARD_SQL = """
    SELECT
        CASE
            WHEN COUNT(*) = 0
            THEN 'FAIL: No rows found in mart for yesterday'
            ELSE 'PASS: ' || COUNT(*) || ' rows present'
        END AS validation_result
    FROM analytics_db.marts.fct_daily_orders
    WHERE order_date = CURRENT_DATE() - 1;
    """
    
    # ── DAG definition ───────────────────────────────────────────────
    with DAG(
        dag_id='sales_pipeline_end_to_end',
        default_args=default_args,
        description='End-to-end sales pipeline: raw → dbt native project → marts',
        schedule_interval='0 6 * * *',     # 6 AM UTC daily
        start_date=days_ago(1),
        catchup=False,
        tags=['snowflake', 'dbt', 'sales'],
    ) as dag:
    
        # Task 1: Check raw data arrived
        check_raw_data = SQLExecuteQueryOperator(
            task_id='check_raw_data_arrived',
            conn_id=SNOWFLAKE_CONN,
            sql=RAW_DATA_CHECK_SQL,
            handler=lambda cursor: logging.info(
                f"Raw row count: {cursor.fetchone()[0]}"
            ),
        )
    
        # Task 2: Execute the native dbt project on Snowflake
        run_dbt_project = SQLExecuteQueryOperator(
            task_id='execute_dbt_project_snowflake',
            conn_id=SNOWFLAKE_CONN,
            sql=EXECUTE_DBT_SQL,
            # Give dbt build enough time for large projects
            execution_timeout=timedelta(hours=2),
        )
    
        # Task 3: Post-run mart validation
        validate_mart_output = SQLExecuteQueryOperator(
            task_id='validate_mart_output',
            conn_id=SNOWFLAKE_CONN,
            sql=ROW_COUNT_GUARD_SQL,
            handler=lambda cursor: logging.info(
                f"Validation result: {cursor.fetchone()[0]}"
            ),
        )
    
        # Task 4: Run broader stats query (logged for observability)
        log_mart_stats = SQLExecuteQueryOperator(
            task_id='log_mart_statistics',
            conn_id=SNOWFLAKE_CONN,
            sql=MART_VALIDATION_SQL,
        )
    
        # Task 5: Success marker
        pipeline_complete = EmptyOperator(task_id='pipeline_complete')
    
        # ── Dependencies ─────────────────────────────────────────────
        (
            check_raw_data
            >> run_dbt_project
            >> validate_mart_output
            >> log_mart_stats
            >> pipeline_complete
        )

    The DAG runs every day at 6 AM UTC. It logs how many raw orders arrived for yesterday, runs dbt build on stg_orders and everything downstream of it (passing Airflow’s run date {{ ds }} as a dbt variable), checks that the mart has rows for yesterday, logs summary statistics and finishes on an empty marker task. It starts at the raw-data check, so loading the raw data (Task 1 in the diagram) and the Slack step happen outside this DAG. Note that the raw-data check and the row-count guard only log their results; they won’t stop the run on their own.

    Step 5: Run specific dbt selectors from Airflow

    One of the things I really like about this approach is that dbt’s full selector syntax passes straight through the ARGS parameter. You don’t have to run the entire project every time.

    Run only staging models:

    EXECUTE_STAGING_ONLY = """
    EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
      ARGS = 'dbt run --select staging.*'
      VERSION = 'LAST';
    """

    Run a specific model and everything downstream of it:

    EXECUTE_ORDERS_DOWNSTREAM = """
    EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
      ARGS = 'dbt build --select stg_orders+'
      VERSION = 'LAST';
    """

    Run tests only, separately from the model run:

    RUN_DBT_TESTS = """
    EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
      ARGS = 'dbt test --select staging.*'
      VERSION = 'LAST';
    """

    This means you can split a single DAG into multiple tasks (one for staging, one for marts, one for tests) and get granular retry behavior in Airflow. If something fails mid-pipeline, Airflow retries only the failed task instead of rerunning everything.

    Here’s that pattern as a DAG:

    run_staging = SQLExecuteQueryOperator(
        task_id='run_dbt_staging',
        conn_id=SNOWFLAKE_CONN,
        sql="""
            EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
              ARGS = 'dbt run --select staging.*'
              VERSION = 'LAST';
        """,
    )
    
    test_staging = SQLExecuteQueryOperator(
        task_id='test_dbt_staging',
        conn_id=SNOWFLAKE_CONN,
        sql="""
            EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
              ARGS = 'dbt test --select staging.*'
              VERSION = 'LAST';
        """,
    )
    
    run_marts = SQLExecuteQueryOperator(
        task_id='run_dbt_marts',
        conn_id=SNOWFLAKE_CONN,
        sql="""
            EXECUTE DBT PROJECT analytics_db.transforms.sales_dbt_project
              ARGS = 'dbt run --select marts.*'
              VERSION = 'LAST';
        """,
    )
    
    run_staging >> test_staging >> run_marts

    This is how I actually run it in practice. If staging tests fail, marts never execute. If marts fail, I retry marts without re-running staging. Clean dependency management with very little code.

    Job-level vs model-level orchestration

    Splitting the project by layer, as above, sits between the two approaches the Airflow and dbt community has argued about for years: run all of dbt as one Airflow task (job-level), or give every model its own task (model-level).

    Job-level: one task for the whole run

    One Airflow task runs something like dbt run --select tag:daily. It’s simple: one task, one line of configuration, fast deploys. Most teams picked it for that reason. The downside is that if one model fails in the middle of a 400-model run, the whole job fails, and you have to dig through dbt logs to find which model actually broke.

    Model-level: one task per model

    Astronomer’s open-source Cosmos library changed that. You point Cosmos at your dbt project directory and it generates the Airflow DAG, one task per model, without hand-written task definitions. Parsing 400 models still costs something, roughly 1 to 2 seconds added to DAG parsing, but that’s now acceptable. A failed model shows up as a red task in the Airflow UI with its compile error, instead of “dbt run exited with code 1” in an SSH log.

    Model-level orchestration gives every model its own Airflow task, so failures are scoped to a model and Airflow’s UI shows exactly where the pipeline broke. It used to carry a penalty: rendering 400 models as 400 tasks loaded the Airflow scheduler, DAG parsing time doubled, and the dynamic task generation you had to write was brittle.

    A 400-model example

    One team running Airflow on AWS (3x m5.2xlarge), dbt Core on a separate EC2 box and a MEDIUM Snowflake warehouse compared the two:

    • Job-level with external dbt: dbt run --select tag:daily as a single daily task took 18 minutes wall-clock. A failed model was buried in the dbt log, and debugging took 45+ minutes of correlating dbt logs, Snowflake QUERY_HISTORY and Airflow task logs.
    • Model-level with Cosmos and Snowflake-native dbt: the same 400 models as 400 Cosmos-generated tasks, up to 8 running in parallel on the MEDIUM warehouse, took 12 minutes (33% faster). The failed model, its compile error and the exact line were visible from the red task. Debugging took 8 minutes.

    The speed gain comes from running independent models in parallel; the debugging gain comes from per-model visibility.

    Which one to use

    Job-level still makes sense if your project is small (under 50 models), it fits in a single logical unit, you don’t need per-model visibility, or you’re on dbt Cloud’s own scheduler rather than Airflow.

    Model-level makes sense if you have 100+ models, need per-model failure isolation, care about debugging speed, or want Airflow to be the single source of truth for the whole pipeline.

    The hybrid: some teams run both in the same DAG: one job-level task for hourly incremental loads (dbt run --select tag:hourly) and a Cosmos task group for the daily mart builds where visibility matters.

    The principle I’d use to decide: observability at execution time beats simplicity at configuration time. Job-level is simpler to configure; model-level is simpler to debug. In production you spend more time debugging than configuring, so pick the granularity that lets you see failures where they happen.

    Step 6: Handle new versions of your dbt project

    I didn’t think about this until I pushed a breaking change to main and my 6 AM pipeline executed the wrong version.

    The DBT PROJECT object is versioned: each change made through ALTER adds a new version, named VERSION$<num>.

    In practice, your CI/CD pipeline (GitHub Actions or similar) should update the DBT PROJECT object after every merge to main:

    # .github/workflows/deploy_dbt.yml
    name: Deploy dbt Project to Snowflake
    
    on:
      push:
        branches: [main]
    
    jobs:
      deploy:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
    
          - name: Install Snowflake CLI
            run: pip install snowflake-cli-labs
    
          - name: Deploy new dbt project version
            env:
              SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT }}
              SNOWFLAKE_USER: ${{ secrets.SNOWFLAKE_USER }}
              SNOWFLAKE_PASSWORD: ${{ secrets.SNOWFLAKE_PASSWORD }}
            run: |
              snow dbt deploy \
                --project-name analytics_db.transforms.sales_dbt_project \
                --from-git \
                --ref main

    On every push to main, the workflow installs the Snowflake CLI and deploys a new version of the project, reading the account, user and password from GitHub secrets.

    In your Airflow SQL, VERSION = 'LAST' always picks up the most recently deployed version. Once CI/CD deploys a new version, the next DAG run uses it with no Airflow changes.

    Step 7: Monitoring (what to watch and where)

    Before this setup, I was watching three screens at once when something went wrong. Now it’s mostly one.

    In Snowsight:

    -- Check recent dbt project execution history
    SELECT
        query_id,
        query_text,
        execution_status,
        start_time,
        end_time,
        DATEDIFF('second', start_time, end_time) AS duration_seconds,
        error_message
    FROM TABLE(
        INFORMATION_SCHEMA.QUERY_HISTORY(
            END_TIME_RANGE_START => DATEADD('day', -1, CURRENT_TIMESTAMP()),
            RESULT_LIMIT => 50
        )
    )
    WHERE query_text ILIKE '%EXECUTE DBT PROJECT%'
    ORDER BY start_time DESC;

    This lists the last day’s EXECUTE DBT PROJECT statements with their status, duration in seconds and any error message, newest first.

    Row count drift detection, added as an Airflow task:

    -- Compare today's mart row count to yesterday's
    -- Flag if it drops more than 20%
    WITH today AS (
        SELECT COUNT(*) AS cnt
        FROM analytics_db.marts.fct_daily_orders
        WHERE order_date = CURRENT_DATE() - 1
    ),
    yesterday AS (
        SELECT COUNT(*) AS cnt
        FROM analytics_db.marts.fct_daily_orders
        WHERE order_date = CURRENT_DATE() - 2
    )
    SELECT
        today.cnt                                               AS today_rows,
        yesterday.cnt                                           AS yesterday_rows,
        ROUND((today.cnt - yesterday.cnt) / NULLIF(yesterday.cnt, 0) * 100, 2) AS pct_change,
        CASE
            WHEN today.cnt < yesterday.cnt * 0.80
            THEN 'ALERT: Row count dropped over 20%'
            ELSE 'OK'
        END AS status
    FROM today, yesterday;

    I added this query as a SQLExecuteQueryOperator task right after the mart validation step. If the row count drops by more than 20% compared with the previous day, the task raises a warning in the Airflow logs and the email alert fires.

    Not every data quality problem shows up as a dbt test failure. Sometimes the data just quietly shrinks because an upstream feed stopped delivering. This catches that.

    Gotchas I hit along the way

    1. EXECUTE DBT PROJECT is synchronous by default. Airflow waits for it to complete before marking the task done. For large projects that’s the behavior you want; just make sure the task’s execution_timeout is generous enough.

    2. Cross-project references don’t work the way you might expect. The DBT PROJECT object can’t reference external file paths, so cross-project dependencies have to be copied into the root of the main project. If you have multiple dbt projects, plan your consolidation before deploying.

    3. VERSION = 'LAST' always runs the most recently deployed version. To pin a specific version in production, use VERSION = 'VERSION$3' (or whichever number). I run LAST in dev and a pinned version in prod, deployed via CI/CD.

    4. Warehouse auto-resume and the first task. The first EXECUTE DBT PROJECT of the day can have a few seconds of latency while dbt_transform_wh resumes. I added a lightweight warm-up query as the very first task in my DAG, so the warehouse is already running when dbt build starts:

    warm_up_warehouse = SQLExecuteQueryOperator(
        task_id='warm_up_warehouse',
        conn_id=SNOWFLAKE_CONN,
        sql="SELECT CURRENT_TIMESTAMP();",
    )
    
    warm_up_warehouse >> check_raw_data >> run_dbt_project >> ...

    It costs almost nothing and removes 5 to 10 seconds of variability at the start of every run.

    5. dbt artifacts stay in Snowflake. When dbt runs inside Snowflake, manifest.json and the other run artifacts stay there too. If anything downstream uses them (dbt Cloud webhooks, dbt Mesh coordination, lineage tools), add a post-run task that exports them explicitly after each run.

    What this setup actually changed for me

    I want to be concrete here, because the “benefits” sections in most blog posts are too abstract.

    Before: my pipeline had six moving parts. An Airflow DAG on one server. dbt installed on a separate instance. A profiles.yml with credentials that needed updating every time we rotated passwords. Separate monitoring in CloudWatch for the dbt server. Debugging a failure meant SSH to the dbt server, find the log file, then cross-reference it with the Airflow logs.

    After: the pipeline has three moving parts: Airflow, Snowflake and GitHub. The dbt credentials are managed by Airflow’s Snowflake connection, which I was already maintaining. Debugging a failure means clicking into the Airflow task logs (which capture the SQL response from Snowflake) and, if I need more detail, running the QUERY_HISTORY query above in Snowsight.

    Performance has also improved since preview: result upload, which took roughly 6 to 6.5 minutes during preview, now completes in around 40 to 45 seconds, about 8 to 10x faster.

    The startup time improvement alone was worth it for me. My morning pipeline used to take 28 to 32 minutes. It now consistently runs in 18 to 22 minutes. That’s not from faster models; it’s from removing environment spin-up overhead.

    Why I think this is the right direction

    I started exploring this because nobody told me to. My team’s existing setup worked, and a reasonable person would have left it alone.

    But the more I looked at it, the more I thought about the overhead we carry when tools don’t talk to each other natively. Every boundary between systems is a place where credentials leak, latency is added and debugging gets harder. The native dbt project in Snowflake closes one of those boundaries. Airflow still owns orchestration, which is where it belongs, but the transformation runs where the data lives.

    One line I read about this stuck with me:

    For the growing number of organizations that have standardized on Snowflake, the native integration offers something genuinely compelling: one fewer system to run, one fewer vendor to manage, and one fewer boundary between your data and the logic that transforms it.

    That’s exactly what this is.

    If you’ve been running dbt Core on a server with Airflow alongside it, and you’ve tolerated the overhead for so long that you’ve stopped noticing it, try this weekend rebuild. You might be surprised how much lighter the pipeline feels on the other side.

    And if you try it and hit something weird, drop it in the comments. I’m still learning this myself.

    Related reading: dbt State on Snowflake: skip unchanged models, cut runtime 60% · dbt Fusion: 30x faster parsing with the Rust engine · Data contracts: stop schema breakage before it happens · Official dbt and Airflow integration guide

  • How I Taught Myself Snowflake Cortex Code (And What I Found)

    How I Taught Myself Snowflake Cortex Code (And What I Found)

    Nobody told me to do this.

    No manager pinged me. No sprint ticket had “explore Cortex Code” written on it. I stumbled across it one evening while clicking around Snowsight after a long day of debugging dbt models, and three hours later I looked up and realized I hadn’t thought about Jira or Slack once.

    That doesn’t happen to me.

    I run this blog because I genuinely love poking around the parts of Snowflake that most people scroll past. Cortex Code is exactly that kind of thing — it’s been sitting quietly inside Snowsight, doing something remarkable, and I feel like almost nobody in the data engineering world is talking about it properly. So let’s fix that.

    What Cortex Code Actually Is (And What It Is Not)

    Before I go any further, I want to be really clear about something that tripped me up when I first read the Snowflake docs — and that I’ve seen cause confusion in the community too.

    Cortex Code is not a SQL function you call.

    It is not SELECT SNOWFLAKE.CORTEX.CODE_ASSIST(...). It doesn’t live in your query editor the way CORTEX.COMPLETE() or CORTEX.SENTIMENT() do. I wasted about 45 minutes trying to invoke it via SQL the first time, so I’m saving you that pain right now.

    Cortex Code is a natural language interface built into Snowsight — Snowflake’s web UI. You access it by navigating to Snowsight, finding the Cortex Code section, uploading or referencing your files, and then literally just… talking to it in plain English. You describe what you want to do with your code or data files, and it responds. Think of it as having an AI pair programmer that lives inside your Snowflake environment, already understands your data context, and doesn’t need you to install anything.

    This distinction matters a lot for how you think about using it in production versus exploration.


    How to Actually Access Cortex Code in Snowsight

    Here’s the step-by-step, because the docs skip over some of this:

    Step 1: Log into Snowsight

    Go to your Snowflake account URL and log in. Make sure you’re on an account that has Cortex features enabled — Enterprise edition or higher, with the right region support.

    Step 2: Navigate to the Cortex Code Section

    In the left sidebar, look for the AI/ML or Cortex section. This UI location has shifted slightly across Snowflake releases, so if you don’t see it immediately, use the search bar at the top of Snowsight and type “Cortex.”

    Step 3: Upload Your Files Using a PUT Command

    This is where it gets interesting. If you want Cortex Code to analyze a specific file — say a Python script, a dbt model, a JSON file, or a CSV — you first upload it to a Snowflake stage using a PUT command in a worksheet:

    -- Create a stage if you don't have one
    CREATE OR REPLACE STAGE my_cortex_stage;
    
    -- Upload your file from your local machine
    PUT file:///Users/yourname/projects/my_dbt_model.sql @my_cortex_stage;
    
    -- Verify it landed
    LIST @my_cortex_stage;

    Step 4: Reference Your File in the Cortex Code Interface

    Once staged, you can reference the file in the Cortex Code interface and start asking questions about it in plain English.

    Step 5: Start Prompting

    You don’t write SQL. You write sentences. That’s the whole point.


    Real Example 1: Analyzing a dbt Model for Performance Issues

    This is the first thing I tried, and it immediately earned its keep.

    I had a dbt model — let’s call it fct_orders_daily.sql — that was consistently running for 14 minutes in production. I’d stared at it, I’d checked clustering, I’d looked at query profiles. I was going in circles.

    I uploaded the file:

    PUT file:///Users/bug/dbt_project/models/marts/fct_orders_daily.sql @my_cortex_stage;

    Then in Cortex Code I typed something like:

    “I’ve uploaded a dbt SQL model called fct_orders_daily.sql. It’s running for 14 minutes. Can you review the logic and tell me where the performance problems likely are? Suggest specific rewrites.”

    What came back wasn’t a generic “add a WHERE clause” response. It identified a specific pattern I had — a correlated subquery inside a CASE statement that was executing per-row. It rewrote the logic using a LEFT JOIN with a pre-aggregated CTE instead. The rewrite took the query from 14 minutes to under 3 minutes when I tested it.

    Did I feel a little embarrassed that an AI caught something I missed? Absolutely. Did I care? Not really. The model shipped.


    Real Example 2: Explaining Someone Else’s Legacy Code

    Every data engineer has that one Snowflake procedure. The one that nobody touches. The one with variable names like tmp_ctr2 and no comments anywhere. The one that was written by someone who left the company in 2021.

    I had one of those. It was a stored procedure managing some SCD2 logic on a customer dimension table. About 200 lines. No documentation.

    I staged the file:

    PUT file:///Users/bug/legacy/sp_customer_dim_scd2.sql @my_cortex_stage;

    Then in Cortex Code:

    “This is a Snowflake stored procedure. Can you explain what it does step by step, in plain English? Then flag any parts that look fragile or risky.”

    It produced a section-by-section breakdown that I turned directly into an internal wiki page. It also flagged that the procedure was doing a full table merge without any row count validation before and after — which, it noted, meant a failed intermediate step could silently produce a partial merge with no error thrown.

    That was a legitimate production risk I had never noticed. I added the validation. Nobody told me to. I just did it because now I knew.


    Real Example 3: Generating New Transformation Code from a Description

    This one genuinely surprised me. I described a transformation I needed in plain language — no file, just a description — and asked Cortex Code to write the SQL.

    My prompt was roughly:

    “I have a table called SALES_EVENTS with columns: event_id, customer_id, event_type (values: ‘purchase’, ‘return’, ‘browse’), event_timestamp, and amount. I want to build a daily summary table that shows, for each customer and each day: total purchases, total returns, net revenue (purchases minus returns), and a flag if they had any browse events that didn’t convert to a purchase on the same day. Write me the Snowflake SQL for this.”

    Here’s essentially what it produced (I’ve cleaned it up slightly for readability):

    WITH daily_events AS (
        SELECT
            customer_id,
            DATE(event_timestamp) AS event_date,
            SUM(CASE WHEN event_type = 'purchase' THEN amount ELSE 0 END) AS total_purchases,
            SUM(CASE WHEN event_type = 'return' THEN amount ELSE 0 END) AS total_returns,
            SUM(CASE WHEN event_type = 'purchase' THEN amount ELSE 0 END) -
            SUM(CASE WHEN event_type = 'return' THEN amount ELSE 0 END) AS net_revenue,
            MAX(CASE WHEN event_type = 'browse' THEN 1 ELSE 0 END) AS had_browse,
            MAX(CASE WHEN event_type = 'purchase' THEN 1 ELSE 0 END) AS had_purchase
        FROM SALES_EVENTS
        GROUP BY customer_id, DATE(event_timestamp)
    )
    
    SELECT
        customer_id,
        event_date,
        total_purchases,
        total_returns,
        net_revenue,
        CASE 
            WHEN had_browse = 1 AND had_purchase = 0 THEN TRUE 
            ELSE FALSE 
        END AS browse_no_convert_flag
    FROM daily_events
    ORDER BY customer_id, event_date;

    That’s clean, readable, and correct. It took maybe 30 seconds from my prompt to a working query. Normally I’d have spent 10-15 minutes writing and testing that from scratch.


    Real Example 4: Reviewing Python Scripts for Data Quality Issues

    I had a Python ingestion script that was pulling data from a REST API and writing to a Snowflake stage. I staged it:

    PUT file:///Users/bug/scripts/api_ingest.py @my_cortex_stage;

    My prompt: “Review this Python script. It ingests data from a REST API into a Snowflake stage. Are there any data quality risks, error handling gaps, or things that might fail silently in production?”

    The response flagged three things:

    • No retry logic on the API call, so a transient network failure would abort the entire run with no retry
    • The script was casting all numeric fields as strings before writing to the stage, which would cause downstream type errors in the COPY INTO command
    • There was no check on API response status codes — a 429 (rate limit) or 500 was being handled the same way as a 200

    All three were real issues. None of them were obvious from a quick read. Finding them manually would have required either running the thing and watching it fail, or very careful code review.


    Where Cortex Code Fits in Your Daily Workflow

    I want to be honest here: Cortex Code is not a replacement for knowing what you’re doing. If you give it a bad prompt, you’ll get a bad answer. If you blindly paste its output into production without reading it, eventually something will break and you’ll deserve it.

    But used as a thinking partner — as a way to get a first draft, spot what you might have missed, or understand something unfamiliar faster — it’s genuinely useful in a way that saves real time.

    Here’s how I’ve actually worked it into my day:

    Morning code review pass: Before I open a PR for anything significant, I stage the file and run a quick “what could go wrong with this?” prompt. It takes 2 minutes and has caught things twice in the last month.

    Legacy code archaeology: Any time I have to touch something old that I didn’t write, I stage it and ask for an explanation before I touch a single line. This alone is worth it.

    First-draft SQL: When I have a new transformation to build and I know exactly what the output should look like but I’m not in the mood to write boilerplate aggregations, I describe the output and let Cortex Code give me a starting point. I always read and edit what it gives me — but starting from something is faster than starting from nothing.

    Onboarding help: I’ve started pointing people who are new to the team at Cortex Code for understanding existing models. “Stage the file, ask it to explain it, then come ask me questions.” It makes onboarding conversations much more productive because they’ve already done some of the basic reading.


    What It Can’t Do (And Where You Still Need to Think)

    I don’t want this to sound like a Snowflake brochure. There are real limitations.

    It doesn’t know your data. It can reason about code logic and SQL patterns, but it doesn’t have context about what’s actually in your tables — so it can’t tell you whether a join is correct because it doesn’t know your actual cardinality or data distribution.

    Complex business logic still needs you. If your transformation encodes ten years of institutional knowledge about how a specific business process works, Cortex Code can write syntactically correct SQL but it can’t know if the business logic is right.

    You have to read the output. Every time. No exceptions.

    And the Snowsight UI for it, as of my exploration, is still evolving — some things feel a little rough around the edges. That’s fine. So did Cortex Analyst when it launched, and it’s much smoother now.


    A Few Prompting Tips That Actually Help

    After spending time with this, here’s what I’ve learned about getting better results:

    Be specific about what you want back. “Review this code” is okay. “Review this code and give me three specific things to change, written as SQL snippets I can copy” is much better.

    Tell it the context it’s missing. “This table has 2 billion rows and is clustered on event_date” is useful information that shapes the advice you’ll get.

    Ask follow-up questions. If the first answer is good but you want to go deeper on one part, just ask. The interface supports back-and-forth.

    Tell it what you’ve already tried. If you’ve already checked clustering and it didn’t help, say so. Otherwise it’ll suggest clustering.


    Why I Think This Matters

    I started this blog because I noticed that a lot of the Snowflake content online is either too shallow (“here’s what the feature is”) or too abstract (“here’s why AI in data warehouses matters”). What’s missing is the honest, practical, “here’s what I actually did and what happened” stuff.

    Cortex Code is one of those features that I think is genuinely going to change how data engineers do their day-to-day work — not in a science fiction way, but in the quiet, unglamorous way where you just realize one day that you’re spending three hours less per week on the boring parts and three hours more on the interesting parts.

    Nobody told me to learn this. I’m glad I did.

    If you try it, tell me how it goes. I’m genuinely curious whether your experience matches mine.