<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aarongmoore on Medium]]></title>
        <description><![CDATA[Stories by Aarongmoore on Medium]]></description>
        <link>https://medium.com/@aarongmoore_88179?source=rss-147e8fe551e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x200eBgijTwJmIA4</url>
            <title>Stories by Aarongmoore on Medium</title>
            <link>https://medium.com/@aarongmoore_88179?source=rss-147e8fe551e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 18:50:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aarongmoore_88179/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[#The Overlooked Superpower: Why Bash Scripting Is More Critical Than Ever for Data Engineers in the…]]></title>
            <link>https://medium.com/@aarongmoore_88179/the-overlooked-superpower-why-bash-scripting-is-more-critical-than-ever-for-data-engineers-in-the-fd53965ad6e2?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd53965ad6e2</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bash-script]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 01:42:20 GMT</pubDate>
            <atom:updated>2026-06-19T01:42:20.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>#The Overlooked Superpower: Why Bash Scripting Is More Critical Than Ever for Data Engineers in the Age of AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sunQJXpp6fohMbVgaedOlA.png" /></figure><p>For nearly a decade, industry conversations about data engineering have focused on SQL, Python, Spark, Snowflake, Databricks, dbt, cloud platforms, and more recently AI coding assistants. While these technologies deserve attention, one of the most valuable skills in a modern data engineer’s toolkit continues to be overlooked: Bash scripting.<br> <br> Many engineers view Bash as an old technology that belongs to system administrators. In reality, Bash remains one of the foundational skills that separates engineers who can build individual data pipelines from engineers who can operate entire data platforms. As organizations adopt AI coding assistants such as Claude Code, Cursor, GitHub Copilot, and Snowflake Cortex Code, Bash has become even more important, not less.<br> <br> The reason is simple: AI can generate code, but data engineers remain responsible for operating, automating, securing, troubleshooting, and integrating production systems. Bash sits directly at the intersection of those responsibilities.<br> <br> Why Bash Still Matters<br> <br> Most data engineering work does not happen inside SQL queries or Python notebooks. Production environments require engineers to move files, deploy code, monitor jobs, manage cloud resources, troubleshoot failures, orchestrate workflows, automate operational tasks, and integrate disparate systems. Bash excels at these activities because it provides direct access to the operating system and the tools that run modern infrastructure.<br> <br> Virtually every cloud environment, Linux server, Kubernetes container, CI/CD runner, and data platform uses shell commands behind the scenes. Even highly managed platforms rely on shell-based automation somewhere within their operational stack.<br> <br> The Hidden Reality of Modern Data Engineering<br> <br> A modern data platform might include Snowflake, Databricks, Airflow, dbt, GitHub Actions, Docker, Terraform, AWS, Azure, and AI-assisted development tools. Each platform has its own interface, but the automation layer connecting them is frequently implemented using Bash.<br> <br> When a deployment pipeline runs, Bash commands execute.<br> When cloud resources are provisioned, Bash commands execute.<br> When containers start, Bash commands execute.<br> When orchestration tools invoke external processes, Bash commands execute.<br> <br> Understanding Bash allows data engineers to understand what is actually happening underneath the abstraction layers.<br> <br> Why AI Makes Bash More Important<br> <br> A common misconception is that AI coding assistants reduce the need for technical depth. The opposite is true.<br> <br> AI can generate a Bash script that deletes files, copies data, provisions cloud infrastructure, or modifies production resources. However, AI cannot assume accountability for those actions. The engineer must understand the generated code before it runs.<br> <br> Organizations increasingly need engineers who can evaluate AI-generated automation and determine whether it is safe, efficient, and aligned with operational requirements.<br> <br> Engineers who understand Bash can:<br> • Validate AI-generated scripts.<br> • Troubleshoot failures when automation breaks.<br> • Improve generated code.<br> • Secure credentials and permissions.<br> • Identify dangerous commands before execution.<br> • Understand infrastructure-level behavior.<br> <br> As AI accelerates development, understanding the underlying execution layer becomes a competitive advantage.<br> <br> Practical Example: Automating Snowflake Loads<br> <br> #!/bin/bash<br> <br> snowsql -a company_account -u data_engineer -d analytics -s public -q “COPY INTO sales<br> FROM @sales_stage<br> FILE_FORMAT=(TYPE=CSV);”<br> <br> This script can be scheduled through cron, Airflow, GitHub Actions, or enterprise schedulers. While AI can generate the command, the engineer must understand authentication, stages, file formats, permissions, and error handling.<br> <br> Practical Example: Coordinating an End-to-End Pipeline<br> <br> #!/bin/bash<br> <br> echo “Starting ETL Pipeline”<br> <br> python extract.py<br> <br> if [ $? -ne 0 ]; then<br> echo “Extract Failed”<br> exit 1<br> fi<br> <br> python transform.py<br> <br> if [ $? -ne 0 ]; then<br> echo “Transform Failed”<br> exit 1<br> fi<br> <br> python load.py<br> <br> echo “Pipeline Complete”<br> <br> This pattern remains extremely common. Bash provides lightweight orchestration without requiring a complex orchestration framework.<br> <br> Operational Excellence and Production Support<br> <br> The best data engineers spend significant time supporting production workloads. During outages, dashboards fail, ingestion jobs stop, APIs become unavailable, and files arrive late.<br> <br> Bash becomes one of the fastest troubleshooting tools available.<br> <br> Example:<br> <br> grep ERROR *.log | tail -20<br> <br> Within seconds an engineer can identify the source of a failure. During a production incident, speed matters far more than elegant code.<br> <br> Cloud Operations<br> <br> Data engineers increasingly own cloud infrastructure alongside data pipelines. Bash integrates naturally with cloud command-line tools.<br> <br> AWS Example:<br> <br> aws s3 sync s3://landing-zone s3://raw-zone<br> <br> Azure Example:<br> <br> az storage blob upload-batch — source ./files — destination raw<br> <br> These simple commands often replace hundreds of lines of custom application code.<br> <br> CI/CD and DataOps<br> <br> Modern DataOps practices depend heavily on automation. Most deployment systems ultimately execute shell commands.<br> <br> Example:<br> <br> #!/bin/bash<br> <br> git pull origin main<br> dbt deps<br> dbt build<br> <br> This simple script can become the foundation of a repeatable deployment process.<br> <br> Bash and Containers<br> <br> Containers have become standard in modern data engineering. Docker images frequently use Bash as their startup mechanism.<br> <br> #!/bin/bash<br> <br> python pipeline.py<br> <br> The engineer who understands Bash understands how containers actually execute workloads.<br> <br> The Business Value of Bash<br> <br> From a business perspective, Bash delivers three significant benefits:<br> <br> First, it reduces operational overhead by automating repetitive tasks.<br> <br> Second, it improves reliability by creating repeatable processes.<br> <br> Third, it accelerates issue resolution during production incidents.<br> <br> Organizations increasingly seek engineers who can own systems end-to-end rather than simply develop transformations.<br> <br> The Career Advantage<br> <br> Nearly every data engineer learns SQL.<br> <br> Many learn Python.<br> <br> Far fewer develop strong Linux, automation, and operational engineering skills.<br> <br> That gap creates opportunity.<br> <br> Engineers with Bash expertise often become the people trusted to solve production issues, automate deployments, integrate platforms, and support mission-critical systems. Those responsibilities frequently lead to architecture, platform engineering, and technical leadership opportunities.<br> <br> Conclusion<br> <br> Bash scripting is not a legacy skill. It is a foundational skill that enables modern data engineering. As cloud platforms, AI assistants, and increasingly complex ecosystems continue to evolve, the engineers who understand the underlying automation layer become more valuable, not less valuable.<br> <br> AI can generate scripts, but it cannot replace operational understanding. Data engineers must still understand how systems interact, how workloads execute, how failures occur, and how automation should be managed. Bash provides that visibility.<br> <br> The future of data engineering will absolutely include AI-assisted development. However, the most successful engineers will combine AI acceleration with deep operational knowledge. Bash scripting remains one of the most practical and effective ways to build that expertise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd53965ad6e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Data Engineering in the Age of AI Agents]]></title>
            <link>https://medium.com/@aarongmoore_88179/data-engineering-in-the-age-of-ai-agents-94371dc6ff94?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/94371dc6ff94</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[dataengineering-future]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 19:16:24 GMT</pubDate>
            <atom:updated>2026-06-12T19:16:24.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJ2gAR_MioZ8X3Qv3Zpdqw.png" /></figure><p>Building Real Systems with Snowflake Cortex Code, Claude Code, and Cursor<br> Beyond Vibe Coding and Toward Measurable Business Outcomes</p><p><strong>Introduction</strong></p><p>Artificial Intelligence is transforming software development at a pace rarely seen in enterprise technology. For data engineers, the arrival of AI-powered coding assistants such as Snowflake Cortex Code, Claude Code, and Cursor has introduced new opportunities to accelerate development, improve quality, and deliver business value faster than ever before.<br> <br> Yet many organizations are approaching these technologies incorrectly. They view AI primarily as a code-generation tool. While generating SQL and Python is valuable, focusing solely on code misses the larger opportunity. The real transformation lies in the rise of AI agents — systems capable of assisting across the entire software development lifecycle.<br> <br> This article explores how modern data engineers can move beyond simple code generation and leverage AI agents to build scalable, governed, production-ready data platforms.</p><p><strong>The Difference Between Building and Vibe Coding</strong></p><p>Vibe coding has become a popular phrase describing a workflow where developers repeatedly prompt AI systems, accept generated code with limited understanding, and rely on additional prompts whenever issues arise.<br> <br> Building is fundamentally different.<br> <br> Builders define architecture, understand requirements, establish governance standards, design testing frameworks, and take ownership of outcomes. AI becomes an accelerator rather than a replacement for engineering judgment.<br> <br> The key question is simple: Can you explain why the generated code works? If not, it does not belong in production.<br> <br> Enterprise data engineering demands reliability, security, observability, and compliance. AI can accelerate implementation, but engineering accountability remains a human responsibility.</p><p><strong>The Evolution from Assistants to Agents</strong></p><p>Most organizations began their AI journey with coding assistants.<br> <br> An engineer requests SQL, Python, or documentation, and the tool responds with generated content.<br> <br> Agentic systems represent the next stage of evolution.<br> <br> Agents can:<br> • Analyze requirements<br> • Explore repositories<br> • Design implementation plans<br> • Generate code<br> • Execute tests<br> • Interpret results<br> • Produce documentation<br> • Recommend improvements<br> <br> The difference is profound.<br> <br> Assistants help developers write code.<br> <br> Agents help engineering teams deliver outcomes.<br> <br> For data engineering organizations, this distinction matters because coding is only a portion of the overall delivery effort. Significant time is spent on analysis, testing, governance, documentation, and operational readiness.</p><p><strong>Snowflake Cortex Code for Data Engineering</strong></p><p>Snowflake Cortex Code brings AI-powered development directly into the Snowflake ecosystem.<br> <br> Data engineers can generate:<br> • SQL transformations<br> • Snowpark code<br> • Stored procedures<br> • Data quality validations<br> • Documentation<br> • Optimization recommendations<br> <br> Rather than starting with a blank page, engineers can focus on refining business logic and architecture while Cortex Code accelerates implementation.<br> <br> The greatest value emerges when engineers combine Cortex Code with strong engineering standards and governance processes.</p><p><strong>Claude Code and Repository-Scale Engineering</strong></p><p>Claude Code extends beyond individual code snippets by understanding broader project context.<br> <br> For data engineering teams, Claude Code is particularly effective for:<br> • Framework development<br> • Repository analysis<br> • Legacy modernization<br> • Documentation generation<br> • Migration projects<br> • Test creation<br> <br> A migration from Informatica to Snowflake, for example, may involve hundreds of mappings and transformations. Claude Code can analyze patterns, identify opportunities for consolidation, and generate migration artifacts that significantly reduce implementation effort.</p><p><strong>Cursor and AI-Native Development</strong></p><p>Cursor integrates AI directly into the development experience.<br> <br> Data engineers can use Cursor to:<br> • Generate Python modules<br> • Refactor codebases<br> • Build dbt projects<br> • Create Infrastructure-as-Code templates<br> • Generate tests<br> • Document repositories<br> <br> Rather than functioning as an isolated chatbot, Cursor becomes part of the engineering workflow, helping developers remain focused while reducing repetitive tasks.</p><p><strong>Agentic Data Engineering on Snowflake</strong></p><p>The future of Snowflake development is likely to involve multiple specialized agents working together.<br> <br> Imagine a Customer 360 initiative integrating Salesforce, SAP, and eCommerce platforms.<br> <br> An Architecture Agent could design schemas and recommend data models.<br> <br> A Data Engineering Agent could create ingestion pipelines and transformations.<br> <br> A Governance Agent could recommend masking policies and access controls.<br> <br> A Testing Agent could generate validation rules and reconciliation checks.<br> <br> A Documentation Agent could produce operational runbooks and lineage descriptions.<br> <br> The engineer remains accountable but spends significantly less time on repetitive implementation activities.</p><p><strong>Business Value of AI Agents</strong></p><p>Executives do not invest in AI because they want more code. They invest because they want measurable business outcomes.<br> <br> Agent-assisted engineering can deliver value through:<br> <br> Increased Delivery Velocity<br> Projects that once required months may be delivered in weeks.<br> <br> Lower Development Costs<br> Automation reduces repetitive engineering effort.<br> <br> Higher Quality<br> Agents generate tests, documentation, and validation checks continuously.<br> <br> Improved Knowledge Retention<br> Architectural decisions and implementation details become documented organizational assets.<br> <br> Better Utilization of Engineering Talent<br> Senior engineers spend more time on architecture and innovation instead of boilerplate implementation.<br> <br> The cumulative impact can dramatically improve the economics of software delivery.</p><p><strong>Practical Example: Customer 360 Platform</strong></p><p>Consider a retailer building a Customer 360 platform on Snowflake.<br> <br> Traditional Approach:<br> • Multiple engineering teams<br> • Months of development effort<br> • Significant manual documentation<br> • Extensive testing cycles<br> <br> Agent-Assisted Approach:<br> <br> Claude Code:<br> • Designs reusable frameworks<br> • Creates implementation plans<br> <br> Cursor:<br> • Accelerates coding<br> • Generates tests<br> • Refactors code<br> <br> Snowflake Cortex Code:<br> • Produces optimized SQL<br> • Generates Snowpark transformations<br> • Assists with performance tuning<br> <br> Business Outcomes:<br> • Faster deployment<br> • Lower implementation costs<br> • Improved data quality<br> • Faster access to customer insights<br> <br> The value is not merely faster coding. The value is faster realization of business objectives.</p><p><strong>Testing, Governance, and Security</strong></p><p>One of the greatest misconceptions surrounding AI-generated code is that automation reduces the need for governance.<br> <br> The opposite is true.<br> <br> Organizations should implement:<br> • Automated testing<br> • Data quality monitoring<br> • Security reviews<br> • Access controls<br> • Data classification<br> • Audit logging<br> • Observability frameworks<br> <br> The combination of AI acceleration and strong governance creates sustainable long-term success.</p><p><strong>The Future Data Engineer</strong></p><p>The next generation of data engineers will increasingly function as architects, reviewers, and orchestrators of agentic systems.<br> <br> Their responsibilities will include:<br> • Defining requirements<br> • Designing architectures<br> • Governing data<br> • Reviewing AI-generated outputs<br> • Optimizing performance<br> • Ensuring compliance<br> • Aligning technical solutions with business goals<br> <br> The most valuable engineers will not necessarily be those who write the most code. They will be those who effectively direct AI systems to produce reliable business outcomes.</p><p><strong>Conclusion</strong></p><p>The industry is rapidly moving beyond AI coding assistants toward AI agents capable of contributing across the entire engineering lifecycle.<br> <br> Snowflake Cortex Code, Claude Code, and Cursor represent important steps in this evolution.<br> <br> Organizations that embrace agentic engineering will gain advantages in delivery speed, quality, knowledge retention, and operational efficiency. However, success will depend on maintaining strong engineering discipline and avoiding the temptation of blind automation.<br> <br> The future belongs to builders — not vibe coders.<br> <br> AI agents are not replacing data engineers. They are enabling great engineers to accomplish more than ever before. Those who learn to effectively orchestrate these tools will define the next era of data engineering excellence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94371dc6ff94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Python as the Universal Language of Modern Data Engineering: Snowflake, Databricks, andEverything…]]></title>
            <link>https://medium.com/@aarongmoore_88179/python-as-the-universal-language-of-modern-data-engineering-snowflake-databricks-andeverything-70566ec62a2b?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/70566ec62a2b</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-engineering-101]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 17:01:21 GMT</pubDate>
            <atom:updated>2026-06-07T17:01:21.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>#Python as the Universal Language of Modern Data Engineering: Snowflake, Databricks, andEverything In Between</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*YTyyE0IEX1FmbSFc3DLcvg.avif" /></figure><h3>Introduction</h3><p>If SQL is the language of data, Python has become the language of data engineering.</p><p>Modern data engineers rarely spend their entire day writing transformations. Instead, they’re building ingestion frameworks, orchestrating pipelines, managing metadata, validating data quality, integrating APIs, and automating platform operations.</p><p>Whether your organization runs primarily on Snowflake, Databricks, or a combination of both, Python has become the connective tissue that ties the entire ecosystem together.</p><p>While SQL remains the best tool for analytical transformations, Python has evolved into the language engineers use to build the systems that move, validate, govern, and operationalize data.</p><p>Let’s look at how Python is being used across modern data engineering platforms.</p><h3>Python and Snowflake: Beyond SQL</h3><p>Many teams still think of Snowflake as a SQL warehouse. In reality, modern Snowflake environments often contain substantial amounts of Python.</p><p>The introduction of Snowpark fundamentally changed how engineers develop on Snowflake.</p><p>Instead of pulling data out of Snowflake for processing, engineers can execute Python code directly inside Snowflake’s compute engine.</p><h3>Reading and Transforming Data with Snowpark</h3><p><strong>from</strong> snowflake.snowpark <strong>import</strong> Session<br><strong>from</strong> snowflake.snowpark.functions <strong>import</strong> col</p><p>session = Session.builder.configs(connection_parameters).create()</p><p>customers = session.table(“RAW.CRM.CUSTOMERS”)</p><p>active_customers = (<br> customers<br> .filter(col(“STATUS”) == “ACTIVE”)<br> .select(<br> “CUSTOMER_ID”,<br> “EMAIL”,<br> “CREATED_DATE”<br> )<br>)</p><p>active_customers.show()</p><p>Although this looks like Pandas, Snowpark generates optimized SQL that executes entirely within Snowflake.</p><p>No data movement.</p><p>No local processing.</p><p>Just Python-generated execution plans.</p><h3>Loading Data into Snowflake</h3><p>One of the most common Data Engineering tasks is API ingestion.</p><p>Consider loading data from a SaaS platform.</p><p><strong>import</strong> requests<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>from</strong> snowflake.connector <strong>import</strong> connect<br><strong>from</strong> snowflake.connector.pandas_tools <strong>import</strong> write_pandas</p><p>response = requests.get(<br> “https://api.company.com/customers&quot;<br>)</p><p>customers = pd.DataFrame(response.json())</p><p>conn = connect(<br> user=”engineer”,<br> password=”***”,<br> account=”company”<br>)</p><p>success, chunks, rows, output = write_pandas(<br> conn,<br> customers,<br> “CUSTOMERS_STAGE”<br>)</p><p>print(f”Loaded {rows} rows”)</p><p>This pattern remains extremely common:</p><p>API<br> ↓<br>Python<br> ↓<br>Snowflake Landing Table<br> ↓<br>dbt / Snowpark<br> ↓<br>Curated Models</p><h3>Calling Snowflake Stored Procedures from Python</h3><p>Many organizations use Python to automate operational tasks.</p><p>session.sql(“””<br>CALL REFRESH_CUSTOMER_DIMENSION()<br>“””).collect()</p><p>session.sql(“””<br>CALL VALIDATE_DAILY_LOAD()<br>“””).collect()</p><p>This approach is frequently used inside orchestration frameworks such as Airflow, Dagster, or Prefect.</p><h3>Building Data Quality Checks</h3><p>Data quality frameworks are often built using Python.</p><p>customer_count = (<br> session.table(“PROD.CUSTOMERS”)<br> .count()<br>)</p><p><strong>if</strong> customer_count &lt; 100000:<br> <strong>raise</strong> Exception(<br> “Customer count below expected threshold”<br> )</p><p>A more sophisticated example:</p><p><strong>from</strong> snowflake.snowpark.functions <strong>import</strong> count</p><p>duplicates = (<br> session.table(“PROD.CUSTOMERS”)<br> .group_by(“CUSTOMER_ID”)<br> .agg(count(“*”).alias(“CNT”))<br> .filter(col(“CNT”) &gt; 1)<br>)</p><p><strong>if</strong> duplicates.count() &gt; 0:<br> <strong>raise</strong> Exception(<br> “Duplicate customer records detected”<br> )</p><p>These types of validations are increasingly embedded directly into CI/CD deployment pipelines.</p><h3>Python and Databricks: The Native Engineering Language</h3><p>If Python complements Snowflake, it is the dominant engineering language inside Databricks.</p><p>Virtually every major capability in Databricks supports Python natively.</p><p>For many engineers, Databricks notebooks serve as both development environment and execution engine.</p><h3>Reading Data with PySpark</h3><p>A typical ingestion process begins by loading raw files.</p><p>orders_df = (<br> spark.read<br> .format(“json”)<br> .load(<br> “/mnt/raw/orders/”<br> )<br>)</p><p>orders_df.printSchema()</p><p>This may represent gigabytes or terabytes of data.</p><p>PySpark abstracts away the distributed processing complexity.</p><h3>Transforming Data at Scale</h3><p><strong>from</strong> pyspark.sql.functions <strong>import</strong> *</p><p>daily_sales = (<br> orders_df<br> .groupBy(“order_date”)<br> .agg(<br> sum(“amount”).alias(“sales”),<br> count(“*”).alias(“order_count”)<br> )<br>)</p><p>display(daily_sales)</p><p>The same code could execute across hundreds of worker nodes.</p><p>The engineer writes business logic.</p><p>Spark handles parallelization.</p><h3>Delta Lake Processing</h3><p>One of the most common engineering tasks in Databricks is writing Delta tables.</p><p>(<br> daily_sales<br> .write<br> .format(“delta”)<br> .mode(“overwrite”)<br> .saveAsTable(<br> “silver.daily_sales”<br> )<br>)</p><p>This simple operation automatically provides:</p><ul><li>ACID transactions</li><li>Schema enforcement</li><li>Time travel</li><li>Version history</li></ul><h3>CDC Processing with MERGE</h3><p>Many production pipelines rely on Delta Lake merge operations.</p><p>deltaTable.alias(“target”).merge(<br> updates.alias(“source”),<br> “target.customer_id = source.customer_id”<br>).whenMatchedUpdateAll(<br>).whenNotMatchedInsertAll(<br>).execute()</p><p>This pattern is foundational for building Silver and Gold layers within a Lakehouse architecture.</p><h3>Auto Loader for Streaming Ingestion</h3><p>One of the most powerful Databricks features is Auto Loader.</p><p>stream_df = (<br> spark.readStream<br> .format(“cloudFiles”)<br> .option(<br> “cloudFiles.format”,<br> “json”<br> )<br> .load(<br> “/mnt/inbound/orders”<br> )<br>)</p><p>Writing the stream:</p><p>(<br> stream_df.writeStream<br> .format(“delta”)<br> .option(<br> “checkpointLocation”,<br> “/checkpoints/orders”<br> )<br> .table(“bronze.orders”)<br>)</p><p>This allows engineers to process continuously arriving files with minimal code.</p><h3>Python as the Bridge Between Snowflake and Databricks</h3><p>An increasingly common architecture uses Databricks and Snowflake together.</p><p>Databricks handles large-scale ingestion and processing.</p><p>Snowflake serves curated analytical data products.</p><p>Python becomes the integration layer.</p><h3>Example: Moving Curated Data to Snowflake</h3><p>curated_df = spark.table(<br> “gold.customer_metrics”<br>)</p><p>pandas_df = curated_df.toPandas()</p><p>write_pandas(<br> snowflake_conn,<br> pandas_df,<br> “CUSTOMER_METRICS”<br>)</p><p>For larger datasets, organizations typically use cloud storage as an intermediary.</p><p>Databricks<br> ↓<br>Parquet Files<br> ↓<br>S3 / ADLS<br> ↓<br>Snowpipe<br> ↓<br>Snowflake</p><p>Python often orchestrates every step in this workflow.</p><h3>Production Engineering: Where Python Really Shines</h3><p>The biggest misconception about Data Engineering is that it primarily involves data transformation.</p><p>In reality, mature data organizations spend significant effort building engineering platforms.</p><p>A typical orchestration workflow might look like:</p><p>@dag(<br> schedule=”@daily”<br>)<br><strong>def</strong> customer_pipeline():</p><p>ingest_api_data()</p><p>validate_raw_data()</p><p>run_dbt_models()</p><p>execute_snowflake_tests()</p><p>notify_slack()</p><p>customer_pipeline()</p><p>Using Airflow, Dagster, or Prefect, Python becomes the operational language that coordinates every stage of the data lifecycle.</p><p>The SQL transforms the data.</p><p>Python runs the platform.</p><h3>Final Thoughts</h3><p>Modern data engineering is no longer about choosing SQL or Python.</p><p>The highest-performing teams embrace both.</p><p>SQL remains unmatched for expressing transformations close to the data.</p><p>Python provides the engineering capabilities required to build reliable platforms around those transformations.</p><p>In Snowflake, Python powers Snowpark, automation, testing, and ingestion frameworks.</p><p>In Databricks, Python drives Spark processing, Delta Lake operations, streaming workloads, and machine learning integration.</p><p>As organizations increasingly adopt both platforms, Python has become the universal language that connects them.</p><p>The most effective data engineers today are not merely SQL developers. They are software engineers who happen to specialize in data — and Python is the language that enables them to operate across the entire modern data stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70566ec62a2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Getting the Best Out of Both Snowflake and Databricks: A Data Engineer’s Guide to Building a…]]></title>
            <link>https://medium.com/@aarongmoore_88179/getting-the-best-out-of-both-snowflake-and-databricks-a-data-engineers-guide-to-building-a-809789a64294?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/809789a64294</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 01:01:12 GMT</pubDate>
            <atom:updated>2026-06-03T01:01:12.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>#Getting the Best Out of Both Snowflake and Databricks: A Data Engineer’s Guide to Building a Modern Data Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Usx9ISUpfxdSPfZ8XnMwfA.png" /><figcaption>Can’t we all get Along?</figcaption></figure><p>Why the Future of Data Engineering Is Not Snowflake <em>or</em> Databricks — It’s Snowflake <em>and</em> Databricks</p><p>For nearly a decade, data platform discussions have been dominated by a seemingly simple question:</p><p><strong>“Should we choose Snowflake or Databricks?”</strong></p><p>It is a question that appears in architecture review meetings, technology evaluations, executive strategy sessions, and countless online forums.</p><p>The assumption behind the question is understandable. Both platforms are leaders in cloud data management. Both support data engineering workloads. Both offer SQL interfaces. Both provide governance capabilities. Both support AI and machine learning initiatives. Both claim to be central components of a modern data platform.</p><p>Yet organizations that have spent years operating large-scale analytics environments are increasingly arriving at the same conclusion:</p><p><strong>The most effective enterprise data platforms often use both.</strong></p><p>Rather than viewing Snowflake and Databricks as competitors fighting for ownership of the same problem, modern data engineering teams are recognizing that each platform solves different parts of the broader data lifecycle exceptionally well.</p><p>Databricks brings unparalleled flexibility for large-scale processing, machine learning, AI development, and lakehouse architectures.</p><p>Snowflake provides world-class analytics, governance, data sharing, and business intelligence capabilities.</p><p>When integrated properly, they form a platform that is often more powerful, more scalable, and more future-proof than either solution operating independently.</p><p>This article explores:</p><ul><li>The evolution of modern data architecture</li><li>Where Snowflake excels</li><li>Where Databricks excels</li><li>Why enterprises increasingly deploy both</li><li>Real-world integration patterns</li><li>Medallion architecture implementation</li><li>Delta Lake and Iceberg considerations</li><li>AI and LLM workloads</li><li>Cost optimization strategies</li><li>Governance approaches</li><li>A Customer 360 case study</li><li>Recommendations for data engineering teams</li></ul><p>Whether you are designing a greenfield platform or modernizing an existing analytics environment, understanding how these technologies complement each other can significantly influence your long-term success.</p><p>The Evolution of the Modern Data Platform</p><p>To appreciate why Snowflake and Databricks work so well together, we need to understand how data platforms evolved.</p><p>The Data Warehouse Era</p><p>For many years, enterprise architecture followed a predictable pattern.</p><p>Operational systems generated data:</p><ul><li>CRM systems</li><li>ERP platforms</li><li>Marketing tools</li><li>Transactional databases</li></ul><p>ETL processes loaded data into a centralized warehouse.</p><p>Analytics occurred exclusively inside that warehouse.</p><p>Life was relatively simple.</p><p>Data volumes were smaller.</p><p>Processing requirements were predictable.</p><p>Most analytics involved reporting and dashboards.</p><p>The Big Data Era</p><p>As organizations digitized operations, data volumes exploded.</p><p>New data sources emerged:</p><ul><li>Web clickstreams</li><li>Mobile applications</li><li>IoT devices</li><li>Social platforms</li><li>Event streams</li></ul><p>Traditional warehouses struggled with:</p><ul><li>Scale</li><li>Cost</li><li>Flexibility</li></ul><p>Organizations began building data lakes to store large volumes of raw data.</p><p>While data lakes solved storage problems, they introduced new challenges:</p><ul><li>Poor governance</li><li>Schema inconsistencies</li><li>Data quality issues</li><li>Difficult analytics</li></ul><p>Many data lakes became what practitioners jokingly referred to as “data swamps.”</p><p>The Cloud-Native Era</p><p>Cloud computing fundamentally changed the economics of data platforms.</p><p>Storage became inexpensive.</p><p>Compute became elastic.</p><p>Infrastructure management became less burdensome.</p><p>This shift created opportunities for new architectures.</p><p>Snowflake emerged as a cloud-native warehouse.</p><p>Databricks emerged as a cloud-native analytics and engineering platform built on Apache Spark.</p><p>Initially they addressed different needs.</p><p>Over time their capabilities expanded and began to overlap.</p><p>Yet their foundational strengths remained distinct.</p><p>Snowflake: The Enterprise Analytics Powerhouse</p><p>Snowflake’s architecture was designed around a core objective:</p><p><strong>Make analytics easy, scalable, and governable.</strong></p><p>Separation of Storage and Compute</p><p>One of Snowflake’s most significant innovations was separating storage from compute.</p><p>Benefits include:</p><ul><li>Independent scaling</li><li>Improved concurrency</li><li>Cost control</li><li>Simplified administration</li></ul><p>Multiple virtual warehouses can query the same data simultaneously without interfering with one another.</p><p>For enterprises supporting hundreds or thousands of users, this architecture is transformative.</p><p>Business Intelligence Excellence</p><p>Snowflake is exceptionally good at serving data to analytical consumers.</p><p>Common workloads include:</p><ul><li>Executive dashboards</li><li>Financial reporting</li><li>Operational analytics</li><li>Ad hoc exploration</li><li>KPI monitoring</li></ul><p>Business users often care less about Spark clusters or distributed compute frameworks and more about reliable access to trusted data.</p><p>Snowflake excels in this area.</p><p>Enterprise Governance</p><p>Governance is frequently underestimated during architecture planning.</p><p>Organizations often focus on ingestion and transformation while overlooking questions such as:</p><ul><li>Who owns the data?</li><li>Who can access it?</li><li>How is sensitive information protected?</li><li>How do we demonstrate compliance?</li></ul><p>Snowflake offers mature capabilities including:</p><ul><li>Role-based access control</li><li>Dynamic masking</li><li>Row-level security</li><li>Data classification</li><li>Secure sharing</li></ul><p>These features are especially valuable in regulated industries.</p><p>Data Sharing as a Competitive Advantage</p><p>Historically, sharing data between organizations required:</p><ul><li>Extracts</li><li>File transfers</li><li>Replication</li><li>Manual coordination</li></ul><p>Snowflake fundamentally changed this process.</p><p>Organizations can securely share data without physically moving it.</p><p>This capability has enabled entirely new business models around data monetization and collaboration.</p><p>Databricks: The Data Engineering and AI Workhorse</p><p>If Snowflake is optimized for enterprise consumption, Databricks is optimized for data creation, transformation, and intelligence.</p><p>Its origins in Apache Spark are critical to understanding its strengths.</p><p>Why Spark Still Matters</p><p>Despite constant innovation in data platforms, large-scale distributed processing remains essential.</p><p>Many data engineering workloads involve:</p><ul><li>Hundreds of millions of records</li><li>Complex joins</li><li>Streaming ingestion</li><li>Feature engineering</li><li>Advanced transformations</li></ul><p>Spark was designed specifically for these scenarios.</p><p>Databricks simplifies operating Spark at enterprise scale.</p><p>The Rise of the Lakehouse</p><p>Databricks popularized the concept of the Lakehouse.</p><p>The idea was straightforward:</p><p>Combine the flexibility of a data lake with the reliability of a warehouse.</p><p>The result is a platform capable of supporting:</p><ul><li>Data engineering</li><li>Analytics</li><li>Machine learning</li><li>AI workloads</li></ul><p>from a shared foundation.</p><p>Delta Lake and Transactional Data Lakes</p><p>One of Databricks’ most important contributions is Delta Lake.</p><p>Delta Lake introduced warehouse-like capabilities into data lakes:</p><ul><li>ACID transactions</li><li>Schema enforcement</li><li>Time travel</li><li>Data versioning</li><li>Reliable updates</li></ul><p>This transformed cloud object storage into a viable platform for enterprise analytics.</p><p>Machine Learning and AI</p><p>This is where Databricks often distinguishes itself most clearly.</p><p>A typical machine learning workflow involves:</p><ol><li>Data preparation</li><li>Feature engineering</li><li>Experimentation</li><li>Model training</li><li>Model validation</li><li>Deployment</li><li>Monitoring</li></ol><p>Databricks supports the entire lifecycle.</p><p>As organizations increasingly invest in AI initiatives, this capability becomes more important.</p><p>Understanding the Modern Division of Responsibilities</p><p>The most successful enterprise architectures often divide responsibilities.</p><p>Instead of forcing one platform to do everything, they allow each platform to specialize.</p><p>A common model looks like this:</p><p>Databricks Handles</p><ul><li>Raw ingestion</li><li>Data engineering</li><li>Streaming pipelines</li><li>Feature engineering</li><li>Machine learning</li><li>AI experimentation</li></ul><p>Snowflake Handles</p><ul><li>Data consumption</li><li>Business analytics</li><li>Governance</li><li>Secure sharing</li><li>Reporting</li><li>Self-service analytics</li></ul><p>This division minimizes friction while maximizing strengths.</p><p>The Medallion Architecture Approach</p><p>One of the most effective ways to organize a Snowflake-Databricks ecosystem is through a Medallion Architecture.</p><p>Bronze Layer</p><p>The Bronze layer stores raw data.</p><p>Characteristics include:</p><ul><li>Minimal transformation</li><li>Full historical retention</li><li>Schema preservation</li></ul><p>Examples:</p><ul><li>CRM extracts</li><li>Application logs</li><li>Kafka events</li><li>Third-party feeds</li></ul><p>Databricks is often responsible for ingesting and maintaining this layer.</p><p>Silver Layer</p><p>The Silver layer represents cleansed and standardized data.</p><p>Common operations include:</p><ul><li>Deduplication</li><li>Validation</li><li>Data quality checks</li><li>Standardization</li></ul><p>This is often where data engineering teams spend most of their effort.</p><p>Gold Layer</p><p>The Gold layer contains business-ready datasets.</p><p>Examples:</p><ul><li>Customer 360</li><li>Product performance</li><li>Sales metrics</li><li>Financial reporting tables</li></ul><p>These datasets are frequently published into Snowflake for enterprise consumption.</p><p>Integration Pattern #1: Databricks Processes, Snowflake Serves</p><p>This remains the most common pattern.</p><p>Data flow:</p><p>Raw Data → Databricks → Curated Data → Snowflake → BI Tools</p><p>Advantages:</p><ul><li>Efficient engineering workflows</li><li>Excellent analytical performance</li><li>Strong governance</li></ul><p>This model scales exceptionally well.</p><p>Integration Pattern #2: Snowflake Feeds AI Workloads</p><p>Many organizations already have years of historical data in Snowflake.</p><p>Rather than migrating everything, they use Databricks as an AI acceleration layer.</p><p>Workflow:</p><p>Snowflake → Databricks → ML Models → Snowflake</p><p>Predictions generated in Databricks can be returned to Snowflake for reporting.</p><p>Examples include:</p><ul><li>Customer churn prediction</li><li>Revenue forecasting</li><li>Fraud detection</li><li>Product recommendations</li></ul><p>Integration Pattern #3: Open Storage Architecture</p><p>Increasingly, organizations are minimizing duplication.</p><p>Instead of maintaining multiple copies of data, they use shared storage.</p><p>This is where open table formats become critical.</p><p>Delta Lake vs Iceberg</p><p>One of the most important architectural decisions today involves open table formats.</p><p>Delta Lake</p><p>Strengths:</p><ul><li>Mature ecosystem</li><li>Strong Databricks integration</li><li>Robust transaction support</li><li>Excellent performance</li></ul><p>Best suited for organizations heavily invested in Databricks.</p><p>Apache Iceberg</p><p>Strengths:</p><ul><li>Open governance</li><li>Multi-engine interoperability</li><li>Broad vendor support</li></ul><p>Increasingly attractive for enterprises seeking flexibility.</p><p>Why This Matters</p><p>Historically, moving between platforms required moving data.</p><p>Open table formats change the equation.</p><p>Multiple engines can access the same underlying data.</p><p>Benefits include:</p><ul><li>Reduced storage costs</li><li>Simplified architecture</li><li>Lower operational complexity</li><li>Reduced vendor lock-in</li></ul><p>This trend may become one of the defining architectural shifts of the next decade.</p><p>Building a Customer 360 Platform</p><p>Let’s examine a practical example.</p><p>Imagine a retail organization seeking a unified customer view.</p><p>Data sources include:</p><ul><li>Ecommerce systems</li><li>Mobile applications</li><li>CRM platforms</li><li>Marketing automation tools</li><li>Customer service systems</li></ul><p>Step 1: Ingestion</p><p>Databricks ingests raw data into Bronze tables.</p><p>Data arrives continuously through streaming and batch pipelines.</p><p>Step 2: Data Standardization</p><p>Silver pipelines perform:</p><ul><li>Identity resolution</li><li>Deduplication</li><li>Address normalization</li><li>Data quality validation</li></ul><p>Millions of customer records are reconciled.</p><p>Step 3: Customer Mastering</p><p>Gold datasets create a trusted Customer 360 model.</p><p>Each customer receives a unified profile.</p><p>Step 4: Machine Learning</p><p>Databricks trains models predicting:</p><ul><li>Churn risk</li><li>Lifetime value</li><li>Product affinity</li><li>Marketing responsiveness</li></ul><p>Step 5: Publishing</p><p>Results are published into Snowflake.</p><p>Business teams access insights through:</p><ul><li>Power BI</li><li>Tableau</li><li>Executive dashboards</li></ul><p>The engineering complexity remains hidden from consumers.</p><p>AI and Large Language Models</p><p>AI is rapidly becoming a core platform requirement.</p><p>Modern enterprises increasingly need:</p><ul><li>Retrieval-Augmented Generation (RAG)</li><li>Vector search</li><li>Embedding generation</li><li>Prompt management</li><li>Agentic workflows</li></ul><p>Databricks often becomes the platform for:</p><ul><li>Data preparation</li><li>Embedding pipelines</li><li>Model experimentation</li></ul><p>Snowflake increasingly becomes the platform for:</p><ul><li>Governance</li><li>Consumption</li><li>Business integration</li></ul><p>Together they create a powerful AI ecosystem.</p><p>Cost Optimization Strategies</p><p>Using two platforms does not necessarily mean doubling costs.</p><p>In many cases, specialization reduces overall spending.</p><p>Optimize Snowflake For</p><ul><li>Interactive analytics</li><li>Reporting</li><li>Dashboard workloads</li></ul><p>Optimize Databricks For</p><ul><li>Batch processing</li><li>ML training</li><li>Heavy transformations</li></ul><p>Avoid running engineering workloads in Snowflake solely because data already exists there.</p><p>Avoid running BI dashboards directly on engineering clusters.</p><p>Each platform should perform the work it was designed to do.</p><p>Governance in a Multi-Platform World</p><p>Governance becomes more challenging when multiple platforms coexist.</p><p>Successful organizations establish:</p><p>Data Ownership</p><p>Every dataset should have:</p><ul><li>An owner</li><li>A steward</li><li>A documented purpose</li></ul><p>Data Contracts</p><p>Data producers should define:</p><ul><li>Schemas</li><li>SLAs</li><li>Quality expectations</li></ul><p>This prevents downstream surprises.</p><p>Lineage</p><p>Lineage becomes critical when data moves across platforms.</p><p>Teams should understand:</p><p>Source → Transformation → Consumption</p><p>at every stage.</p><p>Common Mistakes</p><p>Treating Platforms as Competitors</p><p>This mindset often leads to unnecessary architectural compromises.</p><p>Excessive Data Duplication</p><p>Copies create:</p><ul><li>Cost</li><li>Complexity</li><li>Governance challenges</li></ul><p>Ignoring Metadata</p><p>Metadata is often more valuable than data itself.</p><p>Without context, datasets become unusable.</p><p>Overengineering</p><p>Not every organization needs petabyte-scale architectures.</p><p>Build for current needs while allowing room for growth.</p><p>What the Next Five Years May Look Like</p><p>Several trends appear increasingly likely:</p><p>Open Table Formats Become Standard</p><p>Iceberg and Delta continue expanding.</p><p>AI Becomes Embedded Everywhere</p><p>Every platform will support AI.</p><p>The differentiator will be operational execution.</p><p>Data Products Replace Centralized Ownership</p><p>Domain-oriented architectures will continue growing.</p><p>Interoperability Wins</p><p>Organizations increasingly demand flexibility.</p><p>Vendors that embrace openness will likely gain adoption.</p><p>Final Thoughts</p><p>The data industry often frames technology decisions as winner-take-all battles.</p><p>Reality is usually more nuanced.</p><p>Snowflake and Databricks each emerged to solve different challenges.</p><p>Over time they expanded into adjacent territories, creating overlap that fuels endless comparisons.</p><p>Yet when viewed through the lens of data engineering, the most important observation is this:</p><p><strong>Their strengths remain complementary.</strong></p><p>Databricks excels at creating, transforming, enriching, and learning from data.</p><p>Snowflake excels at governing, sharing, analyzing, and consuming data.</p><p>When integrated thoughtfully, they provide a modern architecture capable of supporting analytics, machine learning, AI, governance, and enterprise-scale data operations.</p><p>The most important question is no longer:</p><p><em>“Which platform should we choose?”</em></p><p>Instead, data engineering leaders should ask:</p><p><em>“How can we use each platform where it delivers the most value?”</em></p><p>The organizations that answer that question well will build data platforms that are more resilient, more scalable, and better prepared for the next generation of analytics and AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=809789a64294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Working with Semi-Structured Data in Snowflake]]></title>
            <link>https://medium.com/@aarongmoore_88179/working-with-semi-structured-data-in-snowflake-56e719a59095?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/56e719a59095</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 22 May 2026 04:32:29 GMT</pubDate>
            <atom:updated>2026-05-22T04:32:29.194Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Data Engineer’s Guide to Ingestion, Transformation, and Query Patterns</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*OM-e2y1DOXo-CZK-50YxjA.jpeg" /></figure><h3>Introduction</h3><p>Modern data pipelines rarely deal with clean, pre-modeled relational data alone. JSON payloads from APIs, nested Avro records from Kafka, Parquet files from data lakes, and XML configurations from legacy systems all land in your warehouse. As a data engineer, you need a platform that treats semi-structured data as a first-class citizen. <br> Snowflake handles semi-structured data natively through its VARIANT data type and a rich set of transformation functions. Unlike traditional databases that require you to shred JSON into relational columns before loading, Snowflake stores semi-structured data in an optimized columnar format and lets you transform it at query time or during ingestion.<br> <br> This article covers the complete lifecycle: how semi-structured data enters Snowflake through batch, bulk, and near real-time ingestion, and — more importantly — how you transform, flatten, cast, and reshape that data into analytics-ready structures. Every example is practical and drawn from real-world business scenarios across e-commerce, healthcare IoT, financial services, and SaaS product analytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tjXtq7lYDv8H9w4o3bV93w.jpeg" /></figure><h3>Semi-Structured Data Types in Snowflake</h3><p>Snowflake provides three data types specifically designed for semi-structured data:</p><h3>VARIANT</h3><p>The VARIANT type can store any valid JSON value: objects, arrays, strings, numbers, booleans, and null. Internally, Snowflake analyzes VARIANT columns and stores them in an optimized columnar format, providing performance comparable to native relational columns for frequently accessed paths.</p><h3>OBJECT</h3><p>An OBJECT is a collection of key-value pairs — essentially a JSON object. Keys are always strings; values can be any VARIANT-compatible type.</p><h3>ARRAY</h3><p>An ARRAY is an ordered sequence of VARIANT values, used for representing lists, repeated fields, or nested collections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*2HLbf44WGq6mI6sytZUS8A.jpeg" /></figure><h3>How Snowflake Optimizes Storage</h3><p>When you load VARIANT data, Snowflake transparently extracts commonly accessed paths and stores them as separate micro-partition columns. This means querying raw_data:user_id is not scanning the entire JSON blob — it reads only the bytes for that path. This optimization applies automatically without any DDL changes on your part.</p><p>— All three types in a single table<br> CREATE TABLE events.raw.api_responses (<br> ingested_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),<br> source_system VARCHAR(50),<br> payload VARIANT, — Full JSON document<br> headers OBJECT, — HTTP response headers<br> tags ARRAY — Array of classification tags<br> );</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*JCNWKUgqpQZ7DJlecH_1Bg.jpeg" /></figure><h3>Ingestion Patterns: Getting Semi-Structured Data In</h3><p>Before you can transform data, you need to land it. Snowflake offers three primary ingestion tiers for semi-structured data, each suited to different latency and volume requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*pQlrMcrqZipuI82bNZ-b2A.jpeg" /></figure><h3>Batch &amp; Bulk Ingestion with COPY INTO</h3><p>For scheduled ETL jobs, backfills, or one-time migrations, COPY INTO remains the workhorse. It supports JSON, Avro, Parquet, and ORC formats natively. The key advantage for data engineers is the ability to transform data during the load itself — you don’t need a separate staging-to-production step.</p><p>— Define a file format for nested JSON<br> CREATE OR REPLACE FILE FORMAT json_events_fmt<br> TYPE = ‘JSON’<br> STRIP_OUTER_ARRAY = TRUE<br> COMPRESSION = ‘GZIP’;<br> <br> — Bulk load with transformation during ingestion<br> COPY INTO analytics.staging.user_events (<br> event_id, user_id, event_type, event_ts, properties<br> )<br> FROM (<br> SELECT<br> $1:event_id::STRING,<br> $1:user_id::INTEGER,<br> $1:event_type::STRING,<br> $1:timestamp::TIMESTAMP_NTZ,<br> $1:properties — Keep nested object as VARIANT<br> FROM @events_stage/2024/03/<br> )<br> FILE_FORMAT = (FORMAT_NAME = ‘json_events_fmt’)<br> PATTERN = ‘.*events_.*\.json\.gz’;<br> <br> — Parquet: auto-schema detection with MATCH_BY_COLUMN_NAME<br> COPY INTO analytics.staging.clickstream<br> FROM @data_lake_stage/clickstream/<br> FILE_FORMAT = (TYPE = ‘PARQUET’)<br> MATCH_BY_COLUMN_NAME = ‘CASE_INSENSITIVE’;</p><h3>Continuous Ingestion with Snowpipe</h3><p>Snowpipe provides event-driven file ingestion. When new files land in your cloud storage (S3, GCS, or Azure Blob), cloud event notifications trigger Snowpipe to load them automatically. Latency is typically one to two minutes from file arrival to query availability. This is ideal when upstream producers write micro-batches of JSON or Parquet files.</p><p>— Create a pipe with transformation<br> CREATE OR REPLACE PIPE analytics.pipes.event_pipe<br> AUTO_INGEST = TRUE<br> AS<br> COPY INTO analytics.raw.events (event_id, payload, received_at)<br> FROM (<br> SELECT<br> $1:id::STRING,<br> $1,<br> CURRENT_TIMESTAMP()<br> FROM @events_external_stage/<br> )<br> FILE_FORMAT = (TYPE = ‘JSON’);</p><h3>Near Real-Time with Snowpipe Streaming</h3><p>Snowpipe Streaming enables row-level ingestion with as low as five-second latency. Unlike file-based Snowpipe, it accepts rows directly via SDK (Java, Python, Node.js) or Kafka connector. It supports exactly-once delivery through offset token tracking and ordered ingestion within channels.<br> <br> For data engineers working with Kafka topics that produce JSON or Avro messages, the Snowflake Connector for Kafka combined with Snowpipe Streaming eliminates the need to stage intermediate files entirely.</p><p>— Python SDK example: streaming semi-structured rows<br> from snowflake.streaming import SnowflakeStreamingClient, Channel<br> <br> client = SnowflakeStreamingClient(<br> account=”myorg-myaccount”,<br> user=”streaming_user”,<br> private_key=private_key<br> )<br> <br> channel = client.open_channel(<br> name=”iot_channel_1&quot;,<br> database=”iot_db”,<br> schema=”raw”,<br> table=”sensor_readings”<br> )<br> <br> # Each row can contain VARIANT-compatible nested data<br> rows = [<br> {<br> “device_id”: “sensor-42”,<br> “reading_ts”: “2024–03–15T10:30:00Z”,<br> “metrics”: {“temperature”: 72.4, “humidity”: 45.2},<br> “tags”: [“building-a”, “floor-3”]<br> }<br> ]<br> <br> channel.insert_rows(rows)<br> client.close()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*HUjIeez3Txt-ldYF_sOFfg.jpeg" /></figure><h3>Loading and Parsing XML Data</h3><p>XML remains prevalent in enterprise environments — EDI transactions, healthcare claims (HL7/CDA), SOAP web services, financial reporting (XBRL), and legacy ERP exports. Snowflake handles XML as a first-class format through the PARSE_XML function and XML file format support.<br> <br> Unlike JSON (which maps directly to VARIANT), XML is parsed into an internal OBJECT representation. You load XML files using COPY INTO with TYPE = ‘XML’, or parse XML strings at query time with PARSE_XML. Once parsed, you navigate the structure using XMLGET for element extraction and GET for attributes and content.</p><p>— Load XML files from stage<br> CREATE OR REPLACE FILE FORMAT xml_fmt<br> TYPE = ‘XML’<br> STRIP_OUTER_ELEMENT = FALSE;<br> <br> CREATE TABLE edi.raw.purchase_orders (src VARIANT);<br> <br> COPY INTO edi.raw.purchase_orders<br> FROM @xml_stage/orders/<br> FILE_FORMAT = (FORMAT_NAME = ‘xml_fmt’);<br> <br> — Parse XML from a VARCHAR column (e.g., API response stored as text)<br> SELECT PARSE_XML(xml_text_column) AS parsed_xml<br> FROM edi.staging.raw_messages;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*5z8gl_jJZTRnQQchtLXMjw.jpeg" /></figure><h3>Transforming Semi-Structured Data</h3><p>This is where the real data engineering work happens. Once semi-structured data lands in Snowflake, you need to extract fields, flatten nested structures, handle type coercion, and produce clean dimensional or fact tables.</p><h3>Path Notation and Field Extraction</h3><p>Snowflake supports both dot notation and bracket notation for traversing VARIANT structures. Dot notation is cleaner for known paths; bracket notation handles dynamic keys and keys with special characters.</p><p>— Sample: payload contains nested JSON<br> — {<br> — “user”: {“id”: 1001, “name”: “Jane”, “email”: “jane@co.com”},<br> — “action”: “purchase”,<br> — “items”: [{“sku”: “A1”, “qty”: 2}, {“sku”: “B3”, “qty”: 1}],<br> — “metadata”: {“source-system”: “web”, “version”: “2.1”}<br> — }<br> <br> SELECT<br> payload:user.id::INTEGER AS user_id,<br> payload:user.name::STRING AS user_name,<br> payload:action::STRING AS action_type,<br> payload:items[0].sku::STRING AS first_item_sku,<br> — Bracket notation for keys with special characters<br> payload:metadata[‘source-system’]::STRING AS source_system,<br> ARRAY_SIZE(payload:items) AS item_count<br> FROM analytics.raw.events<br> WHERE payload:action = ‘purchase’;</p><h3>Flattening Nested Arrays with LATERAL FLATTEN</h3><p>FLATTEN is the most powerful tool in your semi-structured transformation toolkit. It converts nested arrays (or objects) into rows, enabling you to join, aggregate, and filter at the element level. Combined with LATERAL, each input row generates one output row per array element.</p><p>— Flatten order items into individual rows<br> SELECT<br> e.payload:order_id::STRING AS order_id,<br> e.payload:user.id::INTEGER AS user_id,<br> e.payload:order_ts::TIMESTAMP_NTZ AS order_timestamp,<br> f.value:sku::STRING AS item_sku,<br> f.value:qty::INTEGER AS quantity,<br> f.value:unit_price::DECIMAL(10,2) AS unit_price,<br> f.index AS line_item_number<br> FROM analytics.raw.events e,<br> LATERAL FLATTEN(input =&gt; e.payload:items) f<br> WHERE e.payload:action = ‘purchase’<br> AND f.value:qty &gt; 0;</p><h3>Multi-Level Flattening</h3><p>When your JSON has arrays nested within arrays (e.g., orders containing items, each item containing applied discounts), you chain multiple FLATTEN operations.</p><p>— Two-level flatten: orders -&gt; items -&gt; discounts<br> SELECT<br> e.payload:order_id::STRING AS order_id,<br> items.value:sku::STRING AS sku,<br> discounts.value:code::STRING AS discount_code,<br> discounts.value:percent::FLOAT AS discount_percent<br> FROM analytics.raw.events e,<br> LATERAL FLATTEN(input =&gt; e.payload:items) items,<br> LATERAL FLATTEN(input =&gt; items.value:discounts) discounts<br> WHERE e.payload:action = ‘purchase’;</p><h3>Flattening Objects into Key-Value Pairs</h3><p>FLATTEN also works on OBJECT types, emitting one row per key-value pair. This is useful for pivoting dynamic attribute maps.</p><p>— Flatten dynamic properties object into rows<br> SELECT<br> e.payload:event_id::STRING AS event_id,<br> f.key AS property_name,<br> f.value::STRING AS property_value<br> FROM analytics.raw.events e,<br> LATERAL FLATTEN(input =&gt; e.payload:properties) f;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PPqTfERYgZ0rrG5v1Gcujg.jpeg" /></figure><h3>Type Casting and Null Handling</h3><p>VARIANT fields default to VARIANT type. You must explicitly cast to the target type. Be aware that accessing a non-existent path returns NULL (not an error), and casting NULL to a type remains NULL. This is both a feature and a pitfall.</p><p>— Safe casting with fallback values<br> SELECT<br> payload:user.id::INTEGER AS user_id,<br> COALESCE(payload:user.email::STRING, ‘unknown’) AS email,<br> TRY_CAST(payload:amount::STRING AS DECIMAL(12,2)) AS amount,<br> — Check if a path exists before using it<br> IFF(payload:metadata:version IS NOT NULL,<br> payload:metadata:version::STRING,<br> ‘1.0’) AS api_version,<br> — Validate data type before cast<br> CASE<br> WHEN TYPEOF(payload:timestamp) = ‘VARCHAR’<br> THEN TRY_TO_TIMESTAMP(payload:timestamp::STRING)<br> WHEN TYPEOF(payload:timestamp) = ‘INTEGER’<br> THEN TO_TIMESTAMP(payload:timestamp::INTEGER)<br> ELSE NULL<br> END AS event_timestamp<br> FROM analytics.raw.events;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*6Qswj9zduKIoP7ga-h3pEA.jpeg" /></figure><h3>Transforming XML Data (Don’t shudder, its not that bad)</h3><p>XML transformation in Snowflake uses a different function set than JSON. The key functions are XMLGET (to extract named elements), GET with the ‘$’ operator (to retrieve element content), and GET with ‘@’ prefixed names (to access attributes). You combine these with LATERAL FLATTEN to iterate over repeating XML elements — the same pattern as JSON arrays.</p><p>— Extract fields from a purchase order XML document<br> — Source XML:<br> — &lt;order id=”PO-2024–001&quot;&gt;<br> — &lt;customer&gt;Acme Corp&lt;/customer&gt;<br> — &lt;items&gt;<br> — &lt;item sku=”WDG-100&quot; qty=”50&quot;&gt;&lt;desc&gt;Widget A&lt;/desc&gt;&lt;/item&gt;<br> — &lt;item sku=”WDG-200&quot; qty=”25&quot;&gt;&lt;desc&gt;Widget B&lt;/desc&gt;&lt;/item&gt;<br> — &lt;/items&gt;<br> — &lt;total currency=”USD”&gt;4750.00&lt;/total&gt;<br> — &lt;/order&gt;<br> <br> SELECT<br> — Extract attribute from root element<br> GET(src, ‘@id’)::STRING AS order_id,<br> — Extract text content of a child element<br> GET(XMLGET(src, ‘customer’), ‘$’)::STRING AS customer_name,<br> — Extract nested element with attribute<br> GET(XMLGET(src, ‘total’), ‘$’)::DECIMAL(12,2) AS total_amount,<br> GET(XMLGET(src, ‘total’), ‘@currency’)::STRING AS currency<br> FROM edi.raw.purchase_orders;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xHM2onZDYPpW1YSuIkGLSA.jpeg" /></figure><h3>Flattening Repeating XML Elements</h3><p>When XML contains repeating child elements (like line items in an order, diagnoses in a medical record, or transactions in a bank statement), you use LATERAL FLATTEN on the element’s content array — accessed via the ‘$’ operator on the parent element.</p><p>— Flatten repeating &lt;item&gt; elements from purchase order XML<br> SELECT<br> GET(src, ‘@id’)::STRING AS order_id,<br> GET(XMLGET(src, ‘customer’), ‘$’)::STRING AS customer_name,<br> GET(f.value, ‘@sku’)::STRING AS item_sku,<br> GET(f.value, ‘@qty’)::INTEGER AS quantity,<br> GET(XMLGET(f.value, ‘desc’), ‘$’)::STRING AS item_description<br> FROM edi.raw.purchase_orders,<br> LATERAL FLATTEN(input =&gt; GET(XMLGET(src, ‘items’), ‘$’)) f<br> WHERE GET(f.value, ‘@’) = ‘item’;</p><h3>XML to JSON Conversion Pattern</h3><p>A common data engineering pattern is to receive XML from legacy systems and convert it to JSON-friendly structures for downstream consumers. You can parse XML and reconstruct it as clean JSON objects using OBJECT_CONSTRUCT.</p><p>— Convert XML purchase orders to clean JSON structure<br> SELECT<br> OBJECT_CONSTRUCT(<br> ‘order_id’, GET(src, ‘@id’)::STRING,<br> ‘customer’, GET(XMLGET(src, ‘customer’), ‘$’)::STRING,<br> ‘currency’, GET(XMLGET(src, ‘total’), ‘@currency’)::STRING,<br> ‘total’, GET(XMLGET(src, ‘total’), ‘$’)::DECIMAL(12,2),<br> ‘items’, (<br> SELECT ARRAY_AGG(OBJECT_CONSTRUCT(<br> ‘sku’, GET(f.value, ‘@sku’)::STRING,<br> ‘qty’, GET(f.value, ‘@qty’)::INTEGER,<br> ‘description’, GET(XMLGET(f.value, ‘desc’), ‘$’)::STRING<br> ))<br> FROM TABLE(FLATTEN(input =&gt; GET(XMLGET(src, ‘items’), ‘$’))) f<br> WHERE GET(f.value, ‘@’) = ‘item’<br> )<br> ) AS order_json<br> FROM edi.raw.purchase_orders;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*86P0vWuoSLQRTSuYSB7x9Q.jpeg" /></figure><h3>Real-World Business Use Cases</h3><p>The patterns above aren’t academic exercises. Here are six complete business scenarios where semi-structured data processing in Snowflake delivers measurable business value. Each includes the ingestion strategy, transformation logic, and the business outcome it powers.</p><h3>Use Case 1: E-Commerce — Real-Time Inventory &amp; Promotion Analytics</h3><p>Business Problem: A multi-channel retailer receives order events from their website, mobile app, and point-of-sale systems in different JSON formats. They need to track inventory movement in near real-time, understand which promotions drive revenue, and provide live dashboards to merchandising teams.<br> <br> Ingestion Strategy: Snowpipe Streaming via Kafka connector. Each channel (web, mobile, POS) publishes order events to Kafka topics. The Snowflake Kafka connector streams them directly into a raw VARIANT table with sub-10-second latency.<br> <br> Business Outcome: Merchandising sees inventory changes within seconds. Promotion effectiveness is measured in real-time during flash sales, enabling mid-campaign adjustments that increased conversion by 12% in pilot testing.</p><p>— Real-time promotion effectiveness from nested order events<br> CREATE OR REPLACE DYNAMIC TABLE retail.marts.promotion_performance<br> TARGET_LAG = ‘1 minute’<br> WAREHOUSE = analytics_wh<br> AS<br> SELECT<br> DATE_TRUNC(‘hour’, TRY_TO_TIMESTAMP_NTZ(<br> e.payload:order_ts::STRING)) AS hour_bucket,<br> promo.value:code::STRING AS promo_code,<br> promo.value:campaign_name::STRING AS campaign_name,<br> e.payload:channel::STRING AS sales_channel,<br> COUNT(DISTINCT e.payload:order_id::STRING) AS orders_with_promo,<br> SUM(items.value:qty::INTEGER *<br> items.value:unit_price::DECIMAL(10,2)) AS gross_revenue,<br> SUM(promo.value:discount_amount::DECIMAL(10,2)) AS total_discount,<br> SUM(items.value:qty::INTEGER) AS units_sold<br> FROM retail.raw.order_events e,<br> LATERAL FLATTEN(input =&gt; e.payload:items) items,<br> LATERAL FLATTEN(input =&gt; e.payload:promotions_applied) promo<br> WHERE e.payload:promotions_applied IS NOT NULL<br> GROUP BY 1, 2, 3, 4;</p><h3>Use Case 2: Healthcare IoT — Patient Monitoring &amp; Alerting</h3><p>Business Problem: A hospital network collects vital signs from bedside monitoring devices. Each device emits JSON readings every 5 seconds containing heart rate, blood pressure (systolic/diastolic), oxygen saturation, and respiratory rate. Clinical teams need to detect deterioration patterns across patient populations while individual alerts are handled at the edge.<br> <br> Ingestion Strategy: Snowpipe Streaming via Python SDK. Edge gateways aggregate readings per ward and stream batches of 50–100 rows every 10 seconds. The nested metrics object varies by device model — some include ECG waveform arrays, others only basic vitals.<br> <br> Business Outcome: Population-level deterioration trends are visible within 30 seconds. A Dynamic Table computes rolling averages and flags patients whose vitals deviate from their baseline, feeding a clinical dashboard that reduced code blue response times by 18%.</p><p>— Patient vitals deterioration detection<br> CREATE OR REPLACE DYNAMIC TABLE clinical.marts.patient_vital_alerts<br> TARGET_LAG = ’30 seconds’<br> WAREHOUSE = clinical_wh<br> AS<br> WITH parsed_vitals AS (<br> SELECT<br> payload:patient_id::STRING AS patient_id,<br> payload:device_id::STRING AS device_id,<br> payload:ward::STRING AS ward,<br> TRY_TO_TIMESTAMP_NTZ(<br> payload:reading_ts::STRING) AS reading_ts,<br> payload:metrics.heart_rate::FLOAT AS heart_rate,<br> payload:metrics.spo2::FLOAT AS oxygen_sat,<br> payload:metrics.systolic_bp::FLOAT AS systolic_bp,<br> payload:metrics.respiratory_rate::FLOAT AS resp_rate<br> FROM clinical.raw.device_readings<br> WHERE reading_ts &gt; DATEADD(‘hour’, -4, CURRENT_TIMESTAMP())<br> ),<br> rolling_stats AS (<br> SELECT<br> patient_id, ward, reading_ts,<br> heart_rate, oxygen_sat, resp_rate,<br> AVG(heart_rate) OVER (<br> PARTITION BY patient_id<br> ORDER BY reading_ts<br> ROWS BETWEEN 60 PRECEDING AND CURRENT ROW<br> ) AS avg_hr_5min,<br> AVG(oxygen_sat) OVER (<br> PARTITION BY patient_id<br> ORDER BY reading_ts<br> ROWS BETWEEN 60 PRECEDING AND CURRENT ROW<br> ) AS avg_spo2_5min<br> FROM parsed_vitals<br> )<br> SELECT<br> patient_id, ward, reading_ts,<br> heart_rate, oxygen_sat, resp_rate,<br> avg_hr_5min, avg_spo2_5min,<br> CASE<br> WHEN oxygen_sat &lt; 90 THEN ‘CRITICAL’<br> WHEN heart_rate &gt; avg_hr_5min * 1.3 THEN ‘WARNING’<br> WHEN resp_rate &gt; 25 THEN ‘WARNING’<br> ELSE ‘NORMAL’<br> END AS alert_level<br> FROM rolling_stats<br> WHERE alert_level != ‘NORMAL’;</p><h3>Use Case 3: Financial Services — Transaction Fraud Detection Pipeline</h3><p>Business Problem: A payment processor receives transaction events as nested JSON from card networks, containing merchant details, cardholder information, geo-coordinates, device fingerprints, and risk scores from upstream ML models. They need to enrich transactions with merchant category data, compute velocity checks (transactions per card in the last hour), and flag anomalies for the fraud operations team.<br> <br> Ingestion Strategy: Snowpipe Streaming via Kafka. Transaction events arrive at 50,000+ per second during peak hours. Each event contains 30–40 nested fields including arrays of previous transaction references.<br> <br> Business Outcome: Fraud analysts see enriched transaction data within 10 seconds of authorization. Velocity-based rules (computed via window functions on streamed data) catch 23% more fraudulent transactions compared to the previous batch-based system that ran on 15-minute cycles.</p><p>— Transaction velocity and anomaly detection<br> CREATE OR REPLACE DYNAMIC TABLE fraud.marts.transaction_risk_scores<br> TARGET_LAG = ’10 seconds’<br> WAREHOUSE = fraud_wh<br> AS<br> WITH enriched_txn AS (<br> SELECT<br> t.payload:txn_id::STRING AS txn_id,<br> t.payload:card_token::STRING AS card_token,<br> t.payload:merchant.mcc::STRING AS merchant_category,<br> t.payload:merchant.name::STRING AS merchant_name,<br> t.payload:merchant.country::STRING AS merchant_country,<br> t.payload:amount.value::DECIMAL(12,2) AS txn_amount,<br> t.payload:amount.currency::STRING AS currency,<br> t.payload:device.fingerprint::STRING AS device_fp,<br> t.payload:geo.lat::FLOAT AS latitude,<br> t.payload:geo.lon::FLOAT AS longitude,<br> t.payload:risk_scores.ml_score::FLOAT AS ml_risk_score,<br> TRY_TO_TIMESTAMP_NTZ(<br> t.payload:event_ts::STRING) AS event_ts<br> FROM fraud.raw.card_transactions t<br> WHERE event_ts &gt; DATEADD(‘hour’, -2, CURRENT_TIMESTAMP())<br> ),<br> velocity AS (<br> SELECT<br> *,<br> COUNT(*) OVER (<br> PARTITION BY card_token<br> ORDER BY event_ts<br> RANGE BETWEEN INTERVAL ‘1 HOUR’ PRECEDING AND CURRENT ROW<br> ) AS txn_count_1hr,<br> SUM(txn_amount) OVER (<br> PARTITION BY card_token<br> ORDER BY event_ts<br> RANGE BETWEEN INTERVAL ‘1 HOUR’ PRECEDING AND CURRENT ROW<br> ) AS spend_1hr,<br> COUNT(DISTINCT merchant_country) OVER (<br> PARTITION BY card_token<br> ORDER BY event_ts<br> RANGE BETWEEN INTERVAL ‘4 HOUR’ PRECEDING AND CURRENT ROW<br> ) AS countries_4hr<br> FROM enriched_txn<br> )<br> SELECT<br> txn_id, card_token, merchant_name, merchant_category,<br> txn_amount, currency, event_ts,<br> ml_risk_score, txn_count_1hr, spend_1hr, countries_4hr,<br> CASE<br> WHEN ml_risk_score &gt; 0.85 THEN ‘HIGH’<br> WHEN txn_count_1hr &gt; 10 AND spend_1hr &gt; 5000 THEN ‘HIGH’<br> WHEN countries_4hr &gt; 3 THEN ‘HIGH’<br> WHEN ml_risk_score &gt; 0.6 OR txn_count_1hr &gt; 5 THEN ‘MEDIUM’<br> ELSE ‘LOW’<br> END AS composite_risk_level<br> FROM velocity;</p><h3>Use Case 4: SaaS Product Analytics — Feature Adoption &amp; User Journey Mapping</h3><p>Business Problem: A B2B SaaS company tracks user interactions through a client-side event SDK that emits deeply nested JSON. Events include page views, feature clicks, form submissions, and error events — each with different schemas and nested context objects (user traits, company info, feature flags, A/B test assignments). Product managers need to understand feature adoption funnels, time-to-value for new users, and which features correlate with retention.<br> <br> Ingestion Strategy: Batch COPY INTO for historical backfills (billions of events from S3 data lake) combined with Snowpipe for ongoing daily event files. The event tracking SDK writes gzipped JSON files to S3 every 60 seconds.<br> <br> Business Outcome: Product teams can self-serve funnel analysis across any combination of features without waiting for data engineering to build new tables. A single VARIANT-based raw table supports 50+ distinct event types. Onboarding funnel analysis revealed that users who complete 3 specific actions in their first session have 4x higher 90-day retention, leading to a redesigned onboarding flow.</p><p>— Feature adoption funnel analysis from nested event data<br> WITH user_actions AS (<br> SELECT<br> payload:user.id::STRING AS user_id,<br> payload:user.company.id::STRING AS company_id,<br> payload:user.company.plan::STRING AS plan_tier,<br> payload:event_type::STRING AS event_type,<br> payload:properties.feature_name::STRING AS feature_name,<br> TRY_TO_TIMESTAMP_NTZ(<br> payload:timestamp::STRING) AS event_ts,<br> payload:context.ab_tests AS ab_assignments<br> FROM product.raw.tracking_events<br> WHERE payload:event_type IN (‘feature_activated’, ‘feature_used’)<br> AND event_ts &gt;= DATEADD(‘day’, -30, CURRENT_DATE())<br> ),<br> funnel AS (<br> SELECT<br> user_id,<br> company_id,<br> plan_tier,<br> MIN(CASE WHEN feature_name = ‘dashboard_created’<br> THEN event_ts END) AS step1_dashboard,<br> MIN(CASE WHEN feature_name = ‘data_source_connected’<br> THEN event_ts END) AS step2_datasource,<br> MIN(CASE WHEN feature_name = ‘first_report_shared’<br> THEN event_ts END) AS step3_shared,<br> MIN(CASE WHEN feature_name = ‘team_member_invited’<br> THEN event_ts END) AS step4_invite<br> FROM user_actions<br> GROUP BY 1, 2, 3<br> )<br> SELECT<br> plan_tier,<br> COUNT(*) AS total_users,<br> COUNT(step1_dashboard) AS reached_step1,<br> COUNT(step2_datasource) AS reached_step2,<br> COUNT(step3_shared) AS reached_step3,<br> COUNT(step4_invite) AS reached_step4,<br> ROUND(COUNT(step4_invite) * 100.0 /<br> NULLIF(COUNT(step1_dashboard), 0), 1) AS full_funnel_pct,<br> AVG(DATEDIFF(‘hour’, step1_dashboard,<br> step3_shared)) AS avg_hours_to_share<br> FROM funnel<br> WHERE step1_dashboard IS NOT NULL<br> GROUP BY plan_tier<br> ORDER BY total_users DESC;</p><h3>Use Case 5: Supply Chain — Shipment Tracking &amp; Exception Management</h3><p>Business Problem: A logistics company integrates shipment tracking data from multiple carriers (FedEx, UPS, DHL, regional couriers). Each carrier provides status updates in different JSON schemas with varying levels of nesting. The operations team needs a unified view of all shipments, automated exception detection (delays, route deviations, temperature excursions for cold-chain), and predictive ETA updates.<br> <br> Ingestion Strategy: Snowpipe for carrier webhook files (each carrier POSTs to an API gateway that writes to S3) combined with Snowpipe Streaming for GPS/IoT updates from fleet telematics devices.<br> <br> Business Outcome: A unified shipment timeline replaces five separate carrier portals. Exception detection triggers automated customer notifications within 2 minutes of a delay event. Cold-chain temperature excursions are caught in real-time, reducing spoilage claims by 34%.</p><p>— Unified shipment tracking across carriers with exception detection<br> CREATE OR REPLACE DYNAMIC TABLE logistics.marts.shipment_exceptions<br> TARGET_LAG = ‘2 minutes’<br> WAREHOUSE = ops_wh<br> AS<br> WITH normalized_events AS (<br> SELECT<br> — Normalize across carrier schemas<br> COALESCE(<br> payload:shipment_id,<br> payload:tracking_number,<br> payload:consignment_ref<br> )::STRING AS shipment_id,<br> COALESCE(<br> payload:carrier_code,<br> payload:carrier<br> )::STRING AS carrier,<br> COALESCE(<br> TRY_TO_TIMESTAMP(payload:event_time::STRING),<br> TRY_TO_TIMESTAMP(payload:timestamp::STRING),<br> TRY_TO_TIMESTAMP(payload:scan_datetime::STRING)<br> ) AS event_ts,<br> COALESCE(<br> payload:status.code,<br> payload:event_code<br> )::STRING AS status_code,<br> COALESCE(<br> payload:location.city,<br> payload:scan_location.city_name<br> )::STRING AS current_city,<br> — Cold-chain specific (when present)<br> payload:sensors.temperature_c::FLOAT AS temperature_c,<br> payload:sensors.humidity_pct::FLOAT AS humidity_pct,<br> payload:estimated_delivery::STRING AS carrier_eta<br> FROM logistics.raw.carrier_events<br> WHERE ingested_at &gt; DATEADD(‘day’, -7, CURRENT_TIMESTAMP())<br> ),<br> exceptions AS (<br> SELECT<br> shipment_id, carrier, event_ts, status_code,<br> current_city, temperature_c,<br> CASE<br> WHEN status_code IN (‘DELAY’, ‘HELD’, ‘EXCEPTION’) THEN ‘DELIVERY_DELAY’<br> WHEN temperature_c &gt; 8.0 THEN ‘COLD_CHAIN_BREACH’<br> WHEN temperature_c &lt; -2.0 THEN ‘COLD_CHAIN_BREACH’<br> WHEN status_code = ‘ROUTE_DEVIATION’ THEN ‘ROUTE_EXCEPTION’<br> END AS exception_type<br> FROM normalized_events<br> WHERE exception_type IS NOT NULL<br> )<br> SELECT * FROM exceptions;</p><h3>Use Case 6: Enterprise Integration — EDI/XML Purchase Order Processing</h3><p>Business Problem: A manufacturing company receives purchase orders from 200+ suppliers via EDI (Electronic Data Interchange). Orders arrive as XML documents with varying structures — some use ANSI X12 mapped to XML, others use custom schemas. The procurement team needs automated order validation, line-item reconciliation against master data, and spend analytics across all suppliers in a single view.<br> <br> Ingestion Strategy: Batch COPY INTO with TYPE = ‘XML’. Suppliers upload XML files to a shared SFTP server, which syncs to S3 every 15 minutes. A Snowpipe auto-ingest pipeline loads new XML files into a raw VARIANT table. Each XML document becomes one row.<br> <br> Business Outcome: Order processing time dropped from 4 hours (manual review) to 15 minutes (automated validation). Spend analytics across all suppliers — regardless of their XML schema — became possible for the first time, revealing $2.3M in duplicate orders over a 6-month period.</p><p>— Transform XML purchase orders into normalized line items<br> CREATE OR REPLACE DYNAMIC TABLE procurement.marts.po_line_items<br> TARGET_LAG = ’15 minutes’<br> WAREHOUSE = procurement_wh<br> AS<br> WITH parsed_orders AS (<br> SELECT<br> GET(src, ‘@id’)::STRING AS po_number,<br> GET(XMLGET(src, ‘header’), ‘$’) AS header,<br> GET(XMLGET(src, ‘supplier’), ‘$’)::STRING AS supplier_name,<br> GET(XMLGET(src, ‘supplier’), ‘@code’)::STRING AS supplier_code,<br> TRY_TO_DATE(<br> GET(XMLGET(src, ‘order_date’), ‘$’)::STRING<br> ) AS order_date,<br> GET(XMLGET(src, ‘ship_to’), ‘$’)::STRING AS ship_to_location,<br> XMLGET(src, ‘line_items’) AS line_items_element<br> FROM procurement.raw.purchase_orders_xml<br> ),<br> flattened_items AS (<br> SELECT<br> o.po_number,<br> o.supplier_name,<br> o.supplier_code,<br> o.order_date,<br> o.ship_to_location,<br> GET(f.value, ‘@line_num’)::INTEGER AS line_number,<br> GET(XMLGET(f.value, ‘material’), ‘$’)::STRING AS material_code,<br> GET(XMLGET(f.value, ‘description’), ‘$’)::STRING AS description,<br> GET(XMLGET(f.value, ‘quantity’), ‘$’)::INTEGER AS quantity,<br> GET(XMLGET(f.value, ‘unit_price’), ‘$’)::DECIMAL(10,2) AS unit_price,<br> GET(XMLGET(f.value, ‘unit_price’), ‘@currency’)::STRING AS currency<br> FROM parsed_orders o,<br> LATERAL FLATTEN(input =&gt; GET(o.line_items_element, ‘$’)) f<br> WHERE GET(f.value, ‘@’) = ‘item’<br> )<br> SELECT<br> po_number,<br> line_number,<br> supplier_name,<br> supplier_code,<br> order_date,<br> material_code,<br> description,<br> quantity,<br> unit_price,<br> currency,<br> quantity * unit_price AS line_total<br> FROM flattened_items;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xWxNxQo_7Ur-AeVmTdnxbg.jpeg" /></figure><h3>Building a Complete Transformation Pipeline</h3><p>In practice, you combine extraction, flattening, and casting techniques into a materialized transformation layer. Here’s a complete example transforming raw e-commerce events into a fact table using a Dynamic Table with automatic refresh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tVjsT2sEkgMeFLnjc2ZlnQ.jpeg" /></figure><p>— Production transformation: raw events -&gt; fact_order_items<br> CREATE OR REPLACE DYNAMIC TABLE analytics.marts.fact_order_items<br> TARGET_LAG = ‘5 minutes’<br> WAREHOUSE = transform_wh<br> AS<br> WITH parsed_orders AS (<br> SELECT<br> payload:order_id::STRING AS order_id,<br> payload:user.id::INTEGER AS user_id,<br> payload:user.region::STRING AS user_region,<br> TRY_TO_TIMESTAMP_NTZ(<br> payload:order_ts::STRING<br> ) AS order_timestamp,<br> payload:items AS items_array,<br> payload:totals.subtotal::DECIMAL(12,2) AS order_subtotal,<br> payload:totals.tax::DECIMAL(12,2) AS order_tax,<br> payload:totals.shipping::DECIMAL(12,2) AS shipping_cost<br> FROM analytics.raw.events<br> WHERE payload:action = ‘purchase’<br> AND payload:order_id IS NOT NULL<br> ),<br> flattened_items AS (<br> SELECT<br> o.order_id,<br> o.user_id,<br> o.user_region,<br> o.order_timestamp,<br> o.order_subtotal,<br> f.index + 1 AS line_number,<br> f.value:sku::STRING AS product_sku,<br> f.value:product_name::STRING AS product_name,<br> f.value:category::STRING AS product_category,<br> f.value:qty::INTEGER AS quantity,<br> f.value:unit_price::DECIMAL(10,2) AS unit_price,<br> f.value:qty::INTEGER *<br> f.value:unit_price::DECIMAL(10,2) AS line_total<br> FROM parsed_orders o,<br> LATERAL FLATTEN(input =&gt; o.items_array) f<br> )<br> SELECT<br> order_id,<br> line_number,<br> user_id,<br> user_region,<br> order_timestamp,<br> DATE_TRUNC(‘day’, order_timestamp) AS order_date,<br> product_sku,<br> product_name,<br> product_category,<br> quantity,<br> unit_price,<br> line_total,<br> order_subtotal<br> FROM flattened_items;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*J77U3xgsl1gxhym2FYlMzw.jpeg" /></figure><h3>Advanced Transformation Patterns</h3><p>Beyond basic extraction and flattening, data engineers regularly encounter more complex transformation requirements.</p><h3>Constructing Semi-Structured Output</h3><p>Sometimes you need to go the other direction — building VARIANT objects from relational data for downstream consumers or API responses.</p><p>— Build a JSON summary per user<br> SELECT<br> user_id,<br> OBJECT_CONSTRUCT(<br> ‘total_orders’, COUNT(DISTINCT order_id),<br> ‘total_revenue’, SUM(line_total),<br> ‘top_categories’, ARRAY_AGG(DISTINCT product_category),<br> ‘last_order_date’, MAX(order_date)::STRING,<br> ‘avg_order_value’, ROUND(AVG(order_subtotal), 2)<br> ) AS user_summary<br> FROM analytics.marts.fact_order_items<br> GROUP BY user_id;</p><h3>Schema Detection and Evolution</h3><p>One advantage of storing semi-structured data in VARIANT is schema flexibility. However, you still need to understand what schemas exist in your data. Snowflake provides INFER_SCHEMA for staged files and schema evolution for auto-adapting table definitions.</p><p>— Discover the schema of staged Parquet files<br> SELECT *<br> FROM TABLE(<br> INFER_SCHEMA(<br> LOCATION =&gt; ‘@data_lake_stage/events/’,<br> FILE_FORMAT =&gt; ‘parquet_fmt’<br> )<br> );<br> <br> — Create a table that auto-evolves as new columns appear<br> CREATE TABLE analytics.raw.evolving_events (<br> record_content VARIANT<br> )<br> ENABLE_SCHEMA_EVOLUTION = TRUE;<br> <br> — Alternative: create from detected schema<br> CREATE TABLE analytics.raw.events_typed<br> USING TEMPLATE (<br> SELECT ARRAY_AGG(OBJECT_CONSTRUCT(*))<br> FROM TABLE(<br> INFER_SCHEMA(<br> LOCATION =&gt; ‘@data_lake_stage/events/’,<br> FILE_FORMAT =&gt; ‘parquet_fmt’<br> )<br> )<br> );</p><h3>Handling Heterogeneous JSON Schemas</h3><p>In real pipelines, the same topic or endpoint can produce documents with different schemas over time. You handle this by writing defensive transformations.</p><p>— Handle schema variations across API versions<br> SELECT<br> payload:id::STRING AS event_id,<br> — v1 uses ‘ts’, v2 uses ‘event_timestamp’<br> COALESCE(<br> TRY_TO_TIMESTAMP(payload:event_timestamp::STRING),<br> TRY_TO_TIMESTAMP(payload:ts::STRING),<br> ingested_at<br> ) AS event_timestamp,<br> — v1 nests user under ‘actor’, v2 under ‘user’<br> COALESCE(<br> payload:user.id,<br> payload:actor.user_id<br> )::INTEGER AS user_id,<br> — Handle both flat and nested address formats<br> COALESCE(<br> payload:shipping.address.country,<br> payload:country_code<br> )::STRING AS country_code<br> FROM analytics.raw.events;</p><h3>Choosing the Right Ingestion and Transformation Pattern</h3><p>The right choice depends on your latency requirements, data volume, and transformation complexity.</p><h3>Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvZwkVZSolU6GDo7dFilWw.jpeg" /></figure><h3>Decision Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*p4VJbKQ0z-x1KnxkX5S4gQ.jpeg" /></figure><p>Use this mental model:<br> <br> 1. If your source produces files (S3, GCS, ADLS), start with COPY INTO for ad-hoc or Snowpipe for continuous.<br> 2. If your source produces rows or messages (Kafka, custom apps, IoT), use Snowpipe Streaming.<br> 3. For transformation, prefer transforming during COPY when the logic is simple (field extraction, type casting). For complex multi-step logic (joins, aggregations, window functions), land raw data first and transform via Dynamic Tables or scheduled Tasks.<br> 4. Always land the raw VARIANT first in a raw/staging layer. This gives you replay capability and decouples ingestion from transformation.</p><h3>Best Practices for Data Engineers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-4VYQslznm0vojvC8QP-Lg.jpeg" /></figure><h3>Storage and Schema Design</h3><p>· Land raw semi-structured data in a dedicated raw schema with VARIANT columns. Add metadata columns (ingested_at, source_file, source_system) for lineage.</p><p>· Don’t over-flatten at ingestion time. Keep nested structures intact in raw; flatten in downstream transformation layers where you control the logic.</p><p>· Use ENABLE_SCHEMA_EVOLUTION on tables receiving Parquet/Avro if upstream schemas change frequently.</p><p>· For high-cardinality VARIANT columns with thousands of unique paths, consider splitting into multiple VARIANT columns by logical domain to aid Snowflake’s internal columnarization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*11COR2QCRdCZ5qJ2_gn5wg.jpeg" /></figure><h3>Query Performance</h3><p>· Cast VARIANT paths to native types in your transformation layer. Predicates on ::STRING or ::INTEGER are vastly faster than predicates on raw VARIANT.</p><p>· Create materialized views or Dynamic Tables for frequently queried transformations — avoid repeating FLATTEN operations on every dashboard query.</p><p>· Use clustering keys on frequently filtered cast expressions: ALTER TABLE SET CLUSTER KEY (payload:user.region::STRING, order_date);</p><p>· FLATTEN with large arrays (1000+ elements per row) can cause row explosion. Filter or limit before flattening when possible.</p><h3>Operational Monitoring</h3><p>· Monitor COPY_HISTORY and PIPE_STATUS for ingestion failures. Semi-structured parsing errors (malformed JSON) will appear as LOAD_FAILED entries.</p><p>· Use VALIDATE function after COPY INTO to inspect rejected records: SELECT * FROM TABLE(VALIDATE(my_table, JOB_ID =&gt; ‘_last’));</p><p>· For Snowpipe Streaming, monitor the SNOWPIPE_STREAMING_FILE_MIGRATION_HISTORY view for data migration status.</p><p>· Set up ALERT objects on Dynamic Table lag to detect transformation pipeline stalls.</p><h3>Conclusion</h3><p>Semi-structured data in Snowflake is not a compromise — it’s a deliberate architectural choice that gives data engineers flexibility without sacrificing query performance. The VARIANT type combined with FLATTEN, path notation, and type casting gives you a complete toolkit for transforming any nested structure into analytics-ready tables.<br> <br> As the business use cases demonstrate, this isn’t just about storing JSON. It’s about enabling real-time fraud detection, live inventory management, clinical monitoring, product-led growth analytics, and supply chain visibility — all from the same fundamental patterns of land-raw-then-transform.<br> <br> The pattern is straightforward: land raw data quickly using the ingestion method that matches your source’s characteristics (COPY INTO for files, Snowpipe for continuous files, Snowpipe Streaming for row-level real-time), then transform declaratively using Dynamic Tables or scheduled SQL tasks. Keep your raw layer intact, transform progressively, and cast to native types at the boundary where analysts and BI tools consume the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ljRcwJROseC6G8Gp0OrP-g.jpeg" /></figure><h3>Key Takeaways</h3><p>· VARIANT, OBJECT, and ARRAY are first-class Snowflake types with columnar storage optimization.</p><p>· COPY INTO supports JSON, Parquet, Avro, ORC, and XML — with inline transformations during bulk loads.</p><p>· XML is handled via PARSE_XML, XMLGET, and GET with ‘$’/’@’ operators — combined with FLATTEN for repeating elements.</p><p>· Snowpipe Streaming enables sub-10-second ingestion for streaming sources with exactly-once delivery guarantees.</p><p>· LATERAL FLATTEN is your primary tool for converting nested arrays/objects (JSON) and repeating elements (XML) into rows.</p><p>· Real business value: fraud detection in 10s, inventory visibility in 5s, clinical alerts in 30s, EDI processing in 15 min.</p><p>· Always land raw VARIANT data first, then transform downstream — this gives you schema flexibility and replay capability.</p><p>· Dynamic Tables provide declarative, incremental transformations with configurable freshness targets.</p><p>· Cast VARIANT paths to native types at the transformation boundary for optimal query performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e719a59095" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Building Real-Time Data Pipelines with Snowpipe: From File-Based Loading to Sub-10-Second…]]></title>
            <link>https://medium.com/@aarongmoore_88179/building-real-time-data-pipelines-with-snowpipe-from-file-based-loading-to-sub-10-second-5bcc920ddbe7?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bcc920ddbe7</guid>
            <category><![CDATA[snowpipe]]></category>
            <category><![CDATA[streaming-pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 15 May 2026 13:56:52 GMT</pubDate>
            <atom:updated>2026-05-15T13:56:52.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>#Building Real-Time Data Pipelines with Snowpipe: From File-Based Loading to Sub-10-Second Streaming</h3><p><em>A comprehensive guide to Snowpipe, Snowpipe Streaming, and how they compare to Apache Kafka for real-time ingestion</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*V2kUBRCMd9YjY4fUSg-oOQ.jpeg" /></figure><h3>Introduction</h3><p>Getting data into your analytics platform quickly and reliably is the foundation of every real-time data pipeline. Without fast, scalable ingestion, downstream transformations, dashboards, and ML models are limited by stale data regardless of how sophisticated they are. For Snowflake users, the ingestion layer is where your real-time story begins — and Snowflake offers two purpose-built services for this: Snowpipe and Snowpipe Streaming.</p><p>Snowpipe has been Snowflake’s continuous data loading workhorse for years — automatically detecting new files in cloud storage and loading them within seconds to minutes. Snowpipe Streaming, built on Snowflake’s new high-performance architecture, takes this further: applications write rows directly into Snowflake tables with as low as 5-second end-to-end latency and up to 10 GB/s throughput, without staging files at all.</p><p>Together with Snowflake’s downstream processing capabilities (Streams for change detection, Tasks for orchestration, Dynamic Tables for declarative transforms), Snowpipe and Snowpipe Streaming form a complete real-time pipeline architecture — from source event to queryable analytics table — entirely within the Snowflake platform.</p><p>This article provides a comprehensive guide to both Snowpipe variants, walks through production-grade pipeline implementations, and compares Snowflake’s native ingestion against Apache Kafka. Whether you’re choosing between Snowpipe and Snowpipe Streaming, evaluating whether to replace Kafka, or designing a hybrid architecture, this guide gives you the technical depth to make the right decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PWRQHhyUyQzfzBLU93X4hg.jpeg" /></figure><h3>Part 1: Snowpipe — Continuous File-Based Ingestion</h3><h3>What Is Snowpipe?</h3><p>Snowpipe is Snowflake’s serverless, event-driven file ingestion service. It automatically detects new data files as they arrive in cloud storage (S3, GCS, Azure Blob Storage) and loads them into Snowflake tables without requiring manual COPY commands or scheduled batch jobs.</p><p>When a file lands in your configured stage, Snowpipe queues it for loading. A serverless compute layer processes the queue, executing the COPY INTO statement defined in your pipe object. The result: continuous, automated data loading with typical latencies of 30–60 seconds from file creation to queryable data.</p><h3>How Snowpipe Works</h3><p>Snowpipe operates through a pipe object that defines the source stage, target table, file format, and optional transformations:</p><p>· Auto-ingest mode: Cloud storage event notifications (SNS, GCS Pub/Sub, Azure Event Grid) trigger loading when new files arrive. This is the recommended production pattern.</p><p>· REST API mode: Your application calls the Snowpipe REST API to notify Snowflake about new files. Useful when you control file creation and want explicit triggering.</p><p>· Serverless compute: Snowpipe uses Snowflake-managed compute resources. You never provision or manage warehouses for ingestion. Billing is per-file based on compute time.</p><p>· Exactly-once loading: Snowpipe tracks loaded files via metadata. Re-submitting the same file will not create duplicates (within a 14-day window).</p><h3>Setting Up Snowpipe with Auto-Ingest (AWS S3)</h3><p>— Step 1: Create a stage pointing to your S3 bucket<br> CREATE OR REPLACE STAGE raw_data_stage<br> URL = ‘s3://my-bucket/events/’<br> STORAGE_INTEGRATION = my_s3_integration<br> FILE_FORMAT = (TYPE = ‘JSON’);<br> <br> — Step 2: Create the target table<br> CREATE OR REPLACE TABLE raw_events (<br> event_data VARIANT,<br> filename STRING DEFAULT METADATA$FILENAME,<br> file_row_number INT DEFAULT METADATA$FILE_ROW_NUMBER,<br> loaded_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br> );<br> <br> — Step 3: Create the pipe with auto-ingest enabled<br> CREATE OR REPLACE PIPE events_pipe<br> AUTO_INGEST = TRUE<br> AS<br> COPY INTO raw_events (event_data)<br> FROM @raw_data_stage<br> FILE_FORMAT = (TYPE = ‘JSON’);<br> <br> — Step 4: Get the SQS ARN to configure S3 event notifications<br> SHOW PIPES LIKE ‘events_pipe’;<br> — Use the notification_channel value to configure S3 -&gt; SNS -&gt; SQS</p><h3>Snowpipe with Transformations</h3><p>Snowpipe supports COPY INTO transformations, allowing you to reshape data during loading:</p><p>— Load CSV with column reordering and type casting<br> CREATE OR REPLACE PIPE sales_pipe AUTO_INGEST = TRUE AS<br> COPY INTO sales_fact (<br> sale_id, customer_id, product_id,<br> quantity, unit_price, total_amount, sale_date<br> )<br> FROM (<br> SELECT<br> $1::INT, — sale_id<br> $2::STRING, — customer_id<br> $3::STRING, — product_id<br> $4::INT, — quantity<br> $5::DECIMAL(10,2), — unit_price<br> $4::INT * $5::DECIMAL(10,2), — computed total<br> $6::DATE — sale_date<br> FROM @sales_stage<br> )<br> FILE_FORMAT = (TYPE = ‘CSV’ SKIP_HEADER = 1);<br> <br> — Load JSON with field extraction<br> CREATE OR REPLACE PIPE json_pipe AUTO_INGEST = TRUE AS<br> COPY INTO user_events (event_id, user_id, event_type, properties, ts)<br> FROM (<br> SELECT<br> $1:event_id::STRING,<br> $1:user_id::STRING,<br> $1:type::STRING,<br> $1:properties::VARIANT,<br> $1:timestamp::TIMESTAMP_NTZ<br> FROM @json_stage<br> )<br> FILE_FORMAT = (TYPE = ‘JSON’);</p><h3>Snowpipe Monitoring and Management</h3><p>— Check pipe status and load history<br> SELECT SYSTEM$PIPE_STATUS(‘events_pipe’);<br> <br> — View recent load history<br> SELECT *<br> FROM TABLE(INFORMATION_SCHEMA.COPY_HISTORY(<br> TABLE_NAME =&gt; ‘raw_events’,<br> START_TIME =&gt; DATEADD(‘hour’, -24, CURRENT_TIMESTAMP())<br> ))<br> ORDER BY LAST_LOAD_TIME DESC;<br> <br> — Check for load errors<br> SELECT *<br> FROM TABLE(INFORMATION_SCHEMA.COPY_HISTORY(<br> TABLE_NAME =&gt; ‘raw_events’,<br> START_TIME =&gt; DATEADD(‘hour’, -24, CURRENT_TIMESTAMP())<br> ))<br> WHERE STATUS = ‘LOAD_FAILED’<br> OR ERROR_COUNT &gt; 0;<br> <br> — Refresh pipe manually (catch up on missed notifications)<br> ALTER PIPE events_pipe REFRESH;<br> <br> — Pause/resume a pipe<br> ALTER PIPE events_pipe SET PIPE_EXECUTION_PAUSED = TRUE;<br> ALTER PIPE events_pipe SET PIPE_EXECUTION_PAUSED = FALSE;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*XrlGFFNHNrBK5whUxNKXrw.jpeg" /></figure><h3>When to Use Standard Snowpipe</h3><p>· Your source system produces files (CSVs, JSON files, Parquet) in cloud storage</p><p>· Latency of 30–60 seconds from file landing to queryable data is acceptable</p><p>· You want zero-management serverless ingestion with auto-scaling</p><p>· Data arrives in batches or micro-batches (files generated periodically)</p><p>· You need simple transformation during load (column selection, type casting)</p><p>· File-based audit trail is important (know exactly which file produced which rows)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*AVUeVMYRVHxJdqwv1Fu23w.jpeg" /></figure><h3>Part 2: Snowpipe Streaming — Row-Level Real-Time Ingestion</h3><h3>What Is Snowpipe Streaming?</h3><p>Snowpipe Streaming is Snowflake’s real-time, row-level ingestion service built on the high-performance architecture. Unlike standard Snowpipe (which loads files), Snowpipe Streaming enables applications to write rows directly into Snowflake tables as they arrive — no files, no staging, no intermediate storage. Data becomes queryable within seconds.</p><p>The high-performance architecture, now Generally Available, delivers remarkable capabilities:</p><p>· Up to 10 GB/s throughput per table</p><p>· As low as 5-second end-to-end ingest-to-query latency</p><p>· Exactly-once delivery through built-in offset token tracking</p><p>· Ordered ingestion within each channel</p><p>· In-flight transformations (filter, reshape, cast during ingestion)</p><p>· Pre-clustering at ingest time (sort data for optimized queries)</p><p>· Schema evolution (auto-add columns detected in incoming data)</p><p>· Support for Snowflake-managed Apache Iceberg tables</p><p>· SDKs for Java, Python, Node.js, plus a REST API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*n7GCvESKSZL00b4COnUGrg.jpeg" /></figure><h3>Key Concepts: Pipes and Channels</h3><p>Snowpipe Streaming introduces two core concepts:</p><p>PIPE Object: The server-side processing layer for all streaming ingestion. It handles schema validation, in-flight transformations, and pre-clustering. A default pipe is automatically created for each table, or you can create custom pipes for advanced processing.</p><p>Channels: Logical connections between a client and a pipe. Each channel maintains its own offset token for exactly-once delivery. Channels map naturally to source partitions (e.g., Kafka topic partitions), enabling deterministic replay and zero-loss recovery. Rows are ordered within each channel.</p><h3>Setting Up Snowpipe Streaming with Python SDK</h3><p># pip install snowflake-ingest<br> <br> from snowflake.ingest import SnowflakeStreamingIngestClient<br> from snowflake.ingest import SnowflakeStreamingIngestChannel<br> <br> # Initialize the client<br> client = SnowflakeStreamingIngestClient(<br> url=”https://myaccount.snowflakecomputing.com&quot;,<br> user=”my_user”,<br> role=”ingest_role”,<br> private_key=private_key_pem,<br> database=”analytics_db”,<br> schema=”raw”<br> )<br> <br> # Open a channel (maps to a source partition)<br> channel = client.open_channel(<br> channel_name=”events_channel_0&quot;,<br> table_name=”raw_events”<br> )<br> <br> # Insert rows<br> rows = [<br> {“event_id”: “evt_001”, “user_id”: “u123”, “type”: “click”,<br> “timestamp”: “2024–01–15T10:30:00Z”},<br> {“event_id”: “evt_002”, “user_id”: “u456”, “type”: “purchase”,<br> “timestamp”: “2024–01–15T10:30:01Z”},<br> ]<br> <br> # Insert with offset token for exactly-once semantics<br> channel.insert_rows(rows, offset_token=”offset_42&quot;)<br> <br> # Check what’s been committed<br> status = channel.get_latest_committed_offset_token()<br> print(f”Last committed offset: {status}”)<br> <br> # On application restart, reopen channel and resume from last offset<br> channel = client.open_channel(<br> channel_name=”events_channel_0&quot;,<br> table_name=”raw_events”<br> )<br> last_offset = channel.get_latest_committed_offset_token()<br> # Resume producing from last_offset + 1</p><h3>Setting Up Snowpipe Streaming with REST API</h3><p>The REST API is ideal for lightweight workloads, IoT devices, and edge deployments:</p><p># Step 1: Get the streaming hostname<br> GET <a href="https://myaccount.snowflakecomputing.com/v2/streaming/hostname">https://myaccount.snowflakecomputing.com/v2/streaming/hostname</a><br> # Returns: {“hostname”: “streaming-abc123.snowflakecomputing.com”}<br> <br> # Step 2: Open a channel<br> PUT /v2/streaming/databases/ANALYTICS_DB/schemas/RAW/pipes/RAW_EVENTS/channels/iot_device_001<br> Headers:<br> Authorization: Bearer &lt;token&gt;<br> Content-Type: application/json<br> <br> # Response includes next_continuation_token<br> <br> # Step 3: Append rows (NDJSON format, max 4MB per batch)<br> POST /v2/streaming/data/databases/ANALYTICS_DB/schemas/RAW/pipes/RAW_EVENTS/channels/iot_device_001/rows<br> Headers:<br> Authorization: Bearer &lt;token&gt;<br> Content-Type: application/x-ndjson<br> Query params:<br> continuationToken=&lt;token_from_step_2&gt;<br> offsetToken=batch_001<br> Body:<br> {“sensor_id”:”s1&quot;,”temperature”:22.5,”ts”:”2024–01–15T10:30:00Z”}<br> {“sensor_id”:”s1&quot;,”temperature”:22.7,”ts”:”2024–01–15T10:30:01Z”}<br> <br> # Response: {“next_continuation_token”: “…”}</p><h3>In-Flight Transformations</h3><p>Snowpipe Streaming supports transformations during ingestion using COPY command syntax within the PIPE object. This lets you cleanse, reshape, and validate data before it’s committed:</p><p>— Create a custom pipe with in-flight transformations<br> CREATE OR REPLACE PIPE events_streaming_pipe<br> AS<br> COPY INTO events_curated (<br> event_id, user_id, event_type,<br> properties, event_timestamp, ingested_at<br> )<br> FROM (<br> SELECT<br> $1:event_id::STRING,<br> $1:user_id::STRING,<br> UPPER($1:type::STRING), — Normalize to uppercase<br> $1:properties::VARIANT,<br> $1:timestamp::TIMESTAMP_NTZ,<br> CURRENT_TIMESTAMP()<br> FROM @~ — Source reference<br> WHERE $1:type::STRING IS NOT NULL — Filter invalid rows<br> );<br> <br> — Invalid rows are captured in Error Tables for inspection</p><h3>Snowpipe Streaming with Kafka Connector (v4)</h3><p>The Snowflake Connector for Kafka (v4) uses Snowpipe Streaming internally, combining Kafka’s event collection capabilities with Snowflake’s high-performance ingestion:</p><p># Kafka connector configuration (connect-distributed.properties)<br> connector.class=com.snowflake.kafka.connector.SnowflakeSinkConnector<br> name=snowflake-kafka-connector<br> <br> # Connection<br> snowflake.url.name=myaccount.snowflakecomputing.com<br> snowflake.user.name=kafka_user<br> snowflake.private.key=&lt;private_key&gt;<br> <br> # Target<br> snowflake.database.name=analytics_db<br> snowflake.schema.name=raw<br> snowflake.topic2table.map=user_events:raw_user_events,system_events:raw_system_events<br> <br> # Performance tuning<br> # Data becomes queryable within 5–10 seconds<br> # Supports up to 10 GB/s throughput per table<br> <br> # Schema evolution (auto-create columns)<br> snowflake.enable.schematization=true<br> schema.registry.url=http://schema-registry:8081<br> <br> # Error handling<br> errors.tolerance=ALL<br> errors.deadletterqueue.topic.name=snowflake-dlq</p><p>Key benefits of the v4 connector over previous versions: up to 10 GB/s throughput, 5–10 second end-to-end latency, exactly-once delivery, in-flight transformations via PIPE objects, pre-clustering, and server-side schema validation with Error Tables for bad records.</p><h3>Exactly-Once Delivery Semantics</h3><p>Snowpipe Streaming provides exactly-once delivery through offset token tracking:</p><p>· Each channel maintains an offset token — a string that represents the last successfully committed position</p><p>· On insert, you provide an offset token. Snowflake commits the rows and advances the offset atomically.</p><p>· On application crash/restart, reopen the channel and call get_latest_committed_offset_token() to find where you left off</p><p>· Resume producing from the last committed offset + 1 — no duplicates, no gaps</p><p>· For Kafka connector: offset tokens map directly to Kafka consumer offsets, providing end-to-end exactly-once from Kafka topic to Snowflake table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*svLxfthoaRCYM3pNCEH6Kw.jpeg" /></figure><h3>Snowpipe vs. Snowpipe Streaming: When to Use Each</h3><p><strong>Dimension</strong></p><p><strong>Snowpipe (File-Based)</strong></p><p><strong>Snowpipe Streaming (Row-Based)</strong></p><p><strong>Input format</strong></p><p>Files (CSV, JSON, Parquet, Avro, ORC)</p><p>Rows (via SDK or REST API)</p><p><strong>Latency</strong></p><p>30–60 seconds</p><p>5–10 seconds</p><p><strong>Throughput</strong></p><p>Bounded by file size/count</p><p>Up to 10 GB/s per table</p><p><strong>Triggering</strong></p><p>Cloud storage event notifications</p><p>Application-driven (push rows)</p><p><strong>Best for</strong></p><p>Existing file-producing systems</p><p>Event streams, IoT, CDC, Kafka</p><p><strong>Delivery</strong></p><p>Exactly-once (file-level dedup)</p><p>Exactly-once (offset tokens)</p><p><strong>Transformations</strong></p><p>COPY INTO SELECT</p><p>PIPE object with COPY syntax</p><p><strong>Cost model</strong></p><p>Per-file compute charges</p><p>Per-GB throughput-based pricing</p><h3>Part 3: Building an End-to-End Real-Time Pipeline</h3><p>Snowpipe (or Snowpipe Streaming) handles the ingestion layer. To build a complete pipeline, you combine it with downstream processing:</p><p>· Snowpipe/Snowpipe Streaming — Gets data into Snowflake (seconds)</p><p>· Streams — Detect what’s new in the landing table (zero cost)</p><p>· Tasks — Automate transformation on a schedule or trigger (1-minute minimum)</p><p>· Dynamic Tables — Declarative alternative to Streams+Tasks for simple transforms</p><h3>Example: IoT Sensor Pipeline with Snowpipe Streaming</h3><p>— Landing table (populated by Snowpipe Streaming REST API from edge devices)<br> CREATE OR REPLACE TABLE raw_sensor_readings (<br> device_id STRING,<br> sensor_type STRING,<br> reading_value FLOAT,<br> unit STRING,<br> reading_timestamp TIMESTAMP_NTZ,<br> metadata VARIANT<br> );<br> <br> — Stream detects new arrivals (zero cost at rest)<br> CREATE OR REPLACE STREAM sensor_stream<br> ON TABLE raw_sensor_readings<br> APPEND_ONLY = TRUE;<br> <br> — Task processes new readings every minute<br> CREATE OR REPLACE TASK process_sensors<br> USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = ‘XSMALL’<br> SCHEDULE = ‘1 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘sensor_stream’)<br> AS<br> BEGIN<br> — Insert into curated table with validation<br> INSERT INTO sensor_readings_curated<br> SELECT device_id, sensor_type, reading_value, unit,<br> reading_timestamp, CURRENT_TIMESTAMP()<br> FROM sensor_stream<br> WHERE reading_value BETWEEN -1000 AND 10000; — Basic validation<br> <br> — Update device last-seen tracker<br> MERGE INTO device_status tgt<br> USING (<br> SELECT device_id, MAX(reading_timestamp) AS last_seen,<br> COUNT(*) AS reading_count<br> FROM sensor_stream GROUP BY device_id<br> ) src ON tgt.device_id = src.device_id<br> WHEN MATCHED THEN UPDATE SET<br> tgt.last_seen = GREATEST(tgt.last_seen, src.last_seen),<br> tgt.total_readings = tgt.total_readings + src.reading_count<br> WHEN NOT MATCHED THEN INSERT VALUES<br> (src.device_id, src.last_seen, src.reading_count, CURRENT_TIMESTAMP());<br> END;<br> <br> ALTER TASK process_sensors RESUME;</p><h3>Example: E-Commerce Event Pipeline with Kafka Connector</h3><p>— Kafka Connector (v4) auto-creates and populates this table<br> — Events arrive with 5–10 second latency from Kafka topics<br> <br> — Stream on the Kafka-populated landing table<br> CREATE STREAM ecommerce_stream<br> ON TABLE raw_ecommerce_events<br> APPEND_ONLY = TRUE;<br> <br> — Multi-step pipeline as a task DAG<br> CREATE OR REPLACE TASK extract_events<br> WAREHOUSE = pipeline_wh<br> SCHEDULE = ‘1 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘ecommerce_stream’)<br> AS<br> INSERT INTO curated_events<br> SELECT<br> record_content:event_id::STRING AS event_id,<br> record_content:user_id::STRING AS user_id,<br> record_content:session_id::STRING AS session_id,<br> record_content:event_type::STRING AS event_type,<br> record_content:properties::VARIANT AS properties,<br> record_content:revenue::DECIMAL(12,2) AS revenue,<br> record_content:timestamp::TIMESTAMP_NTZ AS event_ts,<br> CURRENT_TIMESTAMP() AS processed_at<br> FROM ecommerce_stream;<br> <br> — Dependent task: real-time revenue tracking<br> CREATE OR REPLACE TASK update_revenue_metrics<br> WAREHOUSE = pipeline_wh<br> AFTER extract_events<br> AS<br> MERGE INTO hourly_revenue tgt<br> USING (<br> SELECT DATE_TRUNC(‘hour’, event_ts) AS hour,<br> SUM(revenue) AS rev, COUNT(*) AS txns<br> FROM curated_events<br> WHERE processed_at &gt; DATEADD(‘minute’, -5, CURRENT_TIMESTAMP())<br> AND revenue &gt; 0<br> GROUP BY 1<br> ) src ON tgt.hour = src.hour<br> WHEN MATCHED THEN UPDATE SET<br> tgt.revenue = tgt.revenue + src.rev,<br> tgt.transactions = tgt.transactions + src.txns<br> WHEN NOT MATCHED THEN INSERT VALUES<br> (src.hour, src.rev, src.txns, CURRENT_TIMESTAMP());<br> <br> ALTER TASK update_revenue_metrics RESUME;<br> ALTER TASK extract_events RESUME;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*CvLg6EdNZxVTyak3k3DPzg.jpeg" /></figure><h3>Part 4: Snowpipe Streaming vs. Apache Kafka — The Complete Comparison</h3><p>The question most data engineers ask: “Do I need Kafka, or can Snowpipe Streaming handle my real-time requirements?” This comparison covers every dimension that matters for the decision.</p><h3>Architectural Differences</h3><p>Apache Kafka is a distributed event streaming platform — a general-purpose message bus that sits between producers and consumers. Events are stored durably in partitioned topics and can be consumed by any number of independent systems. Kafka’s role is event routing and distribution across an organization.</p><p>Snowpipe Streaming is a managed ingestion service — purpose-built to get data into Snowflake tables as fast as possible. It is not a general-purpose message bus. It has one job: ingest rows into Snowflake with low latency, high throughput, and exactly-once semantics. It does this job exceptionally well.</p><p>This fundamental difference means they solve different problems at different architectural layers. Kafka routes events between systems; Snowpipe Streaming loads data into one system (Snowflake). In many architectures, they complement rather than compete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9xSb9B2UFHWbmFjPZ6AX9Q.jpeg" /></figure><h3>Head-to-Head Comparison</h3><p>Latency Deep Dive</p><p>Kafka provides true millisecond-level event delivery. A producer publishes an event, and a consumer can read it within 5–50ms in a well-tuned cluster. This makes Kafka suitable for use cases where every millisecond matters: real-time bidding, live gaming, high-frequency trading.</p><p>Snowpipe Streaming delivers 5–10 second ingest-to-query latency. This means from the moment your SDK/API call sends a row, that row becomes queryable in Snowflake within 5–10 seconds. For analytics, dashboards, reporting, ML feature stores, and most operational use cases, this is indistinguishable from “real-time” to end users.</p><p>Combined pipeline latency: If using the Kafka Connector (v4) with Snowpipe Streaming, expect 10–20 seconds total (Kafka consumer lag + Snowpipe Streaming ingestion). Add 1 minute if you layer a Stream + Task for transformation. Total end-to-end: 70–80 seconds from event production to transformed, queryable result.</p><h3>Cost Comparison</h3><p>Snowpipe Streaming uses transparent, throughput-based pricing: you pay per uncompressed GB of data ingested. No idle costs — if you’re not ingesting, you’re not paying. This makes it extremely cost-effective for variable or bursty workloads.</p><p>Kafka requires always-on infrastructure. A minimal production cluster (3 brokers, replication) costs $1,000-$5,000/month on managed services before processing a single event. High-throughput clusters can cost $10,000-$50,000/month. You pay this whether you’re processing 1 event/second or 1 million events/second.</p><p>For workloads where Snowflake is the sole or primary destination, replacing Kafka with direct Snowpipe Streaming ingestion (via SDK or REST API) can reduce ingestion infrastructure costs by 80–95% for small-to-medium data volumes.</p><h3>Operational Complexity</h3><p>Snowpipe Streaming requires: open a channel, insert rows, track offsets. That’s the complete operational model. No clusters, no partitions to manage, no consumer groups, no schema registry, no monitoring agents, no capacity planning. Snowflake handles all compute scaling automatically.</p><p>Kafka requires: cluster provisioning, partition strategy, replication management, consumer group coordination, offset management, Schema Registry, Kafka Connect (for sinks/sources), monitoring (consumer lag, broker health, under-replicated partitions), security configuration, and rolling upgrades. Even managed Kafka (Confluent Cloud, AWS MSK) requires significant expertise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*6VAZxVSScjn9YS-6h2lz0g.jpeg" /></figure><h3>Part 5: When to Use Each Approach</h3><h3>Choose Snowpipe (Standard) When:</h3><p>· Your source systems produce files (ETL tools, data exports, log rotation)</p><p>· 30–60 second latency is acceptable</p><p>· You want completely zero-touch ingestion (auto-ingest from cloud storage)</p><p>· File-based audit trail matters (which file produced which rows)</p><p>· Data arrives in large batches rather than row-by-row</p><h3>Choose Snowpipe Streaming When:</h3><p>· You need sub-10-second ingestion latency</p><p>· Data arrives as individual events/rows (not files)</p><p>· You’re building custom applications that produce events (IoT, mobile, microservices)</p><p>· You want exactly-once delivery with application-managed offsets</p><p>· You need in-flight transformations during ingestion</p><p>· You’re loading from Kafka topics (use the Kafka Connector v4)</p><p>· High throughput is required (up to 10 GB/s per table)</p><p>· Schema evolution is needed (auto-detect new columns)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*zdZq3ggoFtgL6itR_Io4mw.jpeg" /></figure><h3>Choose Kafka When:</h3><p>· Sub-second latency is required (bidding, gaming, trading)</p><p>· The same events must fan-out to multiple independent systems (not just Snowflake)</p><p>· You need full event replay from any historical point</p><p>· Complex stream processing is required (windowed aggregations, CEP, stateful joins)</p><p>· You’re building an organizational event bus (many producers, many consumers)</p><p>· Events must be processed by non-Snowflake systems first (microservices, real-time ML)</p><h3>Choose Kafka + Snowpipe Streaming (Hybrid) When:</h3><p>· You have existing Kafka infrastructure serving multiple systems</p><p>· Snowflake is one of several consumers of the same event streams</p><p>· You want Kafka for event routing + Snowflake for analytics/warehousing</p><p>· The Kafka Connector v4 gives you the best of both: Kafka’s fan-out + Snowpipe Streaming’s 5–10s latency into Snowflake</p><h3>Part 6: Common Migration Patterns</h3><h3>Replacing Kafka with Snowpipe Streaming</h3><p>If Kafka’s only consumer is Snowflake (no fan-out to other systems), you can eliminate Kafka entirely:</p><p># BEFORE: Application -&gt; Kafka -&gt; Kafka Connector -&gt; Snowflake<br> # AFTER: Application -&gt; Snowpipe Streaming SDK -&gt; Snowflake<br> <br> # Python application producing events directly to Snowflake<br> from snowflake.ingest import SnowflakeStreamingIngestClient<br> <br> client = SnowflakeStreamingIngestClient(<br> url=”https://myaccount.snowflakecomputing.com&quot;,<br> user=”app_user”, role=”ingest_role”,<br> private_key=private_key, database=”prod”, schema=”raw”<br> )<br> <br> channel = client.open_channel(<br> channel_name=”app_events_0&quot;,<br> table_name=”application_events”<br> )<br> <br> # In your application’s event handler:<br> def handle_event(event):<br> channel.insert_rows([event], offset_token=str(event[‘sequence_id’]))<br> # Data queryable in Snowflake within 5–10 seconds<br> # No Kafka, no connector, no intermediate infrastructure</p><h3>Migrating from Standard Snowpipe to Snowpipe Streaming</h3><p>If your current pipeline writes files to S3 and loads via Snowpipe, but you need lower latency:</p><p>· Keep standard Snowpipe for existing file-producing systems (backfill, batch exports)</p><p>· Add Snowpipe Streaming for new real-time sources (application events, IoT)</p><p>· Both can target the same table — they coexist without conflict</p><p>· Use Streams downstream to process changes regardless of ingestion method</p><h3>Adding Snowflake to an Existing Kafka Architecture</h3><p>If you already have Kafka serving multiple systems and want to add Snowflake as a consumer:</p><p>— Deploy Kafka Connector v4 (leverages Snowpipe Streaming internally)<br> — Configuration highlights:<br> <br> # connector.class=com.snowflake.kafka.connector.SnowflakeSinkConnector<br> # snowflake.url.name=myaccount.snowflakecomputing.com<br> # snowflake.topic2table.map=events:raw_events<br> <br> # Result: 5–10 second latency from Kafka topic to queryable Snowflake table<br> # Exactly-once delivery, schema evolution, in-flight transforms all included<br> # Kafka continues serving other consumers unchanged</p><h3>Part 7: Monitoring and Best Practices</h3><h3>Monitoring Snowpipe</h3><p>— Pipe status and queue depth<br> SELECT SYSTEM$PIPE_STATUS(‘events_pipe’);<br> <br> — Load history with error details<br> SELECT FILE_NAME, STATUS, ROW_COUNT, ERRORS_SEEN, FIRST_ERROR_MESSAGE,<br> LAST_LOAD_TIME<br> FROM TABLE(INFORMATION_SCHEMA.COPY_HISTORY(<br> TABLE_NAME =&gt; ‘raw_events’,<br> START_TIME =&gt; DATEADD(‘hour’, -12, CURRENT_TIMESTAMP())<br> ))<br> ORDER BY LAST_LOAD_TIME DESC;<br> <br> — Credit usage<br> SELECT PIPE_NAME, SUM(CREDITS_USED) AS credits_24h<br> FROM SNOWFLAKE.ACCOUNT_USAGE.PIPE_USAGE_HISTORY<br> WHERE START_TIME &gt; DATEADD(‘day’, -1, CURRENT_TIMESTAMP())<br> GROUP BY PIPE_NAME ORDER BY credits_24h DESC;</p><h3>Monitoring Snowpipe Streaming</h3><p>— Channel status and latency<br> — (Available via SDK: channel.get_latest_committed_offset_token())<br> — (Available via REST API: Bulk Get Channel Status endpoint)<br> <br> — File migration history (streaming data optimization)<br> SELECT *<br> FROM SNOWFLAKE.ACCOUNT_USAGE.SNOWPIPE_STREAMING_FILE_MIGRATION_HISTORY<br> WHERE START_TIME &gt; DATEADD(‘hour’, -24, CURRENT_TIMESTAMP())<br> ORDER BY START_TIME DESC;<br> <br> — Streaming ingestion cost<br> — Throughput-based: credits per uncompressed GB ingested<br> SELECT *<br> FROM SNOWFLAKE.ACCOUNT_USAGE.SNOWPIPE_STREAMING_CLIENT_HISTORY<br> WHERE START_TIME &gt; DATEADD(‘day’, -7, CURRENT_TIMESTAMP());</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*k8xusRDEyiIGSmViQd5STQ.jpeg" /></figure><h3>Production Best Practices</h3><p>· Snowpipe: Set up alerting on COPY_HISTORY error counts; use PIPE REFRESH after outages</p><p>· Snowpipe Streaming: Always track offset tokens; implement retry with exponential backoff</p><p>· Use multiple channels for parallelism (one per source partition)</p><p>· Enable schema evolution for evolving data formats (avoid pipeline breakage)</p><p>· Use in-flight transformations to validate/cleanse before data hits the table</p><p>· Monitor latency: compare ingestion timestamps vs. event timestamps</p><p>· For Kafka Connector: tune buffer.flush.time for latency vs. cost tradeoff</p><p>· Set Error Table retention to catch and replay failed records</p><p>· Test failover: kill your producer, restart, verify exactly-once from last offset</p><p>· Use pre-clustering for frequently queried tables to avoid post-ingest CLUSTER BY costs</p><h3>Part 8: Real-World Use Cases</h3><h3>Use Case 1: Real-Time Fraud Detection (FinTech)</h3><p>A payment processing company needs to score transactions for fraud within seconds of authorization. Transactions arrive from payment terminals worldwide at rates exceeding 50,000 events per second during peak hours.</p><p>Architecture: Payment terminals produce events to a regional message queue. A lightweight service reads from the queue and pushes rows to Snowflake via the Snowpipe Streaming Python SDK. Each regional service opens its own channel, providing natural partitioning and exactly-once delivery per region. Data lands in Snowflake within 5–10 seconds.</p><p>Downstream processing: A Stream on the landing table feeds a Task that runs every minute. The Task executes a scoring model (via SQL-based rules or Snowflake ML functions), flags high-risk transactions, and inserts alerts into a monitoring table. A second Task sends notifications via external function when critical thresholds are breached.</p><p>Why Snowpipe Streaming over Kafka: The payment company’s only real-time analytics destination is Snowflake. Kafka would add infrastructure cost and latency for zero benefit — there’s no fan-out to other systems. Snowpipe Streaming reduced their ingestion infrastructure cost by 70% while improving latency from 45 seconds (file-based Snowpipe) to 8 seconds.</p><h3>Use Case 2: IoT Fleet Monitoring (Manufacturing)</h3><p>A manufacturing company monitors 50,000 sensors across 12 factories. Sensors report readings every second — temperature, pressure, vibration, power consumption. The operations team needs live dashboards showing equipment health and anomaly alerts within 30 seconds of an abnormal reading.</p><p>Architecture: Edge gateways at each factory buffer sensor readings and push them to Snowflake via the Snowpipe Streaming REST API every 5 seconds. The REST API is ideal here because edge devices run lightweight Linux with limited compute — no JVM needed. Each factory gateway uses its own channel for exactly-once delivery and ordered ingestion.</p><p>The pipeline processes approximately 50,000 rows/second during peak production hours. Snowpipe Streaming handles this comfortably — well within its 10 GB/s per table capacity. A Stream + Task pipeline runs every minute to compute rolling averages, detect threshold violations, and update the real-time dashboard tables.</p><h3>Use Case 3: E-Commerce Clickstream (Retail)</h3><p>An online retailer captures every user interaction — page views, product clicks, cart additions, searches, purchases. During flash sales, event volume spikes to 200,000 events/second. The marketing team needs real-time conversion funnel metrics, and the recommendation engine needs fresh user behavior data.</p><p>Architecture: The web application produces events to Kafka (because the same events also feed an Elasticsearch-based search ranking system and a real-time recommendation service). The Snowflake Kafka Connector (v4) consumes from the Kafka topics and loads into Snowflake via Snowpipe Streaming — achieving 5–10 second latency from Kafka topic to queryable Snowflake table.</p><p>This is the classic hybrid pattern: Kafka for multi-system fan-out, Snowpipe Streaming (via Kafka Connector) for the Snowflake leg. Within Snowflake, Streams detect new clickstream events and Tasks aggregate them into real-time funnel metrics, session summaries, and user activity scores. The marketing dashboard refreshes every minute with fresh conversion data.</p><h3>Use Case 4: CDC from Operational Database (SaaS)</h3><p>A SaaS platform needs to replicate changes from their PostgreSQL operational database into Snowflake for analytics. They use Debezium to capture CDC events from PostgreSQL’s write-ahead log. Previously, they routed Debezium events through Kafka and into Snowflake via the Kafka connector — a complex pipeline with 5 moving parts.</p><p>Simplified architecture: They replaced the Kafka intermediary with direct Snowpipe Streaming ingestion. A lightweight Debezium consumer reads CDC events and pushes them directly to Snowflake via the Python SDK. Each PostgreSQL table maps to a Snowflake landing table with its own channel. The offset token maps to the PostgreSQL LSN (log sequence number), providing exactly-once CDC replication.</p><p>Within Snowflake, Streams on the landing tables detect INSERT/UPDATE/DELETE operations (represented in the CDC payload). Tasks apply the changes to dimensional models using MERGE statements. The entire pipeline runs with 15-second latency (5s Snowpipe Streaming + 10s average task wait) — down from 90+ seconds with the previous Kafka-based architecture.</p><h3>Conclusion</h3><p>Snowpipe and Snowpipe Streaming represent the two pillars of Snowflake’s ingestion strategy — covering the full spectrum from file-based continuous loading to sub-10-second row-level streaming. Together they handle virtually any real-time ingestion requirement without external infrastructure.</p><p>Standard Snowpipe remains the ideal choice for file-producing systems: zero-touch auto-ingest from cloud storage with 30–60 second latency. It’s battle-tested, simple, and requires no application code changes.</p><p>Snowpipe Streaming, built on the high-performance architecture, is the future of real-time ingestion into Snowflake: 5–10 second latency, 10 GB/s throughput, exactly-once delivery, in-flight transforms, and schema evolution. Whether you’re using the SDK directly, the REST API for IoT edge devices, or the Kafka Connector (v4) for existing Kafka infrastructure — Snowpipe Streaming delivers real-time into Snowflake without managing any ingestion infrastructure yourself.</p><p>For organizations that previously defaulted to Kafka for all real-time requirements: evaluate honestly whether Kafka’s multi-system fan-out and millisecond latency are actually needed. If Snowflake is your primary analytics destination and 5–10 second latency suffices, Snowpipe Streaming eliminates an entire infrastructure layer — reducing cost, complexity, and operational burden while actually improving delivery guarantees.</p><p>The optimal architecture for most organizations uses Snowpipe Streaming for direct-to-Snowflake workloads, the Kafka Connector (v4) where Kafka already exists for multi-system distribution, and Streams + Tasks for downstream in-warehouse processing. This gives you sub-minute end-to-end latency from event to insight, with exactly-once semantics at every layer, and zero infrastructure to manage beyond Snowflake itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bcc920ddbe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Mastering Streams and Tasks in Snowflake: The Complete Guide to Event-Driven Data Pipelines]]></title>
            <link>https://medium.com/@aarongmoore_88179/mastering-streams-and-tasks-in-snowflake-the-complete-guide-to-event-driven-data-pipelines-30d4f70ca734?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d4f70ca734</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 08 May 2026 12:59:39 GMT</pubDate>
            <atom:updated>2026-05-08T12:59:39.777Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into change data capture, automated scheduling, and when to choose Streams &amp; Tasks over Dynamic Tables</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0lZwXGOA47DgcHNN7aJ4zg.jpeg" /></figure><h3>Introduction</h3><p>Modern data platforms demand more than batch processing. As organizations move toward real-time analytics, event-driven architectures, and continuous data integration, the need for robust change data capture (CDC) and automated pipeline orchestration has never been greater. Snowflake addresses these needs through two powerful, complementary features: Streams and Tasks.</p><p>Streams provide a mechanism to track and consume changes to tables at the row level — capturing inserts, updates, and deletes as they occur. Tasks provide the scheduling and orchestration layer, enabling you to automate SQL operations on schedules, in response to data availability, or as complex directed acyclic graphs (DAGs) of dependent operations.</p><p>Together, Streams and Tasks form the backbone of Snowflake’s imperative data pipeline capabilities. While Snowflake’s newer Dynamic Tables offer a declarative alternative for many transformation scenarios, Streams and Tasks remain essential for use cases requiring procedural logic, complex orchestration, conditional execution, external integrations, and fine-grained control over pipeline behavior.</p><p>This article provides a comprehensive guide to understanding, implementing, and optimizing Streams and Tasks. We will explore their architecture, walk through practical code examples, examine real-world use cases, and provide clear guidance on when to choose Streams and Tasks over Dynamic Tables.</p><h3>Part 1: Understanding Snowflake Streams</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*uCg6h_XWEhvXes4hlDdwtg.jpeg" /></figure><h3>What Are Streams?</h3><p>A Snowflake Stream is a schema-level object that records data manipulation language (DML) changes made to a table, including inserts, updates, and deletes. Think of a stream as a bookmark that tracks the delta — the set of changes — between two transactional points in time. When you query a stream, you see only the rows that have changed since the last time the stream was consumed.</p><p>Streams do not contain the actual data. Instead, they record metadata about what changed, leveraging Snowflake’s internal versioning system (based on micro-partitions and Time Travel). This means streams add minimal storage overhead — they simply extend the data retention period of the underlying table to preserve the change information.</p><h3>How Streams Work Internally</h3><p>Under the hood, a stream maintains an offset — a pointer to a specific version of the source table. When you query the stream, Snowflake computes the difference between the current table state and the stored offset. When the stream is consumed within a DML transaction (INSERT, UPDATE, DELETE, MERGE, or COPY INTO that commits successfully), the offset advances to the current table version.</p><p>Key characteristics of stream behavior:</p><p>· Transactional consumption: The stream offset advances only when a DML statement consuming the stream commits successfully. If a transaction rolls back, the offset remains unchanged.</p><p>· Multiple consumers: Multiple streams can be created on the same table, each maintaining its own independent offset. This enables multiple consumers to process changes at their own pace.</p><p>· Staleness: If a stream is not consumed within the data retention period of the source table (determined by the DATA_RETENTION_TIME_IN_DAYS parameter), the stream becomes stale and cannot be queried. You must recreate it.</p><p>· Zero-copy: Querying a stream does not copy data. The computation happens at query time using Snowflake’s versioning metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*5BL2y1y2ynytVYNNlvcSzA.jpeg" /></figure><h3>Stream Metadata Columns</h3><p>When you query a stream, each row includes three additional metadata columns that describe the type of change:</p><p>· METADATA$ACTION — Indicates whether the row was INSERTed or DELETEd.</p><p>· METADATA$ISUPDATE — A boolean indicating whether the action is part of an UPDATE operation. An UPDATE is represented as a DELETE followed by an INSERT, both with METADATA$ISUPDATE set to TRUE.</p><p>· METADATA$ROW_ID — A unique, immutable identifier for each row, used to track the same logical row across changes.</p><h3>Types of Streams</h3><p>Snowflake supports several stream types, each suited to different use cases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bf_OYrrwjQI4LNGZbs9yiA.jpeg" /></figure><h3>Standard (Delta) Streams</h3><p>The default stream type. Standard streams track all DML changes: inserts, updates, and deletes. They provide a net change view — if a row is inserted and then deleted between two consumption points, it will not appear in the stream. Similarly, if a row is inserted and then updated, only the final state appears as an INSERT.</p><p>CREATE OR REPLACE STREAM orders_stream<br> ON TABLE raw_orders;</p><h3>Append-Only Streams</h3><p>Append-only streams track only row inserts. They do not capture updates or deletes. This is ideal for scenarios where you are loading data into staging tables and only care about new arrivals — for example, ingesting event logs or sensor data where records are never modified.</p><p>CREATE OR REPLACE STREAM events_stream<br> ON TABLE raw_events<br> APPEND_ONLY = TRUE;</p><h3>Insert-Only Streams</h3><p>Insert-only streams are specifically designed for external tables. Since external tables reference data in cloud storage that Snowflake doesn’t control, only inserts of new files can be reliably tracked. Insert-only streams capture rows from newly added files.</p><p>CREATE OR REPLACE STREAM ext_events_stream<br> ON EXTERNAL TABLE ext_events<br> INSERT_ONLY = TRUE;</p><h3>Streams on Views</h3><p>You can create streams on views (including secure views) as long as the underlying query meets certain requirements. The view must ultimately reference a single table. This is useful for creating a filtered or transformed perspective of changes without modifying the base table structure.</p><h3>Streams on Directory Tables</h3><p>Directory table streams track metadata changes in stage directory tables, allowing you to detect when new files are staged or existing files are modified/removed.</p><h3>Creating and Querying Streams: Practical Examples</h3><p>Let us walk through a complete example of creating and consuming a stream:</p><p>— Step 1: Create a source table<br> CREATE OR REPLACE TABLE customers (<br> customer_id INT,<br> name STRING,<br> email STRING,<br> tier STRING,<br> updated_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br> );<br> <br> — Step 2: Create a standard stream on the table<br> CREATE OR REPLACE STREAM customers_stream<br> ON TABLE customers<br> SHOW_INITIAL_ROWS = TRUE; — Include existing rows as INSERTs<br> <br> — Step 3: Insert some data<br> INSERT INTO customers (customer_id, name, email, tier) VALUES<br> (1, ‘Alice Johnson’, ‘alice@example.com’, ‘gold’),<br> (2, ‘Bob Smith’, ‘bob@example.com’, ‘silver’),<br> (3, ‘Carol White’, ‘carol@example.com’, ‘bronze’);<br> <br> — Step 4: Query the stream to see changes<br> SELECT * FROM customers_stream;<br> — Returns 3 rows, all with METADATA$ACTION = ‘INSERT’<br> <br> — Step 5: Consume the stream in a DML transaction<br> INSERT INTO customers_dim<br> SELECT customer_id, name, email, tier, updated_at<br> FROM customers_stream<br> WHERE METADATA$ACTION = ‘INSERT’;<br> <br> — After commit, the stream is empty (offset advanced)<br> <br> — Step 6: Make more changes<br> UPDATE customers SET tier = ‘platinum’ WHERE customer_id = 1;<br> DELETE FROM customers WHERE customer_id = 3;<br> <br> — Step 7: Query the stream again<br> SELECT * FROM customers_stream;<br> — Shows: customer_id 1 DELETE (old row) + INSERT (new row with platinum)<br> — customer_id 3 DELETE</p><h3>Part 2: Understanding Snowflake Tasks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*LLTOX3qmwQhHFv-G2LC-5A.jpeg" /></figure><h3>What Are Tasks?</h3><p>A Snowflake Task is a schema-level object that defines a unit of work — a SQL statement or stored procedure call — along with the conditions under which that work should execute. Tasks provide the scheduling and automation layer for Snowflake’s data pipeline capabilities.</p><p>Tasks can be triggered in two ways:</p><p>· Schedule-based: Execute on a recurring schedule (e.g., every 5 minutes, hourly, daily) using either a CRON expression or a fixed interval.</p><p>· Event-based (Triggered Tasks): Execute in response to data arrival or other events, without a fixed schedule.</p><h3>Task Execution Models</h3><h3>User-Managed Warehouse Tasks</h3><p>These tasks run on a virtual warehouse that you specify. You pay for the warehouse compute time. This gives you full control over the compute resources but requires you to manage warehouse sizing and concurrency.</p><p>CREATE OR REPLACE TASK process_orders<br> WAREHOUSE = transform_wh<br> SCHEDULE = ‘5 MINUTE’<br> AS<br> CALL process_new_orders();</p><h3>Serverless Tasks</h3><p>Serverless tasks use Snowflake-managed compute resources. Snowflake automatically provisions and scales the compute needed for each execution. This eliminates the need to manage warehouses and can be more cost-effective for sporadic or variable workloads. You are billed per-second based on actual compute used.</p><p>CREATE OR REPLACE TASK process_orders<br> USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = ‘XSMALL’<br> SCHEDULE = ‘5 MINUTE’<br> AS<br> CALL process_new_orders();</p><h3>Task Scheduling Options</h3><p>Tasks support flexible scheduling through CRON expressions or simple intervals:</p><p>— Run every 5 minutes<br> CREATE TASK t1<br> WAREHOUSE = wh<br> SCHEDULE = ‘5 MINUTE’<br> AS SELECT 1;<br> <br> — Run daily at 6 AM UTC<br> CREATE TASK t2<br> WAREHOUSE = wh<br> SCHEDULE = ‘USING CRON 0 6 * * * UTC’<br> AS SELECT 1;<br> <br> — Run every weekday at 8:30 AM America/New_York<br> CREATE TASK t3<br> WAREHOUSE = wh<br> SCHEDULE = ‘USING CRON 30 8 * * 1–5 America/New_York’<br> AS SELECT 1;<br> <br> — Run on the first day of each month at midnight<br> CREATE TASK t4<br> WAREHOUSE = wh<br> SCHEDULE = ‘USING CRON 0 0 1 * * UTC’<br> AS SELECT 1;</p><h3>Conditional Execution with WHEN</h3><p>One of the most powerful features of tasks is the WHEN clause, which allows conditional execution. The task only runs its SQL body if the WHEN condition evaluates to TRUE. This is commonly used with SYSTEM$STREAM_HAS_DATA() to avoid running transformations when no new data is available:</p><p>CREATE OR REPLACE TASK transform_orders<br> WAREHOUSE = transform_wh<br> SCHEDULE = ‘1 MINUTE’<br> WHEN<br> SYSTEM$STREAM_HAS_DATA(‘orders_stream’)<br> AS<br> INSERT INTO orders_fact<br> SELECT * FROM orders_stream<br> WHERE METADATA$ACTION = ‘INSERT’;</p><p>The WHEN clause is evaluated without consuming warehouse credits (it runs on Snowflake’s cloud services layer). This means you can schedule a task to check frequently without incurring compute costs when there is no work to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*m4AdLminiXlUs02PmgB55A.jpeg" /></figure><h3>Task Graphs (DAGs)</h3><p>Tasks can be organized into directed acyclic graphs (DAGs) where child tasks execute after their predecessor tasks complete successfully. This enables complex, multi-step pipelines with proper dependency management.</p><p>A task graph has the following structure:</p><p>· Root task: The entry point of the graph. Only root tasks have a SCHEDULE. The root task’s schedule triggers the entire graph.</p><p>· Child tasks: Define one or more predecessors using the AFTER clause. A child task runs only after ALL of its predecessors complete successfully.</p><p>· Finalizer task: An optional task that runs after all other tasks in the graph complete (whether they succeeded or failed). Useful for cleanup, notifications, or error handling.</p><p>— Root task: extract raw data<br> CREATE OR REPLACE TASK extract_data<br> WAREHOUSE = etl_wh<br> SCHEDULE = ’10 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘raw_stream’)<br> AS<br> INSERT INTO staging_table<br> SELECT * FROM raw_stream WHERE METADATA$ACTION = ‘INSERT’;<br> <br> — Child task 1: transform customer dimension<br> CREATE OR REPLACE TASK transform_customers<br> WAREHOUSE = etl_wh<br> AFTER extract_data<br> AS<br> MERGE INTO dim_customers tgt<br> USING staging_customers src<br> ON tgt.customer_id = src.customer_id<br> WHEN MATCHED THEN UPDATE SET<br> tgt.name = src.name,<br> tgt.email = src.email,<br> tgt.updated_at = CURRENT_TIMESTAMP()<br> WHEN NOT MATCHED THEN INSERT<br> (customer_id, name, email, created_at, updated_at)<br> VALUES (src.customer_id, src.name, src.email,<br> CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP());<br> <br> — Child task 2: transform product dimension (runs in parallel with task 1)<br> CREATE OR REPLACE TASK transform_products<br> WAREHOUSE = etl_wh<br> AFTER extract_data<br> AS<br> MERGE INTO dim_products tgt<br> USING staging_products src<br> ON tgt.product_id = src.product_id<br> WHEN MATCHED THEN UPDATE SET<br> tgt.name = src.name,<br> tgt.price = src.price,<br> tgt.updated_at = CURRENT_TIMESTAMP()<br> WHEN NOT MATCHED THEN INSERT<br> (product_id, name, price, created_at, updated_at)<br> VALUES (src.product_id, src.name, src.price,<br> CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP());<br> <br> — Child task 3: build fact table (depends on both dimensions)<br> CREATE OR REPLACE TASK build_fact_orders<br> WAREHOUSE = etl_wh<br> AFTER transform_customers, transform_products<br> AS<br> INSERT INTO fact_orders<br> SELECT<br> o.order_id,<br> c.customer_key,<br> p.product_key,<br> o.quantity,<br> o.total_amount,<br> o.order_date<br> FROM staging_orders o<br> JOIN dim_customers c ON o.customer_id = c.customer_id<br> JOIN dim_products p ON o.product_id = p.product_id;<br> <br> — Finalizer task: cleanup and logging<br> CREATE OR REPLACE TASK pipeline_finalizer<br> WAREHOUSE = etl_wh<br> FINALIZE = extract_data<br> AS<br> BEGIN<br> — Log pipeline completion<br> INSERT INTO pipeline_log (pipeline_name, completed_at, status)<br> VALUES (‘order_pipeline’, CURRENT_TIMESTAMP(),<br> CASE WHEN SYSTEM$GET_PREDECESSOR_RETURN_VALUE(‘build_fact_orders’) IS NOT NULL<br> THEN ‘SUCCESS’ ELSE ‘PARTIAL_FAILURE’ END);<br> — Truncate staging tables<br> TRUNCATE TABLE staging_customers;<br> TRUNCATE TABLE staging_products;<br> TRUNCATE TABLE staging_orders;<br> END;<br> <br> — Resume all tasks (tasks are created in suspended state)<br> ALTER TASK pipeline_finalizer RESUME;<br> ALTER TASK build_fact_orders RESUME;<br> ALTER TASK transform_products RESUME;<br> ALTER TASK transform_customers RESUME;<br> ALTER TASK extract_data RESUME; — Root task must be resumed LAST</p><h3>Triggered Tasks</h3><p>Introduced as a newer capability, triggered tasks execute in response to data ingestion events rather than on a fixed schedule. When new data arrives (via Snowpipe, Snowpipe Streaming, INSERT, or COPY), the task is triggered automatically. This provides near-real-time processing without the overhead of frequent polling.</p><p>— A triggered task that fires when new data arrives in raw_events<br> CREATE OR REPLACE TASK process_events<br> WAREHOUSE = streaming_wh<br> WHEN SYSTEM$STREAM_HAS_DATA(‘events_stream’)<br> — No SCHEDULE clause: triggered by data arrival<br> AS<br> INSERT INTO processed_events<br> SELECT<br> event_id,<br> event_type,<br> payload:user_id::STRING AS user_id,<br> payload:action::STRING AS action,<br> event_timestamp<br> FROM events_stream<br> WHERE METADATA$ACTION = ‘INSERT’;</p><h3>Part 3: Combining Streams and Tasks — The Power Duo</h3><p>While streams and tasks are individually useful, their real power emerges when combined. Streams detect what changed; tasks automate when and how to respond. Together they create event-driven, incremental data pipelines that process only what is new or modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*M5db5JTqNpSwWZ6nJqjlxw.jpeg" /></figure><h3>Pattern: Incremental CDC Pipeline</h3><p>The most common pattern combines a stream (for change detection) with a task (for scheduled or triggered processing) and a MERGE statement (for idempotent application of changes to a target table).</p><p>— Source: raw JSON data landing table (loaded by Snowpipe)<br> CREATE OR REPLACE TABLE raw_events (<br> raw_data VARIANT,<br> loaded_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br> );<br> <br> — Stream: track new arrivals<br> CREATE OR REPLACE STREAM raw_events_stream<br> ON TABLE raw_events<br> APPEND_ONLY = TRUE;<br> <br> — Target: curated events table<br> CREATE OR REPLACE TABLE curated_events (<br> event_id STRING,<br> user_id STRING,<br> event_type STRING,<br> event_properties VARIANT,<br> event_timestamp TIMESTAMP_NTZ,<br> processed_at TIMESTAMP_NTZ<br> );<br> <br> — Task: process new events every minute<br> CREATE OR REPLACE TASK curate_events<br> WAREHOUSE = etl_wh<br> SCHEDULE = ‘1 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘raw_events_stream’)<br> AS<br> INSERT INTO curated_events<br> SELECT<br> raw_data:event_id::STRING,<br> raw_data:user_id::STRING,<br> raw_data:event_type::STRING,<br> raw_data:properties::VARIANT,<br> raw_data:timestamp::TIMESTAMP_NTZ,<br> CURRENT_TIMESTAMP()<br> FROM raw_events_stream;<br> <br> ALTER TASK curate_events RESUME;</p><h3>Pattern: Multi-Stream Aggregation</h3><p>A single task can consume multiple streams, enabling you to combine changes from several source tables into a unified transformation:</p><p>— Streams on multiple source tables<br> CREATE STREAM orders_stream ON TABLE raw_orders;<br> CREATE STREAM returns_stream ON TABLE raw_returns;<br> CREATE STREAM payments_stream ON TABLE raw_payments;<br> <br> — Task that joins changes from multiple streams<br> CREATE OR REPLACE TASK build_order_summary<br> WAREHOUSE = analytics_wh<br> SCHEDULE = ‘5 MINUTE’<br> WHEN<br> SYSTEM$STREAM_HAS_DATA(‘orders_stream’)<br> OR SYSTEM$STREAM_HAS_DATA(‘returns_stream’)<br> OR SYSTEM$STREAM_HAS_DATA(‘payments_stream’)<br> AS<br> BEGIN<br> — Process new orders<br> MERGE INTO order_summary tgt<br> USING (<br> SELECT order_id, customer_id, order_total, order_date<br> FROM orders_stream<br> WHERE METADATA$ACTION = ‘INSERT’<br> ) src ON tgt.order_id = src.order_id<br> WHEN NOT MATCHED THEN INSERT VALUES<br> (src.order_id, src.customer_id, src.order_total,<br> 0, src.order_total, src.order_date, ‘active’);<br> <br> — Process returns<br> MERGE INTO order_summary tgt<br> USING (<br> SELECT order_id, return_amount<br> FROM returns_stream<br> WHERE METADATA$ACTION = ‘INSERT’<br> ) src ON tgt.order_id = src.order_id<br> WHEN MATCHED THEN UPDATE SET<br> tgt.return_amount = tgt.return_amount + src.return_amount,<br> tgt.net_amount = tgt.order_total — (tgt.return_amount + src.return_amount),<br> tgt.status = ‘partially_returned’;<br> <br> — Process payments<br> MERGE INTO order_summary tgt<br> USING (<br> SELECT order_id, payment_status<br> FROM payments_stream<br> WHERE METADATA$ACTION = ‘INSERT’<br> ) src ON tgt.order_id = src.order_id<br> WHEN MATCHED THEN UPDATE SET<br> tgt.status = CASE<br> WHEN src.payment_status = ‘completed’ THEN ‘paid’<br> WHEN src.payment_status = ‘failed’ THEN ‘payment_failed’<br> ELSE tgt.status<br> END;<br> END;<br> <br> ALTER TASK build_order_summary RESUME;</p><h3>Pattern: SCD Type 2 Implementation</h3><p>Slowly Changing Dimensions (Type 2) require tracking the history of changes over time. This is a classic use case where streams and tasks excel because you need explicit control over how changes are applied — closing old records and opening new ones:</p><p>— Source table (operational system)<br> CREATE TABLE customer_source (<br> customer_id INT,<br> name STRING,<br> email STRING,<br> address STRING,<br> tier STRING<br> );<br> <br> — Stream on source<br> CREATE STREAM customer_changes<br> ON TABLE customer_source;<br> <br> — SCD Type 2 dimension table<br> CREATE TABLE dim_customer_scd2 (<br> surrogate_key INT AUTOINCREMENT,<br> customer_id INT,<br> name STRING,<br> email STRING,<br> address STRING,<br> tier STRING,<br> effective_from TIMESTAMP_NTZ,<br> effective_to TIMESTAMP_NTZ DEFAULT ‘9999–12–31’::TIMESTAMP_NTZ,<br> is_current BOOLEAN DEFAULT TRUE<br> );<br> <br> — Task to apply SCD2 logic<br> CREATE OR REPLACE TASK apply_customer_scd2<br> WAREHOUSE = dim_wh<br> SCHEDULE = ‘5 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘customer_changes’)<br> AS<br> BEGIN<br> — Step 1: Close existing current records for changed customers<br> UPDATE dim_customer_scd2<br> SET effective_to = CURRENT_TIMESTAMP(),<br> is_current = FALSE<br> WHERE customer_id IN (<br> SELECT customer_id FROM customer_changes<br> WHERE METADATA$ACTION = ‘INSERT’ AND METADATA$ISUPDATE = TRUE<br> )<br> AND is_current = TRUE;<br> <br> — Step 2: Insert new current records<br> INSERT INTO dim_customer_scd2<br> (customer_id, name, email, address, tier, effective_from)<br> SELECT<br> customer_id, name, email, address, tier, CURRENT_TIMESTAMP()<br> FROM customer_changes<br> WHERE METADATA$ACTION = ‘INSERT’;<br> <br> — Step 3: Handle deletes (soft close)<br> UPDATE dim_customer_scd2<br> SET effective_to = CURRENT_TIMESTAMP(),<br> is_current = FALSE<br> WHERE customer_id IN (<br> SELECT customer_id FROM customer_changes<br> WHERE METADATA$ACTION = ‘DELETE’ AND METADATA$ISUPDATE = FALSE<br> )<br> AND is_current = TRUE;<br> END;<br> <br> ALTER TASK apply_customer_scd2 RESUME;</p><h3>Part 4: Streams &amp; Tasks vs. Dynamic Tables — When to Use What</h3><p>Snowflake’s Dynamic Tables provide a declarative approach to data transformation. You write a SELECT query defining the desired result, and Snowflake handles the incremental refresh logic automatically. This raises an important question: when should you use Streams and Tasks, and when should you use Dynamic Tables?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*kpVLFUz-nFa9Gn1Yc76azA.jpeg" /></figure><h3>The Fundamental Difference: Imperative vs. Declarative</h3><p>Streams and Tasks follow an imperative model: you write procedural code that explicitly defines HOW to transform data step by step. Dynamic Tables follow a declarative model: you define WHAT the result should look like, and Snowflake determines how to achieve it.</p><p>— DYNAMIC TABLE approach (declarative):<br> — “I want a table that always reflects this query result”<br> CREATE OR REPLACE DYNAMIC TABLE customer_orders<br> TARGET_LAG = ‘5 minutes’<br> WAREHOUSE = wh<br> AS<br> SELECT<br> c.customer_id,<br> c.name,<br> COUNT(o.order_id) AS total_orders,<br> SUM(o.amount) AS total_spent<br> FROM customers c<br> JOIN orders o ON c.customer_id = o.customer_id<br> GROUP BY c.customer_id, c.name;<br> <br> <br> — STREAMS &amp; TASKS approach (imperative):<br> — “When changes happen, do these specific steps”<br> CREATE STREAM orders_stream ON TABLE orders;<br> <br> CREATE TASK update_customer_orders<br> WAREHOUSE = wh<br> SCHEDULE = ‘5 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘orders_stream’)<br> AS<br> MERGE INTO customer_orders tgt<br> USING (<br> SELECT<br> c.customer_id,<br> c.name,<br> COUNT(o.order_id) AS total_orders,<br> SUM(o.amount) AS total_spent<br> FROM customers c<br> JOIN orders o ON c.customer_id = o.customer_id<br> WHERE o.customer_id IN (<br> SELECT DISTINCT customer_id FROM orders_stream<br> )<br> GROUP BY c.customer_id, c.name<br> ) src ON tgt.customer_id = src.customer_id<br> WHEN MATCHED THEN UPDATE SET<br> tgt.total_orders = src.total_orders,<br> tgt.total_spent = src.total_spent<br> WHEN NOT MATCHED THEN INSERT VALUES<br> (src.customer_id, src.name, src.total_orders, src.total_spent);</p><h3>When to Choose Streams &amp; Tasks Over Dynamic Tables</h3><p>There are several scenarios where Streams and Tasks are the better choice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xhI4MyMv7FtNJYpFQJjbxw.jpeg" /></figure><h3>1. Procedural Logic and Stored Procedures</h3><p>Dynamic Tables cannot call stored procedures or execute multi-statement procedural logic. If your transformation requires conditional branching, loops, error handling, or calls to stored procedures, you must use Tasks.</p><p>— Tasks can execute complex stored procedures<br> CREATE OR REPLACE TASK daily_data_quality<br> WAREHOUSE = qa_wh<br> SCHEDULE = ‘USING CRON 0 6 * * * UTC’<br> AS<br> CALL run_data_quality_checks(‘production’, ‘orders’);<br> — This stored procedure:<br> — 1. Runs 50+ validation rules<br> — 2. Logs failures to an audit table<br> — 3. Sends alerts via external functions<br> — 4. Quarantines bad records<br> — Dynamic Tables cannot do any of this.</p><h3>2. Non-Deterministic Operations</h3><p>Dynamic Tables require deterministic queries — the same input must always produce the same output. Tasks have no such restriction. If your pipeline needs to call external functions, use random sampling, generate surrogate keys with sequences, or incorporate system timestamps in specific ways, Tasks are required.</p><h3>3. External Integrations and Side Effects</h3><p>Tasks can trigger external functions, send notifications, interact with external APIs, and perform operations that have side effects beyond Snowflake. Dynamic Tables are limited to pure data transformations.</p><p>— Task that sends notifications on data quality failures<br> CREATE OR REPLACE TASK alert_on_anomalies<br> WAREHOUSE = monitoring_wh<br> SCHEDULE = ’15 MINUTE’<br> AS<br> BEGIN<br> LET anomaly_count INT;<br> anomaly_count := (<br> SELECT COUNT(*) FROM sales_stream<br> WHERE METADATA$ACTION = ‘INSERT’<br> AND amount &gt; (SELECT AVG(amount) * 3 FROM sales_history)<br> );<br> <br> IF (anomaly_count &gt; 0) THEN<br> — Call external function to send Slack notification<br> CALL send_slack_alert(<br> ‘sales-alerts’,<br> anomaly_count || ‘ anomalous transactions detected’<br> );<br> — Log to audit table<br> INSERT INTO anomaly_log (detected_at, count, channel)<br> VALUES (CURRENT_TIMESTAMP(), anomaly_count, ‘sales’);<br> END IF;<br> END;</p><h3>4. Complex Orchestration with Dependencies</h3><p>While Dynamic Tables handle simple linear pipelines automatically, complex orchestration scenarios — where you need conditional branching, parallel execution with synchronization points, error handling, retry logic, or finalizer steps — require Task graphs.</p><h3>5. Fine-Grained Schedule Control</h3><p>Dynamic Tables let you specify a target lag (e.g., “refresh within 5 minutes of changes”), but you cannot precisely control when refreshes occur. Tasks give you exact scheduling: run at 2 AM, run only on weekdays, run on the first of each month. This is critical for pipelines with business-hour constraints, maintenance windows, or regulatory timing requirements.</p><h3>6. Multi-Statement Transactions</h3><p>Tasks can execute multi-statement transactions within a BEGIN…END block, ensuring atomicity across multiple operations. Dynamic Tables are limited to a single SELECT statement.</p><h3>7. Custom CDC Logic (SCD Type 2, Audit Trails)</h3><p>While Dynamic Tables can implement some SCD patterns, complex CDC logic — where you need to inspect METADATA$ACTION and METADATA$ISUPDATE to make different decisions for inserts vs. updates vs. deletes — requires streams consumed by tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*KwYBuRk2WNVu-S9VAd65Xg.jpeg" /></figure><h3>When to Choose Dynamic Tables</h3><p>Dynamic Tables are the better choice when:</p><p>· Your transformation is a pure SQL query (SELECT with joins, aggregations, window functions).</p><p>· You want Snowflake to manage orchestration and refresh scheduling automatically.</p><p>· You prefer a declarative approach and want to minimize pipeline maintenance.</p><p>· Your pipeline is a chain of simple transformations (raw → staging → curated → analytics).</p><p>· You do not need procedural logic, stored procedures, or external integrations.</p><p>· You want the simplicity of “just define the query and let Snowflake handle the rest.”</p><h3>Comparison Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*CajJ_RzU8B5GDyPWpwObig.png" /></figure><h3>Part 5: Real-World Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*FjH0oLe_bXHim4a1Dy7myQ.jpeg" /></figure><h3>Use Case 1: Real-Time Fraud Detection Pipeline</h3><p>A financial services company needs to detect potentially fraudulent transactions in near-real-time. Transactions flow in continuously via Snowpipe Streaming, and the system must score each transaction, flag suspicious ones, and alert the fraud team — all within seconds of arrival.</p><p>Why Streams &amp; Tasks: This requires calling a scoring model (external function), conditional logic (alert only if score exceeds threshold), and external integrations (sending alerts). Dynamic Tables cannot do any of this.</p><p>— Landing table for raw transactions<br> CREATE TABLE raw_transactions (<br> txn_id STRING,<br> card_number STRING,<br> merchant_id STRING,<br> amount DECIMAL(12,2),<br> currency STRING,<br> location VARIANT, — {lat, lon, city, country}<br> timestamp TIMESTAMP_NTZ<br> );<br> <br> — Append-only stream (transactions are never updated)<br> CREATE STREAM txn_stream<br> ON TABLE raw_transactions<br> APPEND_ONLY = TRUE;<br> <br> — Fraud scoring task<br> CREATE OR REPLACE TASK score_transactions<br> USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = ‘MEDIUM’<br> SCHEDULE = ‘1 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘txn_stream’)<br> AS<br> BEGIN<br> — Score transactions using ML model via external function<br> INSERT INTO scored_transactions<br> SELECT<br> txn_id, card_number, merchant_id, amount, currency,<br> location, timestamp,<br> fraud_score_model(card_number, merchant_id, amount,<br> location:lat::FLOAT, location:lon::FLOAT,<br> timestamp) AS fraud_score,<br> CURRENT_TIMESTAMP() AS scored_at<br> FROM txn_stream;<br> <br> — Flag high-risk transactions<br> INSERT INTO fraud_alerts (txn_id, fraud_score, alert_time)<br> SELECT txn_id, fraud_score, CURRENT_TIMESTAMP()<br> FROM scored_transactions<br> WHERE fraud_score &gt; 0.85<br> AND scored_at &gt; DATEADD(‘minute’, -2, CURRENT_TIMESTAMP());<br> <br> — Send alerts for critical cases<br> LET critical_count INT := (<br> SELECT COUNT(*) FROM fraud_alerts<br> WHERE alert_time &gt; DATEADD(‘minute’, -2, CURRENT_TIMESTAMP())<br> AND fraud_score &gt; 0.95<br> );<br> <br> IF (critical_count &gt; 0) THEN<br> CALL notify_fraud_team(critical_count);<br> END IF;<br> END;<br> <br> ALTER TASK score_transactions RESUME;</p><h3>Use Case 2: Data Warehouse ETL with Quality Gates</h3><p>An e-commerce company maintains a dimensional data warehouse. Data flows from operational systems into a staging layer, passes through quality checks, transforms into dimensional models, and populates fact tables. The pipeline has strict quality gates — if data quality checks fail, downstream processing halts and the data engineering team is notified.</p><p>Why Streams &amp; Tasks: The quality gate pattern (stop processing on failure, notify, quarantine bad data) requires conditional logic and error handling that Dynamic Tables cannot provide.</p><p>— Root task: Check for new data and validate<br> CREATE OR REPLACE TASK etl_validate<br> WAREHOUSE = etl_wh<br> SCHEDULE = ’10 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘stg_orders_stream’)<br> AS<br> BEGIN<br> — Run validation rules<br> CREATE OR REPLACE TEMP TABLE validation_results AS<br> SELECT<br> ‘null_customer’ AS rule_name,<br> COUNT(*) AS violations<br> FROM stg_orders_stream<br> WHERE customer_id IS NULL<br> AND METADATA$ACTION = ‘INSERT’<br> UNION ALL<br> SELECT<br> ‘negative_amount’,<br> COUNT(*)<br> FROM stg_orders_stream<br> WHERE amount &lt; 0<br> AND METADATA$ACTION = ‘INSERT’<br> UNION ALL<br> SELECT<br> ‘future_date’,<br> COUNT(*)<br> FROM stg_orders_stream<br> WHERE order_date &gt; CURRENT_DATE()<br> AND METADATA$ACTION = ‘INSERT’;<br> <br> — Check if any violations exceed threshold<br> LET total_violations INT := (<br> SELECT SUM(violations) FROM validation_results<br> );<br> <br> IF (total_violations &gt; 100) THEN<br> — Quarantine bad records<br> INSERT INTO quarantine_orders<br> SELECT *, CURRENT_TIMESTAMP(), ‘validation_failed’<br> FROM stg_orders_stream<br> WHERE METADATA$ACTION = ‘INSERT’;<br> <br> — This will cause dependent tasks to not run<br> — because the stream will be empty after consumption<br> CALL send_alert(‘Data quality threshold exceeded: ‘<br> || total_violations || ‘ violations’);<br> ELSE<br> — Move valid data to processing stage<br> INSERT INTO processing_orders<br> SELECT * FROM stg_orders_stream<br> WHERE METADATA$ACTION = ‘INSERT’;<br> END IF;<br> END;<br> <br> — Dependent task: Only runs if validate task succeeds<br> CREATE OR REPLACE TASK etl_transform<br> WAREHOUSE = etl_wh<br> AFTER etl_validate<br> AS<br> CALL transform_orders_to_dimensional_model();<br> <br> — Dependent task: Load fact table<br> CREATE OR REPLACE TASK etl_load_facts<br> WAREHOUSE = etl_wh<br> AFTER etl_transform<br> AS<br> CALL load_fact_orders();<br> <br> — Finalizer: Always runs, handles success or failure<br> CREATE OR REPLACE TASK etl_finalizer<br> WAREHOUSE = etl_wh<br> FINALIZE = etl_validate<br> AS<br> BEGIN<br> INSERT INTO etl_audit_log<br> SELECT<br> ‘order_pipeline’,<br> CURRENT_TIMESTAMP(),<br> SYSTEM$TASK_RUNTIME_INFO(‘CURRENT_ROOT_TASK_UUID’),<br> IFF(SYSTEM$TASK_RUNTIME_INFO(‘CURRENT_TASK_GRAPH_RUN_GROUP_ID’)<br> IS NOT NULL, ‘COMPLETED’, ‘FAILED’);<br> END;</p><h3>Use Case 3: Multi-Tenant Data Isolation</h3><p>A SaaS platform needs to maintain separate data products for each tenant. When shared source data changes, tenant-specific views must be updated with their authorized subset. Each tenant has different transformation rules and delivery schedules.</p><p>Why Streams &amp; Tasks: The per-tenant conditional logic, different schedules for different tenants, and the need to iterate over a dynamic list of tenants requires procedural control that Dynamic Tables cannot provide.</p><p>— Procedure called by the task to process each tenant<br> CREATE OR REPLACE PROCEDURE process_tenant_data(tenant_id STRING)<br> RETURNS STRING<br> LANGUAGE SQL<br> AS<br> BEGIN<br> — Get tenant-specific configuration<br> LET config VARIANT := (<br> SELECT config FROM tenant_configs WHERE id = :tenant_id<br> );<br> <br> — Apply tenant-specific transformations<br> MERGE INTO IDENTIFIER(‘tenant_’ || :tenant_id || ‘.analytics’) tgt<br> USING (<br> SELECT * FROM shared_events_stream<br> WHERE METADATA$ACTION = ‘INSERT’<br> AND account_id = :tenant_id<br> ) src ON tgt.event_id = src.event_id<br> WHEN NOT MATCHED THEN INSERT<br> (event_id, event_type, payload, processed_at)<br> VALUES (src.event_id, src.event_type, src.payload,<br> CURRENT_TIMESTAMP());<br> <br> RETURN ‘Processed data for tenant: ‘ || :tenant_id;<br> END;<br> <br> — Task that processes all active tenants<br> CREATE OR REPLACE TASK process_all_tenants<br> WAREHOUSE = multi_tenant_wh<br> SCHEDULE = ‘5 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘shared_events_stream’)<br> AS<br> BEGIN<br> LET tenant_cursor CURSOR FOR<br> SELECT tenant_id FROM active_tenants;<br> <br> FOR tenant IN tenant_cursor DO<br> CALL process_tenant_data(tenant.tenant_id);<br> END FOR;<br> END;<br> <br> ALTER TASK process_all_tenants RESUME;</p><h3>Use Case 4: Event Sourcing and Audit Trail</h3><p>A healthcare application requires a complete, immutable audit trail of all changes to patient records for regulatory compliance. Every change must be captured with who made it, when, and what the before/after values were.</p><p>— Stream captures all changes including updates and deletes<br> CREATE STREAM patient_audit_stream<br> ON TABLE patient_records;<br> <br> — Task builds immutable audit trail<br> CREATE OR REPLACE TASK build_audit_trail<br> WAREHOUSE = compliance_wh<br> SCHEDULE = ‘1 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘patient_audit_stream’)<br> AS<br> INSERT INTO patient_audit_trail (<br> audit_id,<br> patient_id,<br> change_type,<br> field_changes,<br> changed_by,<br> changed_at,<br> row_version<br> )<br> SELECT<br> UUID_STRING(),<br> patient_id,<br> CASE<br> WHEN METADATA$ACTION = ‘INSERT’ AND NOT METADATA$ISUPDATE THEN ‘CREATE’<br> WHEN METADATA$ACTION = ‘INSERT’ AND METADATA$ISUPDATE THEN ‘UPDATE_NEW’<br> WHEN METADATA$ACTION = ‘DELETE’ AND METADATA$ISUPDATE THEN ‘UPDATE_OLD’<br> WHEN METADATA$ACTION = ‘DELETE’ AND NOT METADATA$ISUPDATE THEN ‘DELETE’<br> END,<br> OBJECT_CONSTRUCT(*), — Capture all field values<br> last_modified_by,<br> last_modified_at,<br> METADATA$ROW_ID<br> FROM patient_audit_stream;<br> <br> ALTER TASK build_audit_trail RESUME;</p><h3>Use Case 5: Inventory Synchronization Across Systems</h3><p>A retail company needs to synchronize inventory levels between their Snowflake data warehouse and external systems (ERP, POS, e-commerce platform). When inventory changes in Snowflake (based on sales, returns, and stock adjustments), the changes must be pushed to external systems via API calls.</p><p>— Stream on inventory table<br> CREATE STREAM inventory_changes<br> ON TABLE warehouse_inventory;<br> <br> — Task to sync inventory to external systems<br> CREATE OR REPLACE TASK sync_inventory_external<br> WAREHOUSE = integration_wh<br> SCHEDULE = ‘2 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘inventory_changes’)<br> AS<br> BEGIN<br> — Prepare change payload for external API<br> CREATE OR REPLACE TEMP TABLE inventory_payload AS<br> SELECT<br> sku,<br> warehouse_id,<br> new_quantity,<br> change_reason,<br> OBJECT_CONSTRUCT(<br> ‘sku’, sku,<br> ‘warehouse’, warehouse_id,<br> ‘quantity’, new_quantity,<br> ‘timestamp’, CURRENT_TIMESTAMP()::STRING<br> ) AS api_payload<br> FROM (<br> SELECT<br> sku,<br> warehouse_id,<br> quantity AS new_quantity,<br> last_change_reason AS change_reason<br> FROM inventory_changes<br> WHERE METADATA$ACTION = ‘INSERT’ — Net new state<br> );<br> <br> — Call external function to push to ERP<br> INSERT INTO sync_results<br> SELECT<br> sku,<br> warehouse_id,<br> push_to_erp(api_payload) AS erp_response,<br> CURRENT_TIMESTAMP()<br> FROM inventory_payload;<br> <br> — Call external function to push to e-commerce<br> INSERT INTO sync_results<br> SELECT<br> sku,<br> warehouse_id,<br> push_to_ecommerce(api_payload) AS ecom_response,<br> CURRENT_TIMESTAMP()<br> FROM inventory_payload;<br> <br> — Log sync completion<br> INSERT INTO sync_log (sync_type, record_count, completed_at)<br> VALUES (‘inventory’,<br> (SELECT COUNT(*) FROM inventory_payload),<br> CURRENT_TIMESTAMP());<br> END;<br> <br> ALTER TASK sync_inventory_external RESUME;</p><h3>Part 6: Best Practices and Operational Considerations</h3><h3>Stream Management</h3><p>· Monitor stream staleness: Set up alerts if streams approach their retention window without being consumed. A stale stream must be recreated, and you may lose change data.</p><p>· Use append-only streams for insert-only workloads: They have lower overhead and simpler semantics when you know data will never be updated or deleted.</p><p>· Consider stream on views for filtered CDC: If you only need changes to a subset of rows, create a view with the filter and stream on the view.</p><p>· Multiple streams for multiple consumers: Create separate streams for independent downstream processes so they can advance at their own pace.</p><p>· SHOW_INITIAL_ROWS for bootstrapping: When setting up a new pipeline, use SHOW_INITIAL_ROWS = TRUE to include existing data as initial inserts.</p><h3>Task Management</h3><p>· Use serverless tasks for variable workloads: If your task runs intermittently or has unpredictable compute needs, serverless tasks avoid paying for idle warehouse time.</p><p>· Always use WHEN clauses: Avoid running tasks when there is no work to do. SYSTEM$STREAM_HAS_DATA() checks are essentially free (cloud services layer).</p><p>· Resume tasks in dependency order: When activating a task graph, resume child tasks first, then the root task last. Suspend in reverse order (root first).</p><p>· Monitor with TASK_HISTORY: Use the TASK_HISTORY table function and INFORMATION_SCHEMA views to track execution history, failures, and duration trends.</p><p>· Set appropriate timeouts: Use the USER_TASK_TIMEOUT_MS parameter to prevent runaway tasks from consuming resources indefinitely.</p><p>· Use finalizer tasks for cleanup: Always include a finalizer task in production DAGs for logging, alerting, and cleanup regardless of success or failure.</p><h3>Error Handling Patterns</h3><p>— Robust task with error handling<br> CREATE OR REPLACE TASK robust_pipeline<br> WAREHOUSE = etl_wh<br> SCHEDULE = ‘5 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘source_stream’)<br> AS<br> BEGIN<br> BEGIN<br> — Main processing logic<br> INSERT INTO target_table<br> SELECT transform_data(raw_data)<br> FROM source_stream<br> WHERE METADATA$ACTION = ‘INSERT’;<br> <br> EXCEPTION<br> WHEN OTHER THEN<br> — Log the error<br> INSERT INTO error_log (task_name, error_message, error_time)<br> VALUES (‘robust_pipeline’, SQLERRM, CURRENT_TIMESTAMP());<br> <br> — Send alert<br> CALL send_alert(‘Pipeline failure: ‘ || SQLERRM);<br> <br> — Re-raise to mark task as failed<br> RAISE;<br> END;<br> END;</p><h3>Cost Optimization</h3><p>· Right-size warehouses: Monitor task execution times and adjust warehouse sizes. Over-provisioned warehouses waste money; under-provisioned ones cause SLA breaches.</p><p>· Batch micro-tasks: If you have many small operations, combine them into a single task rather than running many parallel tasks that each start a warehouse.</p><p>· Use AUTO_SUSPEND aggressively: For user-managed warehouse tasks, set AUTO_SUSPEND to 60 seconds or less to minimize idle compute costs.</p><p>· Monitor with SERVERLESS_TASK_HISTORY: For serverless tasks, track credit consumption per task to identify expensive operations.</p><p>· Consider Dynamic Tables for simple transformations: If your pipeline is a pure SQL transformation without procedural logic, Dynamic Tables may be more cost-effective as Snowflake optimizes refresh scheduling.</p><h3>Part 7: Monitoring and Observability</h3><p>Production pipelines require robust monitoring. Snowflake provides several mechanisms to observe stream and task behavior:</p><p>— Check stream status and offset<br> SHOW STREAMS LIKE ‘orders%’;<br> <br> — Verify stream has unconsumed data<br> SELECT SYSTEM$STREAM_HAS_DATA(‘orders_stream’);<br> <br> — View task execution history (last 24 hours)<br> SELECT *<br> FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(<br> SCHEDULED_TIME_RANGE_START =&gt; DATEADD(‘hour’, -24, CURRENT_TIMESTAMP()),<br> RESULT_LIMIT =&gt; 100<br> ))<br> ORDER BY SCHEDULED_TIME DESC;<br> <br> — Check for failed task runs<br> SELECT<br> NAME,<br> STATE,<br> ERROR_CODE,<br> ERROR_MESSAGE,<br> SCHEDULED_TIME,<br> COMPLETED_TIME,<br> DATEDIFF(‘second’, QUERY_START_TIME, COMPLETED_TIME) AS duration_sec<br> FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY())<br> WHERE STATE = ‘FAILED’<br> AND SCHEDULED_TIME &gt; DATEADD(‘day’, -7, CURRENT_TIMESTAMP())<br> ORDER BY SCHEDULED_TIME DESC;<br> <br> — Monitor task graph execution<br> SELECT<br> ROOT_TASK_ID,<br> GRAPH_RUN_GROUP_ID,<br> NAME,<br> STATE,<br> SCHEDULED_TIME,<br> COMPLETED_TIME<br> FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY())<br> WHERE ROOT_TASK_ID = ‘&lt;root_task_id&gt;’<br> ORDER BY GRAPH_RUN_GROUP_ID DESC, SCHEDULED_TIME;<br> <br> — Track serverless task credit usage<br> SELECT<br> TASK_NAME,<br> SUM(CREDITS_USED) AS total_credits,<br> COUNT(*) AS execution_count,<br> AVG(CREDITS_USED) AS avg_credits_per_run<br> FROM SNOWFLAKE.ACCOUNT_USAGE.SERVERLESS_TASK_HISTORY<br> WHERE START_TIME &gt; DATEADD(‘day’, -30, CURRENT_TIMESTAMP())<br> GROUP BY TASK_NAME<br> ORDER BY total_credits DESC;</p><h3>Part 8: Migrating Between Streams/Tasks and Dynamic Tables</h3><p>As your pipeline needs evolve, you may need to migrate between approaches. Here is guidance for both directions:</p><h3>Migrating from Streams/Tasks to Dynamic Tables</h3><p>Consider migration when:</p><p>· Your task contains only a single SELECT-based transformation (no procedural logic).</p><p>· You spend significant time managing task schedules and stream health.</p><p>· Your transformation is a simple MERGE that could be expressed as a SELECT.</p><p>· You want Snowflake to automatically optimize refresh frequency.</p><p>— BEFORE: Stream + Task approach<br> CREATE STREAM sales_stream ON TABLE raw_sales;<br> <br> CREATE TASK aggregate_sales<br> WAREHOUSE = wh<br> SCHEDULE = ‘5 MINUTE’<br> WHEN SYSTEM$STREAM_HAS_DATA(‘sales_stream’)<br> AS<br> MERGE INTO daily_sales_summary tgt<br> USING (<br> SELECT<br> sale_date,<br> region,<br> SUM(amount) AS total_sales,<br> COUNT(*) AS transaction_count<br> FROM sales_stream<br> WHERE METADATA$ACTION = ‘INSERT’<br> GROUP BY sale_date, region<br> ) src ON tgt.sale_date = src.sale_date AND tgt.region = src.region<br> WHEN MATCHED THEN UPDATE SET<br> tgt.total_sales = tgt.total_sales + src.total_sales,<br> tgt.transaction_count = tgt.transaction_count + src.transaction_count<br> WHEN NOT MATCHED THEN INSERT VALUES<br> (src.sale_date, src.region, src.total_sales, src.transaction_count);<br> <br> <br> — AFTER: Dynamic Table (simpler, Snowflake manages refresh)<br> CREATE OR REPLACE DYNAMIC TABLE daily_sales_summary<br> TARGET_LAG = ‘5 minutes’<br> WAREHOUSE = wh<br> AS<br> SELECT<br> sale_date,<br> region,<br> SUM(amount) AS total_sales,<br> COUNT(*) AS transaction_count<br> FROM raw_sales<br> GROUP BY sale_date, region;</p><h3>Keeping Streams/Tasks When Dynamic Tables Cannot Replace Them</h3><p>Do not attempt migration when your pipeline requires any of: stored procedure calls, external function invocations, multi-statement transactions, non-deterministic logic, conditional execution, error handling with custom recovery, or interactions with external systems. These capabilities are exclusive to the imperative Streams and Tasks model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8hjUMXK2lFnDsTHkBpMCMw.jpeg" /></figure><h3>Conclusion</h3><p>Snowflake Streams and Tasks represent the platform’s most powerful and flexible tools for building data pipelines. Streams provide efficient, low-overhead change data capture that tracks every insert, update, and delete at the row level. Tasks provide robust scheduling and orchestration, from simple recurring jobs to complex multi-step DAGs with conditional execution and error handling.</p><p>While Dynamic Tables offer a compelling declarative alternative for straightforward transformations, Streams and Tasks remain indispensable for scenarios requiring:</p><p>· Procedural logic and stored procedures</p><p>· External integrations and API calls</p><p>· Complex orchestration with quality gates and error handling</p><p>· Fine-grained scheduling control</p><p>· Multi-statement atomic transactions</p><p>· Custom CDC patterns like SCD Type 2</p><p>· Event-driven alerting and notifications</p><p>The choice between Streams/Tasks and Dynamic Tables is not binary — many production architectures use both. Use Dynamic Tables for simple, declarative transformations where Snowflake’s automatic refresh optimization adds value. Use Streams and Tasks for complex, procedural pipelines where you need full control over execution logic, error handling, and external integrations.</p><p>By mastering both approaches and understanding their respective strengths, you can build data platforms that are both powerful and maintainable — choosing the right tool for each specific pipeline requirement rather than forcing a one-size-fits-all solution.</p><h3>Appendix: Quick Reference</h3><h3>Essential Stream Commands</h3><p>— Create a standard stream<br> CREATE STREAM my_stream ON TABLE my_table;<br> <br> — Create an append-only stream<br> CREATE STREAM my_stream ON TABLE my_table APPEND_ONLY = TRUE;<br> <br> — Check if stream has data<br> SELECT SYSTEM$STREAM_HAS_DATA(‘my_stream’);<br> <br> — Show stream details<br> SHOW STREAMS IN SCHEMA my_db.my_schema;<br> DESCRIBE STREAM my_stream;<br> <br> — Drop a stream<br> DROP STREAM my_stream;</p><h3>Essential Task Commands</h3><p>— Create a scheduled task<br> CREATE TASK my_task<br> WAREHOUSE = wh<br> SCHEDULE = ‘5 MINUTE’<br> AS &lt;sql&gt;;<br> <br> — Create a serverless task<br> CREATE TASK my_task<br> USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = ‘XSMALL’<br> SCHEDULE = ‘5 MINUTE’<br> AS &lt;sql&gt;;<br> <br> — Create a child task<br> CREATE TASK child_task<br> WAREHOUSE = wh<br> AFTER parent_task<br> AS &lt;sql&gt;;<br> <br> — Resume/suspend tasks<br> ALTER TASK my_task RESUME;<br> ALTER TASK my_task SUSPEND;<br> <br> — Execute a task manually (for testing)<br> EXECUTE TASK my_task;<br> <br> — View task history<br> SELECT * FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY());<br> <br> — Show task dependencies<br> SHOW TASKS IN SCHEMA my_db.my_schema;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d4f70ca734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Building Cortex Code Skills:
 A Practical Guide for Data Engineers]]></title>
            <link>https://medium.com/@aarongmoore_88179/building-cortex-code-skills-a-practical-guide-for-data-engineers-0f3eeba43055?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3eeba43055</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 01 May 2026 16:14:04 GMT</pubDate>
            <atom:updated>2026-05-01T16:14:04.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*l0pHbdB6HUFRXrXafnoI2Q.jpeg" /></figure><h3>Introduction</h3><p>Every data engineer knows the feeling: you have built the same dbt scaffolding for the fifth time this quarter, manually re-typed the same Snowflake stored-procedure boilerplate, or walked a teammate through the same pipeline debugging workflow over Slack. These repetitive patterns are where organizations silently hemorrhage engineering hours.</p><p>Cortex Code, Snowflake’s AI-powered CLI coding assistant, introduces a feature called Skills that directly addresses this problem. Skills are reusable, shareable instruction sets that encode your team’s hard-won workflows, best practices, and domain knowledge into something an AI assistant can execute consistently. Think of them as runbooks that the AI actually follows, not just reads.</p><p>In this article, we will cover what Skills are, why they matter for data engineering teams specifically, and walk through practical examples you can adapt to your own work. By the end, you will have the knowledge to build your first Skill and a clear understanding of why this capability is set to change how data teams operate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ardbp4DC0ZzkGnU71t9DxA.jpeg" /></figure><h3>What Are Cortex Code Skills?</h3><p>At their core, Skills are Markdown files with structured frontmatter that guide Cortex Code’s behavior for specific tasks. When you invoke a Skill using the $ prefix (for example, $optimize-query), the AI loads that Skill’s instructions and follows a defined workflow with built-in checkpoints, guardrails, and stopping points.</p><p>A Skill consists of:</p><p>· A SKILL.md file containing frontmatter metadata and workflow instructions</p><p>· Optional template files for code scaffolding</p><p>· Optional reference documents for domain-specific knowledge</p><p>· Optional Python scripts for custom tooling</p><p>Here is the minimal structure:</p><p>my-skill/</p><p>SKILL.md # Required: main skill file</p><p>templates/ # Optional: code templates</p><p>references/ # Optional: reference docs</p><p>scripts/ # Optional: helper scripts</p><p>Skills can live at the project level (inside .cortex/skills/ in your repo), at the global level (~/.snowflake/cortex/skills/ on your machine), or be synced from remote Git repositories. This means a team lead can publish Skills centrally, and every engineer on the team gets the same consistent workflows.</p><h3>Why Skills Matter: The Case for Encoded Expertise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*oW_LIxssl8CUN-tpYe_Ogw.jpeg" /></figure><h3>The Problem with Tribal Knowledge</h3><p>Data engineering teams accumulate enormous amounts of institutional knowledge: how to structure incremental models, which Snowflake session parameters to set for large merges, how to debug a stuck dynamic table refresh, the exact sequence for safely deploying a breaking schema change. This knowledge typically lives in three places: individual engineers’ heads, scattered Confluence pages, or that one Slack thread from 2023.</p><p>When a senior engineer leaves, that knowledge walks out the door. When a new hire joins, they spend weeks rediscovering patterns that the team already solved. Skills provide a fourth, better option: encode the knowledge directly into the tool that engineers use every day.</p><h3>Consistency at Scale</h3><p>Without Skills, every engineer interacting with Cortex Code provides their own prompts and gets slightly different results. One person’s “create a dbt model” might include tests and documentation; another’s might not. Skills standardize the output. When your team invokes $new-dbt-model, everyone gets the same structure, the same test coverage, the same documentation format, because the Skill defines the workflow.</p><h3>AI Guardrails for Production Systems</h3><p>Data engineers work with production systems where mistakes cost real money and time. Skills include explicit stopping points where the AI must pause and get human approval before proceeding. This is not a nice-to-have; it is a fundamental safety mechanism. A Skill for database migrations can enforce that the AI presents the migration plan, waits for approval, then executes, rather than autonomously running ALTER TABLE statements against production.</p><h3>Compounding Returns</h3><p>Every Skill you build is an investment that pays dividends every time it is invoked. A Skill that saves 20 minutes per use across a team of 8 engineers who each use it twice a week saves over 270 hours per year. More importantly, it eliminates an entire category of errors and inconsistencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*jhhQ-gvK3OLAt4Rg9lL_Zg.jpeg" /></figure><h3>Why Data Engineers Should Care</h3><p>Cortex Code has deep, native integration with the tools data engineers use daily. Skills can leverage:</p><p>· Direct SQL execution against Snowflake with connection management</p><p>· dbt workflows via the built-in fdbt tool for fast model parsing and lineage analysis</p><p>· Data diff capabilities for comparing tables and validating migrations</p><p>· Semantic model validation via Cortex Analyst</p><p>· Object discovery for searching tables, views, and schemas</p><p>This means Skills for data engineering are not abstract prompt wrappers. They orchestrate real tools: running SQL, parsing dbt manifests, comparing table contents, and validating semantic models. The Skill is the workflow logic; Cortex Code provides the execution engine.</p><p>Here are the domains where Skills have the highest impact for data engineering teams:</p><p>· Pipeline scaffolding: Creating new dbt models, sources, and staging layers with consistent patterns</p><p>· Data quality workflows: Automated validation, profiling, and anomaly detection</p><p>· Migration playbooks: Schema changes, platform migrations, and version upgrades</p><p>· Incident response: Debugging stale data, failed refreshes, and performance regressions</p><p>· Cost optimization: Warehouse sizing analysis, query profiling, and credit monitoring</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bnLagaeNkO3m2R6UiaClUA.jpeg" /></figure><h3>Anatomy of a Well-Built Skill</h3><p>Before diving into examples, let us understand the key components that make a Skill effective. Every production-quality Skill should include these elements.</p><h3>Frontmatter</h3><p>The frontmatter is YAML metadata at the top of SKILL.md. It tells Cortex Code when to activate the Skill and what tools it needs.</p><p>— -</p><p>name: my-skill-name</p><p>description: “Purpose of the skill. Use when: specific scenarios.</p><p>Triggers: keyword1, keyword2, keyword3.”</p><p>tools: [“bash”, “sql_execute”, “edit”] # Optional: recommended tools</p><p>— -</p><p>The description field is critical. It should clearly state the purpose, the situations that trigger it, and specific keywords. This is how Cortex Code decides whether to suggest the Skill.</p><h3>Workflow Steps with Stopping Points</h3><p>The body of the Skill defines a numbered workflow. Each major step should include what the AI should do and when it must stop for human approval.</p><p>## Workflow</p><p>### Step 1: Analyze Current State</p><p>Run `fdbt info` to understand the dbt project structure.</p><p>List all models in the target directory.</p><p>### Step 2: Present Plan</p><p>Show the user what changes will be made.</p><p>**STOP**: Wait for user approval before making any changes.</p><p>### Step 3: Implement Changes</p><p>Apply the approved changes to the model files.</p><p>Stopping points are what separate a Skill from a naive prompt. They enforce human-in-the-loop control at exactly the moments where oversight matters most.</p><h3>Error Handling</h3><p>Good Skills anticipate failure. Rather than letting the AI improvise when something goes wrong, define explicit error-handling paths.</p><p>### Step 3: Execute Migration</p><p>Run the migration SQL against the target schema.</p><p>**If error occurs:**</p><p>- Compilation error: Show the error, suggest fix, wait for approval</p><p>- Permission denied: List required grants, ask user to verify access</p><p>- Timeout: Suggest breaking into smaller batches</p><ul><li>Unknown error: Present full error output, ask user for guidance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*o9lywl2MAOsr8Ro5iYz0QQ.jpeg" /></figure><h3>Practical Example 1: dbt Model Scaffolding Skill</h3><p>Let us build a real Skill that data engineers will use frequently: scaffolding new dbt staging models with tests, documentation, and consistent naming conventions.</p><h3>The Problem</h3><p>Every time an engineer creates a new staging model, they need to: create the SQL file with the correct naming convention, add a YAML schema file with column descriptions and tests, ensure the source is defined, and follow the team’s style guide. Without a Skill, each engineer does this slightly differently.</p><h3>The Skill: scaffold-staging-model</h3><p>— -</p><p>name: scaffold-staging-model</p><p>description: “Create a new dbt staging model with tests and docs.</p><p>Use when: creating staging models, new source tables, stg_ models.</p><p>Triggers: staging model, new stg, scaffold model, add source.”</p><p>tools: [“bash”, “edit”, “write”]</p><p>— -</p><p># Scaffold dbt Staging Model</p><p>## Workflow</p><p>### Step 1: Gather Requirements</p><p>Ask the user for:</p><p>1. **Source name**: The raw source (e.g., “stripe”, “salesforce”)</p><p>2. **Table name**: The specific table (e.g., “payments”, “accounts”)</p><p>3. **Key columns**: Primary key and important business columns</p><p>STOP: Confirm requirements before proceeding.</p><p>### Step 2: Discover Project Structure</p><p>Run `fdbt info` to find:</p><p>- The staging directory path (typically models/staging/)</p><p>- Existing source definitions in _sources.yml files</p><p>- Naming conventions already in use</p><p>If the source is already defined, note it.</p><p>If not, flag that we need to add it.</p><p>### Step 3: Present the Plan</p><p>Show the user exactly which files will be created or modified:</p><p>- models/staging/{source}/stg_{source}__{table}.sql</p><p>- models/staging/{source}/_stg_{source}__models.yml</p><p>- models/staging/{source}/_sources.yml (if source is new)</p><p>STOP: Wait for user approval of file plan.</p><p>### Step 4: Create the Model SQL</p><p>Generate the staging model following these conventions:</p><p>- Use a CTE named “source” that selects from {{ source() }}</p><p>- Use a “renamed” CTE for column renaming and casting</p><p>- Final select from the “renamed” CTE</p><p>- Include column-level comments for non-obvious transformations</p><p>### Step 5: Create the Schema YAML</p><p>Generate the schema file with:</p><p>- Model description</p><p>- Column descriptions for every column</p><p>- not_null test on primary key</p><p>- unique test on primary key</p><p>- accepted_values tests where applicable</p><p>### Step 6: Validate</p><p>Run `dbt compile — select stg_{source}__{table}` to verify.</p><p>STOP: Present results. If errors, help debug.</p><p>## Stopping Points</p><p>- After Step 1: Requirements confirmed</p><p>- After Step 3: File plan approved</p><p>- After Step 6: Compilation verified</p><p>This Skill ensures that every staging model across your entire team follows the same pattern. New engineers get the benefit of the team’s conventions without having to learn them first.</p><h3>Practical Example 2: Snowflake Query Performance Analyzer</h3><p>Data engineers frequently need to investigate slow queries. This Skill automates the analysis workflow that experienced engineers follow manually.</p><h3>The Skill: analyze-query-performance</h3><p>— -</p><p>name: analyze-query-performance</p><p>description: “Analyze Snowflake query performance and suggest</p><p>optimizations. Use when: slow query, query optimization,</p><p>performance tuning, warehouse sizing.</p><p>Triggers: slow, performance, optimize, warehouse size.”</p><p>tools: [“sql_execute”, “bash”]</p><p>— -</p><p># Snowflake Query Performance Analyzer</p><p>## Workflow</p><p>### Step 1: Identify the Query</p><p>Ask the user for one of:</p><p>- A query ID from QUERY_HISTORY</p><p>- A SQL statement to analyze</p><p>- A dbt model name to look up</p><p>### Step 2: Gather Execution Metrics</p><p>Query SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY for:</p><p>- Total elapsed time, compilation time, execution time</p><p>- Bytes scanned vs bytes spilled to local/remote storage</p><p>- Partitions scanned vs partitions total</p><p>- Warehouse size used during execution</p><p>Also check QUERY_ACCELERATION_ELIGIBLE if available.</p><p>### Step 3: Analyze the Query Profile</p><p>Look for these common performance issues:</p><p>**Spilling to storage:**</p><p>- Local spill &gt; 0: Consider larger warehouse</p><p>- Remote spill &gt; 0: Definitely needs larger warehouse</p><p>**Partition pruning:**</p><p>- If partitions_scanned / partitions_total &gt; 0.5:</p><p>suggest clustering keys or filter pushdown</p><p>**Compilation time:**</p><p>- If compilation_time &gt; 5s: Check for complex views,</p><p>deep CTE chains, or excessive column counts</p><p>### Step 4: Present Findings</p><p>Summarize findings in a table format:</p><p>| Metric | Value | Assessment |</p><p>Include specific, actionable recommendations.</p><p>STOP: Let user decide which optimizations to pursue.</p><p>### Step 5: Implement (if requested)</p><p>Help implement approved optimizations:</p><p>- Rewrite queries for better pruning</p><p>- Add clustering keys</p><p>- Adjust warehouse configuration</p><p>## Stopping Points</p><p>- After Step 4: Review findings before any changes</p><p>- After Step 5: Verify optimization results</p><h3>Practical Example 3: Pipeline Incident Response</h3><p>When a data pipeline fails at 3 AM, the last thing an on-call engineer needs is to remember the debugging sequence from memory. This Skill encodes the incident response playbook.</p><h3>The Skill: debug-pipeline</h3><p>— -</p><p>name: debug-pipeline</p><p>description: “Debug failed or stale data pipelines.</p><p>Use when: pipeline failure, stale data, task failure,</p><p>dbt run error, dynamic table lag.</p><p>Triggers: pipeline down, data stale, task failed, debug.”</p><p>tools: [“sql_execute”, “bash”, “read”]</p><p>— -</p><p># Pipeline Incident Response</p><p>## Workflow</p><p>### Step 1: Triage</p><p>Ask the user:</p><p>1. What is failing? (dbt model, dynamic table, task, stream)</p><p>2. When did it start? (or when was data last fresh?)</p><p>3. Any recent changes? (deployments, schema changes, grants)</p><p>### Step 2: Gather Evidence</p><p>**For dbt models:**</p><p>- Check dbt run logs in target/ directory</p><p>- Run `fdbt info` to get project context</p><p>- Check QUERY_HISTORY for failed SQL</p><p>**For dynamic tables:**</p><p>- Query DYNAMIC_TABLE_REFRESH_HISTORY for error details</p><p>- Check downstream dependencies for cascade failures</p><p>**For Snowflake tasks:**</p><p>- Query TASK_HISTORY for error messages</p><p>- Check task scheduling and predecessors</p><p>### Step 3: Diagnose</p><p>Common root causes to check:</p><p>- Permission changes (SHOW GRANTS)</p><p>- Schema drift (compare expected vs actual columns)</p><p>- Resource contention (warehouse queue depth)</p><p>- Upstream data issues (source freshness)</p><p>### Step 4: Present Diagnosis</p><p>Provide:</p><p>- Root cause (confirmed or suspected)</p><p>- Evidence supporting the diagnosis</p><p>- Recommended fix with exact commands/SQL</p><p>- Risk assessment of the fix</p><p>STOP: Get approval before applying any fix.</p><p>### Step 5: Apply Fix</p><p>Execute the approved remediation.</p><p>Verify the fix resolved the issue.</p><p>Document what happened for the postmortem.</p><p>## Stopping Points</p><p>- After Step 4: Diagnosis review before any changes</p><p>- After Step 5: Fix verification</p><h3>How to Build Your First Skill: Step by Step</h3><h3>Step 1: Identify a Repeatable Workflow</h3><p>Start by looking at your own work over the past month. What did you do more than twice? What involved multiple steps? What did you explain to someone else? Common candidates include:</p><p>· Setting up a new data source end-to-end</p><p>· Running a data quality audit on a table</p><p>· Investigating cost spikes in warehouse usage</p><p>· Deploying schema changes across environments</p><p>· Onboarding a teammate to a specific pipeline</p><h3>Step 2: Choose the Scope</h3><p>Create the Skill directory at the appropriate level. For team-shared Skills, use the project-level location so they are version-controlled with your code:</p><p># Project-level (shared via git)</p><p>mkdir -p .cortex/skills/my-skill</p><p># Global (personal, all projects)</p><p>mkdir -p ~/.snowflake/cortex/skills/my-skill</p><h3>Step 3: Write the Frontmatter</h3><p>The frontmatter is the most important part to get right. A good description with clear trigger keywords ensures the Skill activates when engineers need it.</p><p>— -</p><p>name: audit-table-quality</p><p>description: “Run a comprehensive data quality audit on a</p><p>Snowflake table. Use when: checking data quality, validating</p><p>a new source, pre-migration validation.</p><p>Triggers: data quality, audit, validate table, check nulls.”</p><p>— -</p><h3>Step 4: Define the Workflow</h3><p>Write numbered steps that the AI will follow. Each step should have a clear action and, where appropriate, a stopping point. Keep these guidelines in mind:</p><p>· Use imperative language: “Run X”, “Check Y”, “Present Z”</p><p>· Include stopping points before any destructive or significant actions</p><p>· Define explicit error handling for known failure modes</p><p>· Keep the total Skill under 500 lines for reliable loading</p><p>· Reference specific tools: sql_execute for Snowflake, fdbt for dbt, bash for CLI commands</p><h3>Step 5: Test Incrementally</h3><p>Invoke your Skill immediately and test each step. Use the /skill command in Cortex Code to manage and verify your Skill is loaded correctly.</p><p># Invoke your skill</p><p>$audit-table-quality Check the ORDERS table in PROD</p><p># If changes are needed, edit and re-invoke</p><p># Skills are loaded fresh each time</p><h3>Step 6: Share with Your Team</h3><p>If the Skill is in .cortex/skills/ within your repository, it ships with your code. Every engineer who clones the repo has access. For cross-repo Skills, use the remote configuration in ~/.snowflake/cortex/skills.json:</p><p>{</p><p>“remote”: [</p><p>{</p><p>“source”: “https://github.com/your-org/cortex-skills&quot;,</p><p>“ref”: “main”,</p><p>“skills”: [{ “name”: “audit-table-quality” }]</p><p>}</p><p>]</p><p>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*fvFtt4TF4_5WZ1qQORuHEA.jpeg" /></figure><h3>Best Practices for Production Skills</h3><h3>1. Always Include Stopping Points</h3><p>Never let a Skill execute destructive operations without a checkpoint. The pattern is: gather information, present a plan, wait for approval, then execute. This applies to any operation that modifies data, schema, or configuration.</p><h3>2. Be Specific About Tools</h3><p>Rather than saying “query the database,” specify “use sql_execute to run the following query against Snowflake.” Rather than “check the dbt project,” specify “run fdbt info to discover the project structure.” Specificity prevents the AI from inventing plausible but incorrect commands.</p><h3>3. Handle Errors Explicitly</h3><p>For every step that involves execution, define what should happen when it fails. Unhandled errors cause the AI to improvise, which is exactly what you do not want in a production workflow.</p><h3>4. Keep Skills Focused</h3><p>A Skill that tries to do everything does nothing well. Build small, composable Skills rather than monolithic ones. A “deploy schema change” Skill can reference a “validate migration” Skill without combining them into one massive workflow.</p><h3>5. Version Control Your Skills</h3><p>Skills in .cortex/skills/ are just files in your repository. They should go through the same code review process as your dbt models or SQL scripts. A bad Skill can cause as much damage as a bad migration script.</p><h3>6. Document the “Why”</h3><p>Include comments in your Skill explaining why certain steps exist. Future maintainers (including future you) need to understand the reasoning. “Check for NULL primary keys because the legacy system occasionally sends NULLs during partial syncs” is far more useful than “Check for NULL primary keys.”</p><h3>Advanced Patterns</h3><h3>Skills with Reference Documents</h3><p>For complex domains, place detailed reference material in a references/ directory. The Skill can instruct the AI to load these on-demand:</p><p>pipeline-migration/</p><p>SKILL.md</p><p>references/</p><p>snowflake-to-databricks-mapping.md</p><p>common-sql-translations.md</p><p>templates/</p><p>target_model_template.sql</p><h3>Skills with Templates</h3><p>Place template files in a templates/ directory for the Skill to use as starting points. This is especially useful for scaffolding Skills where the output structure is well-defined.</p><h3>Skills with Custom Scripts</h3><p>For operations that need custom logic beyond what the AI can do inline, include Python scripts. Use uv for dependency management and always reference scripts with absolute paths:</p><p>## Tools</p><p>### validate_schema.py</p><p>**Usage:** `uv run — project &lt;SKILL_DIR&gt; python &lt;SKILL_DIR&gt;/scripts/validate_schema.py`</p><p>Validates that the proposed schema change is backwards-compatible.</p><p>Reads the current schema from Snowflake and compares against the proposed DDL.</p><h3>The Bigger Picture: How Skills Change Team Dynamics</h3><p>Skills are not just a productivity tool. They represent a shift in how data engineering teams operate.</p><p><strong>Onboarding accelerates.</strong></p><p>A new engineer on day one can invoke $debug-pipeline and follow the same incident response workflow as a ten-year veteran. The Skill does not replace experience, but it ensures the right steps happen in the right order.</p><p><strong>Standards become self-enforcing.</strong></p><p>Instead of writing a style guide that people eventually stop reading, encode it in a Skill. The standard is not documented; it is executed.</p><p><strong>Expertise becomes durable.</strong></p><p>When your best engineer figures out the optimal approach for a complex migration, that approach becomes a Skill. It survives job changes, team reorganizations, and the passage of time.</p><p><strong>AI becomes reliable.</strong></p><p>Without Skills, AI assistance is a coin flip: sometimes brilliant, sometimes wrong in dangerous ways. Skills provide the guardrails that make AI assistance consistent and trustworthy in production contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Cb1I-_EpvV1pDhq9VtU3gg.jpeg" /></figure><h3>Getting Started: Your First Week with Skills</h3><p>Here is a practical roadmap for adopting Skills on your data engineering team:</p><p><strong>Day 1: Audit your workflows</strong></p><p>List every task you do repeatedly. Star the ones that involve multiple steps, multiple tools, or that you have explained to someone else more than once.</p><p><strong>Day 2: Build your first Skill</strong></p><p>Pick the simplest starred item. Follow the step-by-step guide in this article. Aim for a working Skill with 3–5 workflow steps and at least one stopping point.</p><p><strong>Day 3: Test and iterate</strong></p><p>Run the Skill against real scenarios. Identify where the AI goes off-script and add more specific instructions or error handling.</p><p><strong>Day 4: Share with a teammate</strong></p><p>Move the Skill to .cortex/skills/ and push it to your repo. Have a teammate invoke it and collect feedback.</p><p><strong>Day 5: Build a team backlog</strong></p><p>Based on the experience, identify the next five Skills your team should build. Prioritize by frequency of use multiplied by complexity of the workflow.</p><h3>Conclusion</h3><p>Cortex Code Skills transform the relationship between data engineers and AI assistance. Instead of hoping the AI understands your team’s context, you encode that context explicitly. Instead of trusting the AI to make the right decisions autonomously, you define exactly where human judgment is required.</p><p>For data engineering teams specifically, Skills address a persistent challenge: the gap between knowing the right way to do something and consistently doing it that way under the pressure of deadlines, on-call incidents, and growing pipeline complexity.</p><p>The mechanics are simple: a Markdown file, some structured frontmatter, a clear workflow with stopping points. The impact compounds over time as your Skill library grows and your team’s collective expertise becomes embedded in the tools they use every day.</p><p>Start small. Build one Skill this week. Share it with your team. Then build another. The investment pays for itself faster than you might expect.</p><p>— -</p><p>Aaron Moore is a Solutions Engineer at Snowflake specializing in data engineering, Cortex AI, and modern data architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3eeba43055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability in Snowflake: A Data Engineer’s Guide to Knowing What’s Actually Happening in Your…]]></title>
            <link>https://medium.com/@aarongmoore_88179/observability-in-snowflake-a-data-engineers-guide-to-knowing-what-s-actually-happening-in-your-6b10012ed061?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b10012ed061</guid>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 13:44:28 GMT</pubDate>
            <atom:updated>2026-04-24T13:44:28.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Observability in Snowflake: A Data Engineer’s Guide to Knowing What’s Actually Happening in Your Data Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*F5NqVwsTzmB55n5QjeAuyg.jpeg" /></figure><p><em>Why observability is the missing pillar in modern data engineering, what Snowflake offers today, and what the Observe acquisition means for the future.</em></p><p>I have a confession. For the first few years of my data engineering career, observability was an afterthought. I would build pipelines, schedule them, watch them succeed a few times, and move on to the next project. The pipeline was “done.” Sound familiar?</p><p>Then reality hit. A downstream dashboard was showing stale numbers for three days before anyone noticed. A warehouse was auto-resuming every 90 seconds and burning credits like jet fuel. A nightly MERGE was silently producing duplicate rows because a source table’s schema had drifted. In every case, the data was broken long before anyone knew about it.</p><p>That is the core argument for observability in data engineering: the cost of not knowing is always higher than the cost of looking. And if you are building on Snowflake, the platform now offers a surprisingly deep set of native observability capabilities that most data engineers are not fully leveraging.</p><p>This article walks through why observability matters from a data engineering perspective, catalogs the features Snowflake provides today, includes practical SQL examples you can run in your own account, and explores what Snowflake’s acquisition of Observe Inc. signals for the future of the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*A5xFlCvqCpnaJWNBb-5NyA.jpeg" /></figure><h3>Why Observability Matters for Data Engineers</h3><p>In software engineering, observability is a well-established discipline. The “three pillars” — logs, metrics, and traces — are table stakes for any production service. But in data engineering, we have historically gotten by with something much more primitive: did the job succeed or fail?</p><p>That binary view is dangerously insufficient. A pipeline can succeed and still produce wrong data. A query can return results and still be scanning ten times more data than it should. A warehouse can be running and still be wasting thousands of dollars a month. Success and correctness are not the same thing.</p><p>True data observability extends across several dimensions that data engineers need to care about:</p><p>· <strong>Data Quality: </strong>Are the values in my tables correct, complete, and fresh? Are there unexpected NULLs, duplicates, or schema changes?</p><p>· <strong>Pipeline Health: </strong>Are my ETL/ELT jobs running on schedule? Are they taking longer than expected? Are they failing silently?</p><p>· <strong>Performance: </strong>Which queries are slow? Which warehouses are over- or under-provisioned? Where is compute being wasted?</p><p>· <strong>Cost: </strong>How much am I spending, on what, and is it trending in the right direction? Who or what is driving cost increases?</p><p>· <strong>Security and Compliance: </strong>Who is accessing what data? Are policies being enforced? Is sensitive data flowing where it should not?</p><p>· <strong>Lineage: </strong>Where did this data come from? What breaks if I change this table? How does data flow from source to consumption?</p><p>When you frame it this way, observability is not a nice-to-have. It is the connective tissue that lets you operate a data platform with confidence rather than hope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*hK_Blv5g9bAJVbE_B0OQHw.jpeg" /></figure><h3>Snowflake’s Native Observability Features</h3><p>One of the things I appreciate about Snowflake is that observability is not bolted on as a third-party integration. Much of it is built into the platform. Let us walk through the major feature areas.</p><h3>ACCOUNT_USAGE and ORGANIZATION_USAGE Views</h3><p>The SNOWFLAKE database ships with two schemas that are the backbone of Snowflake observability: ACCOUNT_USAGE and ORGANIZATION_USAGE. These are system-managed views that expose metadata about virtually everything happening in your account.</p><p>Key views that data engineers should know intimately:</p><p>· <strong>QUERY_HISTORY: </strong>Every query executed in the account, with execution time, bytes scanned, partitions pruned, warehouse used, and error codes. This is your go-to for performance analysis.</p><p>· <strong>ACCESS_HISTORY: </strong>Tracks read and write operations at the column level. Tells you who accessed what data, when, and how it moved between objects. Essential for compliance auditing and understanding data lineage.</p><p>· <strong>WAREHOUSE_METERING_HISTORY: </strong>Credit consumption by warehouse over time. Combine this with QUERY_HISTORY to identify which queries or users are driving cost.</p><p>· <strong>STORAGE_USAGE: </strong>Tracks storage consumption across databases, including Time Travel and Fail-safe overhead.</p><p>· <strong>LOGIN_HISTORY: </strong>Authentication events, useful for security monitoring and detecting unauthorized access.</p><p>· <strong>TASK_HISTORY: </strong>Execution history for Snowflake Tasks, which is critical if you are using native Snowflake orchestration for your pipelines.</p><p>· <strong>DATA_TRANSFER_HISTORY: </strong>Tracks data movement across regions and clouds, a common source of unexpected costs.</p><p>These views retain data for up to 365 days (for most views), giving you a full year of operational history without any additional tooling. The trick is actually querying them regularly. I recommend building a set of standard monitoring queries and scheduling them as Snowflake Tasks or integrating them with your orchestration tool of choice.</p><p>Here is a practical example — a query to find your top 10 most expensive queries from the past 7 days:</p><p>SELECT<br> query_id,<br> user_name,<br> warehouse_name,<br> execution_status,<br> total_elapsed_time / 1000 AS elapsed_seconds,<br> bytes_scanned / POWER(1024, 3) AS gb_scanned,<br> partitions_scanned,<br> partitions_total,<br> ROUND(partitions_scanned / NULLIF(partitions_total, 0), 2) AS scan_ratio,<br> query_text<br> FROM snowflake.account_usage.query_history<br> WHERE start_time &gt;= DATEADD(day, -7, CURRENT_TIMESTAMP())<br> AND execution_status = ‘SUCCESS’<br> ORDER BY bytes_scanned DESC<br> LIMIT 10;</p><p>That scan_ratio column is one of the most valuable metrics you can monitor. A ratio near 1.0 means the query is scanning almost every partition — a strong signal that clustering keys are missing or the query pattern does not align with how the data is organized. Queries with a low scan ratio are efficiently pruning partitions, which is what you want.</p><h3>Data Quality Monitoring with Data Metric Functions (DMFs)</h3><p>This is one of the more underappreciated features in Snowflake. Data Metric Functions (DMFs) allow you to define data quality checks that run continuously on your tables and views, on a schedule you control.</p><p>Snowflake provides several system DMFs out of the box for common quality dimensions:</p><p>· NULL_COUNT — Count of NULL values in a column</p><p>· DUPLICATE_COUNT — Count of duplicate values</p><p>· UNIQUE_COUNT — Count of distinct values</p><p>· FRESHNESS — How recently the table was updated</p><p>· ROW_COUNT — Number of rows in the table</p><p>You can also write custom DMFs for domain-specific checks — for example, verifying that a revenue column is never negative, or that a date column does not contain future dates. Here is an example of attaching a system DMF and setting an expectation:</p><p>— Attach the FRESHNESS DMF to a critical table<br> ALTER TABLE analytics.core.daily_revenue<br> SET DATA_METRIC_SCHEDULE = ‘TRIGGER_ON_CHANGES’;<br> <br> ALTER TABLE analytics.core.daily_revenue<br> ADD DATA METRIC FUNCTION<br> SNOWFLAKE.CORE.FRESHNESS(analytics.core.daily_revenue)<br> WITH EXPECTATION EXPECTED_FRESHNESS<br> AS EXPECT freshness &lt; 3600; — alert if stale &gt; 1 hour</p><p>DMFs run on serverless compute, so there is no warehouse to manage. Results flow into an event table, and you can set expectations with thresholds that flag violations. Snowflake even supports anomaly detection on DMF results, using historical patterns to automatically flag when a metric drifts outside its predicted range.</p><p>Cortex Data Quality takes this further by using AI to agentically suggest data quality checks based on your metadata and usage patterns. Instead of manually auditing every table to decide what to monitor, the system recommends checks for you.</p><p>As a data engineer, DMFs give you something incredibly valuable: proactive alerting on data quality issues before a stakeholder files a ticket. This is the shift from reactive firefighting to proactive monitoring.</p><h3>Event Tables: Logging, Tracing, and Metrics</h3><p>If you are writing stored procedures, UDFs, or Snowpark code, Snowflake’s event table system gives you structured observability directly in the platform. The system is built on the OpenTelemetry standard, which means the concepts will feel familiar if you have worked with distributed tracing in software engineering.</p><p>Event tables capture three types of data:</p><p>· <strong>Log messages: </strong>Unstructured text entries from your code. Think of these as print statements, but captured in a queryable table.</p><p>· <strong>Trace events: </strong>Structured, attributed events that can be grouped into spans. These let you trace execution across multiple steps of a pipeline or procedure.</p><p>· <strong>Metrics: </strong>CPU and memory utilization metrics generated by Snowflake for your running code.</p><p>Every Snowflake account now comes with a default event table. You control the telemetry level (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE) at the account, database, schema, or individual object level. This granularity is important — you do not want DEBUG-level logging on every UDF in production, but you absolutely want it available when troubleshooting a specific function.</p><p>Setting the telemetry level is straightforward:</p><p>— Enable INFO-level logging for a specific schema<br> ALTER SCHEMA my_db.pipelines<br> SET LOG_LEVEL = ‘INFO’;<br> <br> — Enable trace events for a specific procedure<br> ALTER PROCEDURE my_db.pipelines.load_daily_revenue()<br> SET TRACE_LEVEL = ‘ON_EVENT’;</p><p>For data engineers writing Snowpark pipelines, this is a significant improvement over the old approach of wrapping everything in try/except blocks and hoping your error messages make it to an external log aggregator. You can emit structured trace events that are queryable with SQL, stored alongside your data, and retained according to your policies.</p><h3>Data Lineage</h3><p>Snowflake tracks data lineage natively — both at the object level (table to view to downstream table) and at the column level. This lineage is automatically captured for operations like CREATE TABLE AS SELECT, INSERT, MERGE, UPDATE, and COPY INTO.</p><p>You can visualize lineage in Snowsight through the Lineage tab on any table or view, or query it programmatically using the GET_LINEAGE function and the ACCESS_HISTORY view. The lineage graph also surfaces stored procedures and tasks that created the data movement, giving you a complete picture of how data flows through your orchestration layer.</p><p>From a data engineering perspective, lineage answers critical questions:</p><p>· Impact analysis: “If I change this source table, what downstream objects break?”</p><p>· Root cause analysis: “This dashboard is wrong — where did the bad data originate?”</p><p>· Compliance: “Can I prove that sensitive PII data only flows into authorized tables?”</p><p>· Deprecation: “Is anyone still using this old staging table, or can I safely drop it?”</p><p>Lineage also integrates with Snowflake’s governance features — tags and masking policies propagate through the lineage graph, so you can see where sensitive columns flow and ensure policies follow the data. The Lineage tab in Snowsight even highlights missing or mismatched tags on upstream and downstream columns, letting you remediate governance gaps without writing any SQL.</p><h3>AI Observability</h3><p>With the rise of Cortex AI and generative AI applications built on Snowflake, the platform now includes AI-specific observability through Cortex AI Observability, which went GA in July 2025. This feature lets you evaluate and trace generative AI applications using the LLM-as-a-judge methodology, powered by the TruLens framework.</p><p>Key capabilities include:</p><p>· <strong>Evaluations: </strong>Systematically measure accuracy, relevance, groundedness, and cost of your RAG or summarization applications across different LLMs, prompts, and configurations.</p><p>· <strong>Comparison: </strong>Compare evaluations side-by-side to identify the best configuration for production deployments.</p><p>· <strong>Tracing: </strong>Trace every step of an AI application execution — from input prompt to retrieved context to tool use to final LLM response. Debug individual records and optimize for accuracy, latency, and cost.</p><p>If you are building Cortex Agents or RAG pipelines on Snowflake, this is not optional. AI applications are notoriously difficult to debug — a subtle change in a prompt template or retrieval strategy can silently degrade answer quality. AI Observability gives you the instrumentation to catch these regressions before your users do. And because evaluation results are stored in your Snowflake event table, you can query them with SQL just like any other observability data.</p><h3>Cost Management and Resource Monitoring</h3><p>Observability without cost awareness is incomplete. Snowflake provides several mechanisms for monitoring and controlling spend:</p><p>· <strong>Resource Monitors: </strong>Set credit quotas on warehouses with automatic notifications and suspension when thresholds are reached.</p><p>· <strong>Budgets: </strong>Define credit budgets at the account or custom scope level with spend tracking and alerting.</p><p>· <strong>WAREHOUSE_METERING_HISTORY and METERING_DAILY_HISTORY: </strong>Granular credit consumption data for analysis and chargeback.</p><p>· <strong>Snowsight Cost Management Dashboard: </strong>Visual interface for tracking spend by warehouse, service type, and time period.</p><p>Here is a query I run weekly to spot cost anomalies by warehouse:</p><p>WITH daily_credits AS (<br> SELECT<br> warehouse_name,<br> DATE_TRUNC(‘day’, start_time) AS usage_date,<br> SUM(credits_used) AS credits<br> FROM snowflake.account_usage.warehouse_metering_history<br> WHERE start_time &gt;= DATEADD(day, -30, CURRENT_TIMESTAMP())<br> GROUP BY 1, 2<br> )<br> SELECT<br> warehouse_name,<br> usage_date,<br> credits,<br> AVG(credits) OVER (<br> PARTITION BY warehouse_name<br> ORDER BY usage_date<br> ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING<br> ) AS avg_7d,<br> credits / NULLIF(avg_7d, 0) AS ratio_vs_avg<br> FROM daily_credits<br> WHERE usage_date = CURRENT_DATE() — 1<br> ORDER BY ratio_vs_avg DESC;</p><p>Any warehouse with a ratio_vs_avg significantly above 1.0 warrants investigation. Maybe someone ran an ad-hoc backfill. Maybe a pipeline change is scanning more data than expected. Either way, you want to know about it before the invoice arrives.</p><h3>Trust Center</h3><p>The Snowflake Trust Center provides security-focused observability through automated scanners that evaluate your account against security best practices and CIS benchmarks. It surfaces findings like accounts without MFA, overly permissive network policies, or stale credentials.</p><p>While this is typically an admin concern, data engineers benefit from Trust Center findings too. If your service accounts have security gaps, your pipelines are at risk. Treat Trust Center as the security layer of your observability stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*flArQ-dI8excfJ-Hzv6NPg.jpeg" /></figure><h3>Putting It All Together: The Data Engineer’s Observability Stack on Snowflake</h3><p>Here is how I think about layering these features into a practical observability strategy:</p><p>· <strong>Layer 1 — Data Quality: </strong>Attach DMFs to your critical tables. Set expectations. Configure anomaly detection on freshness and row counts. Monitor the results in Snowsight or query the event table.</p><p>· <strong>Layer 2 — Pipeline Health: </strong>Use TASK_HISTORY and QUERY_HISTORY to monitor pipeline execution. Set alerts on failures, long-running queries, and schedule drift.</p><p>· <strong>Layer 3 — Performance: </strong>Query QUERY_HISTORY for partition pruning ratios, spill-to-disk events, and queue wait times. Identify queries that are scanning too much data or spilling to remote storage.</p><p>· <strong>Layer 4 — Cost: </strong>Set up Resource Monitors and Budgets. Build weekly cost review queries against WAREHOUSE_METERING_HISTORY. Alert on anomalous spend patterns.</p><p>· <strong>Layer 5 — Lineage and Governance: </strong>Use lineage to validate that data flows are correct. Propagate tags and policies. Query ACCESS_HISTORY for compliance reporting.</p><p>· <strong>Layer 6 — Code-Level Observability: </strong>Emit structured logs and traces from Snowpark code. Set appropriate telemetry levels. Query event tables when debugging production issues.</p><p>None of this requires external tooling. That is the key insight. Snowflake has built a remarkably comprehensive observability surface into the platform itself. The challenge is not capability — it is adoption. Most teams are only scratching the surface of what is available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*XhlVE8mIyXWCDdwJmOZf7g.jpeg" /></figure><h3>The Observe Acquisition: What It Means for the Future</h3><p>In 2025, Snowflake completed the acquisition of Observe Inc., a cloud-native observability platform founded by former Splunk engineers. This is not a minor tuck-in acquisition — it represents a strategic bet on observability as a core pillar of the Snowflake platform.</p><p>To understand why this matters, you need to understand what Observe brings to the table.</p><h3>What Is Observe?</h3><p>Observe is an AI-powered observability platform designed to handle logs, metrics, and traces at massive scale. It is built on a data lake architecture with a proprietary technology called the O11y Context Graph™, which structures telemetry data using semantic relationships, incremental views, and token indexes for fast search and correlation.</p><p>Key differentiators of Observe include:</p><p>· <strong>AI SRE: </strong>An AI-powered site reliability assistant that correlates signals across logs, metrics, and traces using natural language. It surfaces root causes and suggests actionable fixes, reducing mean time to resolution by up to 3x according to Observe’s customer benchmarks.</p><p>· <strong>O11y Data Lake™: </strong>Stores telemetry in open formats including Apache Iceberg tables, with up to 10x compression on low-cost cloud storage. This is a fundamental departure from traditional observability vendors that lock you into proprietary storage and charge per GB ingested.</p><p>· <strong>Cost Efficiency: </strong>Observe reports up to 60% lower cost compared to traditional observability platforms like Splunk or Datadog, achieved through elastic compute separation and efficient storage tiering.</p><p>· <strong>Full Signal Coverage: </strong>Unified log management, APM (Application Performance Monitoring), infrastructure monitoring, and LLM observability in a single platform with 400+ pre-built integrations.</p><h3>Why This Acquisition Matters for Data Engineers</h3><p>Here is where it gets interesting from a data engineering perspective. Think about the telemetry data you generate as a data engineer that currently lives outside of Snowflake:</p><p>· Airflow, Dagster, or Prefect logs from your orchestration layer</p><p>· Application logs from services that produce the data your pipelines ingest</p><p>· Infrastructure metrics from the Kubernetes clusters running your processing frameworks</p><p>· API call traces from external data sources and SaaS connectors</p><p>· CI/CD pipeline logs from your dbt builds and deployments</p><p>Today, this telemetry data typically lives in a completely separate system — Datadog, Splunk, CloudWatch, Grafana — and correlating an issue across your Snowflake platform and your infrastructure stack requires jumping between tools, mental context switching, and often manual timeline reconstruction.</p><p>The Observe acquisition has the potential to unify this. Consider a scenario that every data engineer has lived through: a business user reports that a revenue dashboard is showing yesterday’s numbers. Today, your debugging process looks something like this:</p><p>· Check Airflow UI to see if the DAG ran. It shows a failure.</p><p>· SSH or log into your log aggregator to find the Airflow task logs. The error is a timeout.</p><p>· Switch to CloudWatch or Datadog to check if the source database was healthy at that time.</p><p>· Go back to Snowflake to check QUERY_HISTORY and see if the COPY INTO even started.</p><p>· Finally piece together that the source database had a connection pool exhaustion at 2 AM, which caused the Airflow task to time out, which left the Snowflake staging table empty, which propagated stale data downstream.</p><p>That investigation involved four different tools and probably took 30–45 minutes. Now imagine a world where all of those signals live in one system:</p><p>· Your Airflow task failure logs and your Snowflake TASK_HISTORY data are in the same queryable system.</p><p>· An anomaly in your DMF freshness results is automatically correlated with an infrastructure event from the source system.</p><p>· Your Snowpark pipeline traces and your Kubernetes pod metrics are linked through a shared context graph.</p><p>· An AI-powered SRE agent can reason across all of these signals and surface the causal chain in natural language.</p><p>· All of this telemetry is stored in Iceberg tables on your cloud storage, queryable with SQL, and governed by Snowflake’s access control.</p><p>This is the strategic play. Snowflake is positioning itself not just as a data warehouse or a data cloud, but as the convergence point for all data — including operational and observability data. If your application logs, infrastructure metrics, and data platform telemetry all live in the same system, the cross-correlation possibilities are enormous.</p><h3>The Iceberg Connection</h3><p>It is worth noting that Observe’s architecture is built on open data lake storage with Iceberg table support. This aligns perfectly with Snowflake’s aggressive push into the open table format ecosystem with Iceberg tables, Polaris Catalog, and catalog-linked databases. The combination means observability data can be stored in the same open format as your analytical data, governed by the same policies, and queried by the same engines.</p><p>For data engineers, this means observability data becomes a first-class data asset. You can build transformations on top of it, join it with business data, and create derived datasets that combine operational insights with business context. Want to know which pipelines are costing the most per dollar of downstream revenue they support? That analysis requires joining observability data with business data — and it becomes trivial when both live in the same platform. The boundary between “observability data” and “analytical data” starts to dissolve.</p><h3>AI SRE and the Future of Incident Response</h3><p>Observe’s AI SRE capability deserves special attention. Today, when a data pipeline breaks, the data engineer is the SRE. You manually check the orchestrator logs, look at the Snowflake query history, check the source system status, and piece together a root cause narrative. This process is time-consuming and relies heavily on tribal knowledge — the engineer who built the pipeline is often the only one who can debug it efficiently.</p><p>An AI SRE that has access to all of these signals — and can correlate them automatically using natural language — changes the debugging experience fundamentally. Instead of “let me check five different systems,” the workflow becomes asking “what caused the revenue dashboard to go stale at 3 AM?” and the system surfaces the causal chain: a Kubernetes node ran out of memory, which killed the Airflow worker, which missed the scheduled task, which left the Snowflake staging table un-refreshed, which propagated stale data to the dashboard.</p><p>We are not fully there yet. The acquisition is recent, and deep platform integration takes time. But the direction is clear, and it is worth planning for. The teams that invest in centralized observability now will be best positioned to take advantage of these capabilities as they mature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*L0Pu2YTeXmtKaLDXurwBtQ.jpeg" /></figure><h3>Practical Recommendations</h3><p>Whether you are starting from zero or looking to mature your observability practice on Snowflake, here are concrete steps to take:</p><p>· <strong>Start with DMFs: </strong>Pick your five most critical tables and attach freshness, row count, and null count DMFs. Set expectations so you get alerted on violations. This takes an hour and immediately gives you proactive quality monitoring.</p><p>· <strong>Build a monitoring query library: </strong>Write standard queries against QUERY_HISTORY, WAREHOUSE_METERING_HISTORY, and TASK_HISTORY. Schedule them as Snowflake Tasks that write results to a monitoring schema. Add the cost anomaly and scan ratio queries from this article as a starting point.</p><p>· <strong>Set up Resource Monitors: </strong>Every production warehouse should have a resource monitor with notification and suspension thresholds. This is the single fastest way to prevent cost surprises.</p><p>· <strong>Instrument your Snowpark code: </strong>If you are writing Python UDFs, procedures, or Snowpark pipelines, emit structured trace events. Set LOG_LEVEL and TRACE_LEVEL on your pipeline schemas. Future-you will thank current-you when debugging a production issue at 2 AM.</p><p>· <strong>Use lineage before making changes: </strong>Before altering or dropping any object, check its downstream lineage in Snowsight or via GET_LINEAGE. Make this a standard part of your change management process.</p><p>· <strong>Review ACCOUNT_USAGE weekly: </strong>Set a recurring calendar event. Look at cost trends, slow queries, failed tasks, and access patterns. Fifteen minutes a week prevents hours of firefighting.</p><p>· <strong>Plan for convergence: </strong>Keep an eye on how Snowflake integrates Observe. When it becomes available, consider consolidating your observability stack onto the platform to reduce tool sprawl and enable cross-domain correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xwwfQwTwnB3li-idvKqQzg.jpeg" /></figure><h3>Closing Thoughts</h3><p>Observability in data engineering is not about dashboards. It is about trust. When you can answer “is the data correct, is it fresh, is it costing what it should, and is it being used appropriately” at any moment, you operate with confidence. When you cannot, you operate with anxiety.</p><p>Snowflake has quietly built one of the most comprehensive native observability surfaces in the data platform space. ACCOUNT_USAGE views give you 365 days of operational history. DMFs give you proactive data quality monitoring. Event tables give you OpenTelemetry-based logging and tracing. Lineage gives you impact analysis and governance. AI Observability gives you evaluation frameworks for generative AI applications. And the Observe acquisition signals that this is just the beginning.</p><p>For data engineers, the message is clear: observability is not someone else’s job. It is part of the craft. And the tooling to do it well is already at your fingertips.</p><p>Start small. Attach a few DMFs. Query your ACCOUNT_USAGE views. Set a resource monitor. Then expand from there. The platform rewards the curious.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><em>Aaron Moore is a Sr Solutions Engineer at Snowflake, focused on Data Engineering. He writes weekly about Snowflake and data engineering on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b10012ed061" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#Using Snowflake Openflow to Ingest Data from APIs]]></title>
            <link>https://medium.com/@aarongmoore_88179/using-snowflake-openflow-to-ingest-data-from-apis-f36a4e622cc9?source=rss-147e8fe551e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f36a4e622cc9</guid>
            <dc:creator><![CDATA[Aarongmoore]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 18:08:38 GMT</pubDate>
            <atom:updated>2026-04-17T18:08:38.685Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Data Engineer’s Guide to Connecting REST APIs, SaaS Platforms, and Custom Endpoints to Snowflake</em></p><h3>Introduction</h3><p>Every modern enterprise runs on APIs. Your CRM exposes customer records through REST endpoints. Your marketing platforms publish campaign metrics via OAuth-protected JSON feeds. Your HR system offers payroll extracts through SOAP services wrapped in modern REST facades. And somewhere in your organization, a line-of-business team is pulling data from a niche vendor API by running a cron job on someone’s laptop.</p><p>For data engineers, the challenge isn’t whether API data matters — it’s how to build reliable, secure, and observable pipelines that bring API data into your analytics platform without creating a sprawl of bespoke Python scripts and fragile scheduling logic. This is the problem Snowflake Openflow was built to solve.</p><p>Snowflake Openflow is a fully managed data integration service built on Apache NiFi. It provides a visual, flow-based programming model with hundreds of processors for connecting to virtually any data source — structured or unstructured, batch or streaming — and landing that data directly into Snowflake. Openflow runs either inside your Snowflake account via Snowpark Container Services (SPCS) or in your own VPC through Bring Your Own Cloud (BYOC) deployments.</p><p>In this article, we’ll take a deep dive into using Openflow specifically for API-based data ingestion. We’ll cover every API connector Openflow offers, walk through security configuration, explore observability and monitoring, discuss business value, show how Cortex Code accelerates development, and provide technical examples you can adapt for your own pipelines.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*QLxPrl6Qx5R5cRV8MJr77w.jpeg" /></figure><h3>Why API Ingestion Is a First-Class Data Engineering Problem</h3><p>Traditional data integration focused on databases and flat files. Today, a significant and growing portion of enterprise data lives behind APIs that never touch a traditional database. Consider the scope:</p><p>· Salesforce holds your pipeline and revenue data, accessible via Bulk API 2.0.</p><p>· Microsoft Dataverse stores CRM records, case management data, and custom entities from Dynamics 365 and Power Platform apps.</p><p>· SharePoint and Google Drive contain contracts, invoices, SOWs, and meeting recordings that power AI-driven search and summarization.</p><p>· Workday exposes HR analytics through Report-as-a-Service (RaaS) streams.</p><p>· Ad platforms — Google Ads, Meta Ads, LinkedIn Ads, Amazon Ads — publish campaign performance metrics needed for marketing attribution.</p><p>· Collaboration tools like Jira, Slack, and Confluence hold operational metadata: sprint velocity, incident timelines, and knowledge base content.</p><p>· Industry-specific platforms like Veeva Vault serve regulated life sciences data through proprietary APIs.</p><p>The traditional approach to ingesting this data involves writing custom Python or Java scripts, managing OAuth token refresh logic, handling pagination, implementing retry and backoff strategies, dealing with rate limits, parsing nested JSON, and scheduling everything through Airflow or cron. Each new API source adds another script to maintain, another set of credentials to rotate, and another pipeline that can silently fail at 2 AM.</p><p>Openflow replaces this fragmented approach with a single platform that handles all of these concerns declaratively through a visual canvas and curated connectors.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*QoPMaAveJ05RqRt0EkyuKw.jpeg" /></figure><h3>The Complete Openflow API Connector Catalog</h3><p>Openflow’s connector library divides into two categories: curated connectors that provide turnkey integration with specific SaaS platforms, and general-purpose HTTP processors that let you connect to any API endpoint. Here is the full catalog relevant to API-based ingestion.</p><h3>Curated SaaS Connectors</h3><p>Each curated connector is a versioned, opinionated NiFi flow definition built by Snowflake. They follow strict design patterns for performance, fault tolerance, and configuration simplicity. For API ingestion, the following connectors are available:</p><p><strong>Openflow Connector for Salesforce Bulk API. </strong>Replicates standard and custom Salesforce objects into Snowflake using Bulk API 2.0 with incremental change data capture. Handles large-volume extracts efficiently by submitting asynchronous bulk jobs, polling for completion, and streaming results directly into Snowflake via Snowpipe Streaming. Supports both full and incremental sync modes. Authentication is managed through the StandardSalesforceClientService controller, which handles OAuth token lifecycle automatically.</p><p><strong>Openflow Connector for Microsoft Dataverse. </strong>Integrates data from Microsoft Power Platform and Dynamics 365 applications. Uses the FetchMicrosoftDataverseTable and ListMicrosoftDataverseTables processors to discover and extract entity data. Supports incremental extraction based on modification timestamps, enabling efficient CDC-style replication of CRM records, custom entities, and business process data into Snowflake.</p><p><strong>Openflow Connector for SharePoint. </strong>Ingests documents and content from SharePoint Online. Two primary use cases: (1) Ingest SharePoint content and make it ready for chat in AI assistants with Snowflake Cortex, and (2) Ingest content for custom processing in Snowflake. Handles OAuth authentication against Microsoft Graph API, supports folder traversal, and processes documents of all types including PDFs, Word documents, and spreadsheets.</p><p><strong>Openflow Connector for Google Drive. </strong>Ingests Google Drive content for AI assistant integration with Snowflake Cortex or custom processing. Authenticates via Google OAuth 2.0, traverses folder hierarchies, and extracts both native Google Workspace formats and uploaded files.</p><p><strong>Openflow Connector for Google Sheets. </strong>Loads data from Google Sheets into Snowflake tables for reporting, analytics, and insights. Useful for teams that maintain reference data, mapping tables, or manual data entry in spreadsheets that need to feed into the analytics warehouse.</p><p><strong>Openflow Connector for Box. </strong>Ingests Box content with multiple modes: content for custom processing, AI-ready content for Cortex assistants, Box AI metadata extraction for enrichment in Snowflake, and reverse enrichment to push Snowflake metadata back into Box.</p><p><strong>Openflow Connector for Google Ads. </strong>Imports metrics from Google Ads for performance tracking and optimization. Extracts campaign, ad group, and keyword-level performance data using the Google Ads API.</p><p><strong>Openflow Connector for Meta Ads. </strong>Brings Meta (Facebook) Ads data into Snowflake to unify and analyze marketing performance. Extracts campaign insights, ad set metrics, and audience performance data.</p><p><strong>Openflow Connector for LinkedIn Ads. </strong>Imports campaign performance data from LinkedIn Ads for B2B marketing analytics. Extracts campaign metrics, audience insights, and conversion data.</p><p><strong>Openflow Connector for Amazon Ads. </strong>Imports advertising performance data from Amazon Ads for e-commerce marketing analysis. Covers Sponsored Products, Sponsored Brands, and Sponsored Display campaign metrics.</p><p><strong>Openflow Connector for Workday. </strong>Gets Workday data into Snowflake using Report-as-a-Service (RaaS) streams for enterprise-level analytics and planning. Connects to Workday’s reporting API to extract HR, financial, and operational data without requiring direct database access.</p><p><strong>Openflow Connector for Jira Cloud. </strong>Extracts Jira issues and project details for cross-team visibility and deeper insights. Supports extraction of issues, sprints, boards, and custom fields through the Jira REST API.</p><p><strong>Openflow Connector for Slack. </strong>Pulls Slack messages and metadata into Snowflake for searchable, organization-wide insights. Extracts channel messages, thread replies, user metadata, and reaction data.</p><p><strong>Openflow Connector for Confluence. </strong>Integrates with Atlassian Confluence through the StandardConfluenceClientService controller. Extracts pages, blog posts, and space metadata for knowledge management analytics.</p><p><strong>Openflow Connector for Veeva Vault. </strong>Replicates Veeva Vault data into Snowflake using Direct Data archives for analytics and reporting. Critical for life sciences organizations that need to analyze clinical trial data, regulatory submissions, and quality management records in Snowflake.</p><p><strong>Openflow Connector for Kafka. </strong>Ingests real-time events from Apache Kafka into Snowflake for near real-time analytics. While primarily a streaming connector, many organizations use Kafka as an API event bus, making this connector relevant for event-driven API architectures.</p><p><strong>Openflow Connector for Kinesis Data Streams. </strong>Ingests real-time events from Amazon Kinesis Data Streams into Snowflake. Similar to Kafka, relevant when APIs publish events to Kinesis as an intermediary.</p><h3>General-Purpose HTTP Processors</h3><p>When your data source doesn’t have a curated connector — a proprietary vendor API, an internal microservice, a government open-data endpoint, or any REST/HTTP service — Openflow provides powerful HTTP processors that let you build custom integrations.</p><p><strong>InvokeHTTP. </strong>The primary processor for calling external APIs. It supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, and arbitrary custom methods), configurable connection and read timeouts, OAuth2 access token refresh strategies (built-in), SSL/TLS via SSLContextService, proxy configuration, request/response header manipulation, chunked transfer encoding, HTTP/2 negotiation, digest authentication, cookie persistence, response caching (RFC 7234), and multipart form-data uploads. FlowFile attributes are automatically converted to HTTP headers based on configurable regex patterns, and dynamic properties become request headers — making it straightforward to pass API keys, correlation IDs, or tenant identifiers. The processor routes responses to relationship outputs based on HTTP status codes: 2xx to Original/Response, 4xx to No Retry, 5xx to Retry, and socket errors to Failure.</p><p><strong>RestLookupService. </strong>A controller service that performs REST API lookups to enrich FlowFiles as they pass through a pipeline. Ideal for scenarios where you need to join streaming data with reference data from an API — for example, enriching order records with customer details from a CRM API, or decorating log events with asset metadata from a CMDB endpoint.</p><p><strong>HandleHttpRequest. </strong>Turns an Openflow runtime into an HTTP server that can receive webhook callbacks and API push notifications. When a SaaS platform supports webhooks (e.g., Stripe payment events, GitHub repository events, or Salesforce outbound messages), HandleHttpRequest listens for those payloads and injects them into the flow for processing and loading into Snowflake.</p><p><strong>HttpRecordSink. </strong>A controller service that sends record-oriented data to an HTTP endpoint. Useful for bidirectional flows where Openflow not only ingests data from APIs but also pushes processed results back to external systems.</p><h3>Technical Deep Dive: Building an API Ingestion Pipeline</h3><h3>Example 1: Ingesting Data from a REST API with InvokeHTTP</h3><p>Let’s walk through building a pipeline that calls an external REST API, handles pagination, transforms the JSON response, and loads it into Snowflake. This pattern works for any REST API and is the foundation for custom integrations.</p><p><strong>Step 1: Configure the HTTP call. </strong>Add an InvokeHTTP processor to the canvas. Set the HTTP URL to your API endpoint — for example, <a href="https://api.example.com/v2/transactions.">https://api.example.com/v2/transactions.</a> Set the HTTP Method to GET. Configure the OAuth2 Access Token Provider if the API uses OAuth, or add an Authorization header as a dynamic property for API key authentication.</p><p>InvokeHTTP processor configuration:</p><p>HTTP URL: <a href="https://api.example.com/v2/transactions?page=${page.number}&amp;limit=500">https://api.example.com/v2/transactions?page=${page.number}&amp;limit=500</a><br> HTTP Method: GET<br> OAuth2 Strategy: Refresh with Client Credentials<br> Connection Timeout: 30 seconds<br> Read Timeout: 60 seconds<br> SSL Context: StandardSSLContextService (with trusted CA certs)<br> <br> Dynamic Properties:<br> X-API-Key: ${api.key}<br> Accept: application/json<br> X-Request-ID: ${UUID()}</p><p><strong>Step 2: Handle pagination. </strong>Most APIs return paginated results. Use an UpdateAttribute processor before InvokeHTTP to initialize a page.number attribute to 1. After InvokeHTTP, use EvaluateJsonPath to extract the total page count or next-page URL from the response. Route the flow: if more pages exist, increment page.number with UpdateAttribute and loop back to InvokeHTTP. If no more pages, continue downstream.</p><p><strong>Step 3: Parse and transform the JSON response. </strong>Connect InvokeHTTP’s Response relationship to a ConvertRecord processor configured with a JsonTreeReader and a JsonRecordSetWriter (or AvroRecordSetWriter if you prefer schema evolution). Use JoltTransformJSON if you need to restructure deeply nested payloads before loading.</p><p><strong>Step 4: Load into Snowflake. </strong>Route the transformed records to a PutSnowpipeStreaming processor. This processor uses Snowpipe Streaming to load data into Snowflake with sub-second latency and exactly-once semantics. Configure the Snowflake Authentication Strategy as SNOWFLAKE_MANAGED for automatic credential management.</p><p>PutSnowpipeStreaming configuration:</p><p>Snowflake Authentication Strategy: SNOWFLAKE_MANAGED<br> Snowflake Account URL: <a href="https://myorg-myaccount.snowflakecomputing.com/">https://myorg-myaccount.snowflakecomputing.com</a><br> Snowflake Database: RAW_DATA<br> Snowflake Schema: API_INGESTION<br> Snowflake Table: TRANSACTIONS<br> Snowflake Role: OPENFLOW_INGEST_ROLE<br> Record Reader: JsonTreeReader</p><p>― ― ―</p><h3>Example 2: Replicating Salesforce Data with Incremental CDC</h3><p>The Salesforce Bulk API connector provides a turnkey experience for extracting Salesforce objects. Here’s how the pipeline works:</p><p>· The connector uses the StandardSalesforceClientService controller to manage OAuth authentication with Salesforce, handling token refresh automatically.</p><p>· It submits Bulk API 2.0 jobs to Salesforce, which processes the extraction asynchronously for efficient large-volume data transfer.</p><p>· Incremental sync is handled by tracking the SystemModstamp field — on each run, the connector only extracts records modified since the last successful extraction.</p><p>· Results stream through PutSnowpipeStreaming into your target Snowflake table with schema detection and evolution.</p><p>Connector configuration highlights:</p><p>Salesforce Object: Account (or any standard/custom object)<br> Sync Mode: Incremental<br> Tracking Field: SystemModstamp<br> Batch Size: 10,000 records<br> Auth Service: StandardSalesforceClientService<br> — Client ID: (from Salesforce Connected App)<br> — Client Secret: (from Salesforce Connected App)<br> — Auth Endpoint: https://login.salesforce.com<br> — Grant Type: Client Credentials</p><p>Once configured, this connector runs continuously, detecting changes in Salesforce and replicating them to Snowflake within minutes. No custom code, no cron jobs, no token rotation scripts.</p><p>― ― ―</p><h3>Example 3: Connecting to Microsoft Dataverse</h3><p>Microsoft Dataverse is the data backbone for Dynamics 365 and Power Platform applications. The Openflow Connector for Microsoft Dataverse uses two specialized processors to extract entity data:</p><p><strong>ListMicrosoftDataverseTables: </strong>Discovers available entities (tables) in your Dataverse environment. This is useful for initial setup — you can enumerate all entities and select which ones to replicate.</p><p><strong>FetchMicrosoftDataverseTable: </strong>Extracts records from a specific Dataverse entity. Supports incremental extraction based on modification timestamps, enabling efficient CDC-style replication.</p><p>Authentication uses OAuth 2.0 client credentials against Azure Active Directory. You register an App Registration in Azure AD, grant it the Dataverse API permission, and configure the connector with the resulting client ID, secret, and tenant ID.</p><p>A typical pipeline flow: ListMicrosoftDataverseTables (for discovery) → FetchMicrosoftDataverseTable (for extraction) → ConvertRecord (for schema alignment) → PutSnowpipeStreaming (for loading into Snowflake). This gives you a complete, incremental replication pipeline from Dynamics 365 CRM to Snowflake without writing a single line of code.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*kfqAOHDT4GO6Di6xC92Ebg.jpeg" /></figure><h3>Security: Enterprise-Grade Protection for API Credentials and Data</h3><p>When you’re connecting to external APIs, security isn’t optional — it’s the foundation. Openflow provides multiple layers of security that address authentication, authorization, network isolation, encryption, and secrets management.</p><h3>Authentication</h3><p><strong>Snowflake Managed Token. </strong>The default and recommended authentication method for Openflow runtimes connecting to Snowflake. It eliminates the need to generate, store, and rotate long-lived credentials like key pairs. Tokens are short-lived and automatically refreshed. In SPCS deployments, the runtime uses native SPCS session tokens. In BYOC deployments, it uses workload identity federation to exchange cloud provider identity (e.g., AWS IAM role) for a Snowflake token.</p><p><strong>OAuth 2.0 for External APIs. </strong>Snowflake’s External API Security Integration provides centralized OAuth configuration for connecting to external services. It supports three grant types:</p><p>· Client Credentials — for service-to-service authentication where no user context is needed.</p><p>· Authorization Code — for delegated access that requires user consent.</p><p>· JWT Bearer — for certificate-based authentication common in enterprise environments.</p><p>Here’s an example of creating a security integration for Microsoft SharePoint:</p><p>CREATE SECURITY INTEGRATION sharepoint_security_integration<br> TYPE = API_AUTHENTICATION<br> AUTH_TYPE = OAUTH2<br> OAUTH_CLIENT_AUTH_METHOD = CLIENT_SECRET_POST<br> OAUTH_CLIENT_ID = ‘YOUR_CLIENT_ID’<br> OAUTH_CLIENT_SECRET = ‘YOUR_CLIENT_SECRET’<br> OAUTH_GRANT = ‘CLIENT_CREDENTIALS’<br> OAUTH_TOKEN_ENDPOINT = <br> ‘https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/token&#39;<br> OAUTH_ALLOWED_SCOPES = (‘https://graph.microsoft.com/.default&#39;)<br> ENABLED = TRUE;</p><p><strong>Key-Pair Authentication. </strong>An alternative for BYOC deployments where explicit credential management is required. Supports key-pair rotation for zero-downtime credential updates.</p><h3>Authorization</h3><p>Openflow integrates with Snowflake’s Role-Based Access Control (RBAC). Fine-grained roles control who can create deployments, manage runtimes, configure connectors, and access target tables. ACCOUNTADMIN grants privileges for deployment creation, while custom roles can be scoped to specific connector operations and target schemas. This means your Openflow pipelines operate under the principle of least privilege — a connector ingesting marketing data doesn’t need access to financial tables.</p><h3>Network Security</h3><p><strong>AWS PrivateLink. </strong>Openflow connectors support reading and writing data to Snowflake using inbound AWS PrivateLink, ensuring that data never traverses the public internet. For BYOC deployments, the data plane runs inside your VPC, so connections to internal APIs stay within your network perimeter.</p><p><strong>Tri-Secret Secure. </strong>Openflow connectors are compatible with Tri-Secret Secure for writing data to Snowflake, providing an additional layer of encryption using a customer-managed key combined with Snowflake’s key to create a composite master key.</p><h3>Encryption and Secrets Management</h3><p>All communications between Openflow deployments and the Openflow control plane are encrypted using TLS. For BYOC deployments, Openflow integrates with AWS Secrets Manager and HashiCorp Vault for external secrets management, ensuring that API credentials, OAuth secrets, and connection strings are never stored in plaintext within pipeline configurations.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0psrw2Y7m2EACPzhAL-rRA.jpeg" /></figure><h3>Observability: Monitoring Your API Pipelines</h3><p>A pipeline you can’t observe is a pipeline you can’t trust. Openflow provides comprehensive telemetry that integrates directly with Snowflake’s event table infrastructure, giving you a single pane of glass for monitoring all your data integration flows.</p><h3>Event Table Integration</h3><p>Openflow sends all runtime telemetry — logs and metrics — to the Snowflake event table you configure during setup. This means your pipeline observability data lives alongside your business data in Snowflake, queryable with standard SQL. The telemetry follows the OpenTelemetry schema with rich resource attributes identifying the deployment, runtime, pod, container, and cloud provider.</p><p>Key resource attributes in the event table:</p><p>· openflow.dataplane.id — the unique identifier of the Openflow deployment.</p><p>· k8s.pod.name — the specific pod handling the data flow, useful for debugging node-level issues.</p><p>· k8s.container.restart_count — alerts you to runtime instability.</p><p>· container.image.tag — tracks the Openflow version running in each runtime.</p><h3>Application Metrics</h3><p>Openflow emits detailed flow-level metrics that let you understand exactly what’s happening inside each pipeline. These include:</p><p>· <strong>Throughput: </strong>Connection metrics — input/output byte counts and item counts, queue depth and duration, backpressure threshold status.</p><p>· <strong>Latency: </strong>Processor metrics — invocation count, processing duration (nanoseconds), bytes read/written, active thread count.</p><p>· <strong>Queue Health: </strong>FlowFile metrics — total count, active and queued FlowFiles, bytes in queue.</p><p>· <strong>System: </strong>JVM metrics — heap and non-heap memory, GC runs and duration, thread counts, CPU load.</p><p>Example: Query to monitor API call success rates over the last hour:</p><p>SELECT<br> RECORD:metric:name::STRING AS metric_name,<br> RECORD_ATTRIBUTES:name::STRING AS processor_name,<br> VALUE::NUMBER AS metric_value,<br> TIMESTAMP<br> FROM my_event_table<br> WHERE RESOURCE_ATTRIBUTES:application::STRING = ‘openflow’<br> AND RECORD:metric:name::STRING LIKE ‘processor.invocations%’<br> AND RECORD_ATTRIBUTES:name::STRING = ‘InvokeHTTP’<br> AND TIMESTAMP &gt; DATEADD(hour, -1, CURRENT_TIMESTAMP())<br> ORDER BY TIMESTAMP DESC;</p><h3>MonitorActivity Processor</h3><p>The MonitorActivity processor is a built-in Openflow processor that watches data flow through a connection and generates alerts when activity stops for a configurable duration. For API ingestion pipelines, this is critical: if an upstream API goes down or a connector stalls, MonitorActivity detects the gap and can trigger notifications. You can route its output to alert channels or log it to the event table for dashboard integration.</p><h3>Runtime Logs</h3><p>Openflow runtimes emit structured JSON logs that you can parse with TRY_PARSE_JSON in Snowflake. Each log entry includes the formatted message, severity level (ERROR, WARN, INFO, DEBUG, TRACE), the fully-qualified logger name (useful for filtering to specific processors like com.snowflake.openflow.runtime.processors), the thread name, and exception stack traces when errors occur. This gives you full diagnostic capability without SSH-ing into containers.</p><p>Example: Query to find API connection errors in the last 24 hours:</p><p>SELECT<br> TIMESTAMP,<br> TRY_PARSE_JSON(VALUE):formattedMessage::STRING AS message,<br> TRY_PARSE_JSON(VALUE):level::STRING AS log_level,<br> TRY_PARSE_JSON(VALUE):loggerName::STRING AS logger,<br> TRY_PARSE_JSON(VALUE):throwable::STRING AS exception<br> FROM my_event_table<br> WHERE RESOURCE_ATTRIBUTES:application::STRING = ‘openflow’<br> AND RECORD_TYPE = ‘LOG’<br> AND TRY_PARSE_JSON(VALUE):level::STRING = ‘ERROR’<br> AND TIMESTAMP &gt; DATEADD(day, -1, CURRENT_TIMESTAMP())<br> ORDER BY TIMESTAMP DESC;</p><h3>Building Dashboards</h3><p>Because all telemetry lands in a Snowflake event table, you can build monitoring dashboards using Streamlit in Snowflake, Snowsight dashboards, or external tools like Grafana and Tableau. Common dashboard panels include: records ingested per connector over time, API response latency percentiles, error rates by processor, queue backpressure indicators, and runtime resource utilization. Additionally, Snowflake’s OpenTelemetry Reporting Task can forward metrics to any OTLP-compatible destination for integration with existing observability stacks like Datadog or New Relic.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*hoffu0CSwufEiTGIzgAxPA.jpeg" /></figure><h3>Accelerating Development with Cortex Code</h3><p>Cortex Code is Snowflake’s AI-powered development CLI that understands your Snowflake environment and can assist with Openflow pipeline development. Here’s how it accelerates API ingestion workflows:</p><p><strong>Pipeline Design Assistance. </strong>Describe your integration requirement in natural language — “I need to ingest data from the GitHub API and load it into Snowflake” — and Cortex Code can help you identify the right processors, configure InvokeHTTP properties, design the flow topology, and generate the necessary SQL for security integrations and target tables.</p><p><strong>SQL Generation for Security Integrations. </strong>Setting up OAuth security integrations requires precise SQL. Cortex Code can generate CREATE SECURITY INTEGRATION statements, CREATE SECRET statements, and the associated GRANT commands based on your target API’s authentication requirements.</p><p><strong>Monitoring Query Development. </strong>Cortex Code can help you write complex event table queries to monitor your Openflow pipelines. Ask it to “write a query that shows InvokeHTTP error rates grouped by target URL over the last 7 days” and it generates the SQL, understanding the event table schema and Openflow’s telemetry structure.</p><p><strong>Troubleshooting. </strong>When a pipeline fails, Cortex Code can help diagnose the issue by querying event table logs, interpreting error messages from NiFi processors, and suggesting configuration fixes. It understands the relationship between Openflow processors, controller services, and Snowflake objects.</p><p><strong>Documentation and Discovery. </strong>Cortex Code has access to Snowflake documentation and can answer questions about processor properties, connector capabilities, and best practices without requiring you to context-switch to a browser. Ask “what authentication methods does InvokeHTTP support?” and get an immediate, accurate answer.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*qeABaEKgiu-mcYYu4ENlXQ.jpeg" /></figure><h3>Business Value: Why Invest in API Ingestion with Openflow</h3><p>Beyond the technical capabilities, there are compelling business reasons for using Openflow as your API ingestion platform.</p><h3>Eliminate Tool Sprawl</h3><p>Most enterprises have accumulated a patchwork of integration tools: Fivetran for some SaaS sources, custom Python scripts for APIs, Airflow DAGs for orchestration, and maybe a legacy ETL tool for databases. Each tool has its own credential store, monitoring approach, and failure modes. Openflow consolidates all of this — database CDC, SaaS API ingestion, file processing, and streaming — into a single managed platform with unified security and observability.</p><h3>Reduce Operational Risk</h3><p>Custom scripts are technical debt from the moment they’re written. They break when APIs change their schemas, when OAuth tokens expire in unexpected ways, when rate limits tighten. Openflow’s curated connectors are maintained by Snowflake, with version updates that track API changes. The visual canvas makes pipeline logic visible and auditable — anyone on the team can understand what a flow does without reading code.</p><h3>Accelerate Time-to-Value</h3><p>A curated Openflow connector can have data flowing into Snowflake within an hour of configuration. Even custom InvokeHTTP integrations take a fraction of the time compared to writing, testing, deploying, and monitoring a custom script. The visual flow designer eliminates the build-deploy-test cycle for integration logic.</p><h3>Enable AI Use Cases</h3><p>Unstructured data from APIs — documents from SharePoint, content from Google Drive, messages from Slack — becomes immediately available for Snowflake Cortex AI processing. Openflow’s connectors can ingest content and make it ready for Cortex Search Service, enabling natural language querying across your organization’s documents. This turns API ingestion from a data engineering task into an AI enablement strategy.</p><h3>Security and Compliance</h3><p>For regulated industries, Openflow’s integration with Snowflake’s security model — RBAC, PrivateLink, Tri-Secret Secure, and event table auditing — means API ingestion pipelines meet enterprise compliance requirements without bolting on additional security layers. Data never leaves the Snowflake security perimeter in SPCS deployments, and BYOC deployments keep data within your VPC.</p><h3>Cost Efficiency</h3><p>Openflow’s managed model means you pay for compute utilization rather than per-connector licensing fees. This is particularly advantageous when connecting to many API sources — the marginal cost of adding another connector to an existing deployment is minimal compared to per-source pricing models.</p><p>― ― ―</p><h3>Real-World Scenarios: Why Customers Choose Openflow for API Ingestion</h3><h3>Scenario 1: Unified Marketing Analytics</h3><p>A retail company runs campaigns across Google Ads, Meta Ads, LinkedIn Ads, and Amazon Ads. Each platform has its own API, authentication scheme, rate limits, and data format. Before Openflow, the marketing analytics team maintained four separate Python scripts, each with hardcoded credentials, running on an EC2 instance. When the Meta Ads API changed its pagination model, the script broke silently for two weeks before anyone noticed.</p><p>With Openflow, they deploy four curated ad platform connectors on a single runtime. Each connector handles authentication, pagination, and schema mapping natively. The event table captures metrics from all four connectors, and a single Streamlit dashboard shows data freshness, record counts, and error rates across all marketing sources. The team eliminated custom code entirely and reduced their mean time to detect ingestion failures from days to minutes.</p><h3>Scenario 2: CRM Data Consolidation</h3><p>A manufacturing company uses Microsoft Dataverse for CRM (via Dynamics 365), SharePoint for document management, and several external vendor APIs for supply chain data. They need all of this data in Snowflake for operational analytics and AI-powered demand forecasting.</p><p>Openflow’s Dataverse connector replicates CRM entities — accounts, contacts, opportunities, and custom entities — with incremental CDC. The SharePoint connector ingests contracts and purchase orders, making them searchable via Cortex Search. InvokeHTTP handles the custom supply chain API calls. All three data streams flow into Snowflake through a single Openflow deployment, governed by Snowflake RBAC and monitored through the event table.</p><h3>Scenario 3: Life Sciences Regulatory Compliance</h3><p>A pharmaceutical company needs to replicate clinical trial data from Veeva Vault, HR data from Workday, and project tracking data from Jira into Snowflake for cross-functional analytics. Regulatory requirements demand full audit trails, encryption at rest and in transit, and network isolation.</p><p>Openflow meets every requirement: Veeva Vault connector for clinical data, Workday connector for HR analytics, Jira connector for project visibility. PrivateLink ensures network isolation. Tri-Secret Secure provides encryption. The event table creates a complete audit trail of every record ingested, when, and by which runtime — satisfying FDA and HIPAA auditability requirements.</p><p>― ― ―</p><h3>Deployment Architecture for API Ingestion</h3><p>Openflow offers two deployment models, each with different trade-offs for API ingestion workloads.</p><h3>Snowflake Deployment (SPCS)</h3><p>The Openflow runtime runs as a Snowpark Container Services workload inside your Snowflake account. This is the simplest option — no infrastructure to manage, native integration with Snowflake security, and pay-per-use compute. Choose this when your API sources are accessible over the public internet (or through Snowflake-supported endpoints) and you want minimal operational overhead. Available in all AWS and Azure commercial regions.</p><h3>Bring Your Own Cloud (BYOC)</h3><p>The Openflow data plane runs in your own AWS VPC while Snowflake manages the control plane. Choose this when you need to connect to APIs that are only accessible within your private network (internal microservices, on-premises systems with VPN connectivity), when you require data to be processed within your VPC before reaching Snowflake, or when you need integration with AWS Secrets Manager or HashiCorp Vault for credential management. Available in AWS commercial regions.</p><p>In both models, you can run multiple runtimes within a single deployment to isolate workloads by team, environment (dev/staging/prod), or data sensitivity level. Each runtime can scale independently based on the throughput demands of its API sources.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*FRWVU4YJkJp7LYbF7qLscg.jpeg" /></figure><h3>Best Practices for API Ingestion with Openflow</h3><p>· <strong>Use curated connectors first. </strong>Start with curated connectors when available. They handle authentication, pagination, error recovery, and schema mapping out of the box. Only use InvokeHTTP for APIs without a dedicated connector.</p><p>· <strong>Design for failure. </strong>Build pagination, retry, and backoff logic into every InvokeHTTP flow. Use the Retry relationship for 5xx errors and configure exponential backoff with the PenalizeFlowFile processor.</p><p>· <strong>Centralize credential management. </strong>Use Snowflake’s External API Security Integration for OAuth. Never hardcode credentials as processor properties. Use Snowflake secrets for API keys and sensitive configuration values.</p><p>· <strong>Monitor from day one. </strong>Set up event table queries and dashboards before going to production. Configure MonitorActivity processors on critical flow segments. Define alerting thresholds for record counts, error rates, and queue depths.</p><p>· <strong>Isolate environments. </strong>Run separate runtimes for development, staging, and production. Use Openflow’s deployment model to isolate environments and prevent configuration drift.</p><p>· <strong>Apply least privilege. </strong>Apply Snowflake’s RBAC model to Openflow. Create dedicated roles for each connector with minimum necessary privileges on target tables.</p><p>· <strong>Separate ingestion from transformation. </strong>Land API data in raw tables first, then transform with dbt, dynamic tables, or Snowpark. This preserves the original API response for debugging and reprocessing.</p><p>· <strong>Version and test connector upgrades. </strong>APIs change without warning. Pin your connector versions, test upgrades in a staging runtime before promoting to production, and maintain schema evolution strategies in your target tables.</p><p>· <strong>Tag records with provenance metadata. </strong>Use FlowFile attributes to tag records with their source API, extraction timestamp, and batch identifier. This metadata is invaluable for debugging, reprocessing, and lineage tracking.</p><p>― ― ―</p><h3>Advanced Patterns for API Ingestion</h3><h3>Pattern 1: Multi-API Fan-Out with Shared Authentication</h3><p>Many organizations need to call multiple endpoints from the same API provider. For example, a Salesforce integration might extract Accounts, Contacts, Opportunities, and custom objects from the same org. Rather than configuring separate OAuth credentials for each extraction, Openflow lets you define a single controller service (like StandardSalesforceClientService) and reference it from multiple processors. This centralizes credential management and ensures token refresh happens once, not per-processor.</p><p>In a fan-out pattern, a GenerateFlowFile processor creates trigger FlowFiles on a schedule. A RouteOnAttribute processor splits the flow by object type (Account, Contact, Opportunity). Each branch calls the appropriate API endpoint through its own processor instance, but all share the same authentication controller service. Results merge back into a common flow for loading into Snowflake, with FlowFile attributes identifying the source object type.</p><h3>Pattern 2: Webhook Ingestion with HandleHttpRequest</h3><p>Not all API ingestion is pull-based. Many modern platforms support webhooks — push-based notifications where the source system calls your endpoint when data changes. Openflow’s HandleHttpRequest processor turns your runtime into an HTTP server capable of receiving these webhook payloads.</p><p>A webhook ingestion pipeline looks like this: HandleHttpRequest listens on a configured port and path. When a webhook fires (e.g., a Stripe payment event or GitHub push notification), the payload becomes a FlowFile. HandleHttpResponse immediately returns a 200 OK to the sender to acknowledge receipt. The FlowFile then passes through validation (EvaluateJsonPath to verify required fields), transformation (JoltTransformJSON to flatten nested structures), and loading (PutSnowpipeStreaming to write to Snowflake). If validation fails, the FlowFile routes to a dead-letter queue for manual review.</p><p>HandleHttpRequest configuration for a webhook endpoint:</p><p>Listening Port: 8443<br> SSL Context Service: StandardSSLContextService<br> Allowed Paths: /webhooks/stripe, /webhooks/github<br> HTTP Method Filter: POST<br> Max Request Size: 10 MB<br> <br> Downstream routing:<br> HandleHttpRequest → EvaluateJsonPath (validate payload)<br> → Success: JoltTransformJSON → PutSnowpipeStreaming<br> → Failure: LogMessage → PutSnowpipeStreaming (dead_letter table)</p><h3>Pattern 3: API Data Enrichment with RestLookupService</h3><p>Sometimes you don’t just need to ingest API data — you need to enrich data that’s already flowing through your pipeline with additional context from an API. The RestLookupService controller makes this possible without breaking out of the Openflow flow.</p><p>Consider a use case where you’re ingesting order records from a database CDC connector, and each order contains a customer_id. You need to enrich each order with the customer’s current account status from your CRM API. Configure a RestLookupService pointing to your CRM endpoint (e.g., <a href="https://api.crm.com/v1/customers/$%7Bcustomer_id%7D),">https://api.crm.com/v1/customers/${customer_id}),</a> then use a LookupRecord processor to join the API response fields onto each order record. The result is an enriched record that includes both the order data and the real-time customer status, loaded into Snowflake as a single denormalized row.</p><h3>Pattern 4: Rate-Limited API Extraction</h3><p>Many APIs impose rate limits — Salesforce allows 100 concurrent API calls, Jira throttles to 100 requests per minute for most endpoints, and ad platform APIs often have daily quota limits. Openflow handles this through several mechanisms:</p><p>· <strong>Backpressure and retry. </strong>The InvokeHTTP processor’s Retry relationship captures 429 (Too Many Requests) and 5xx responses. Connect Retry back to InvokeHTTP with a PenalizeFlowFile processor in between to implement automatic backoff.</p><p>· <strong>Connection backpressure. </strong>Openflow’s connection backpressure thresholds prevent downstream overload. If the target Snowflake table can’t keep up, connections apply backpressure to slow upstream processors, which in turn slows API calls naturally.</p><p>· <strong>Explicit rate limiting. </strong>Use ControlRate processor to enforce explicit rate limits — for example, no more than 50 requests per minute — ensuring you stay within API quota boundaries.</p><p>· <strong>Batch operations. </strong>Curated connectors like Salesforce Bulk API use asynchronous batch operations specifically designed to avoid per-request rate limits entirely.</p><p>― ― ―</p><h3>Error Handling and Pipeline Resilience</h3><p>API integrations fail. Endpoints go down, tokens expire, schemas change, rate limits are hit, and network partitions happen. Openflow’s flow-based model provides natural resilience patterns that are difficult to replicate in custom code.</p><h3>Relationship-Based Error Routing</h3><p>Every Openflow processor defines explicit output relationships for different outcomes. InvokeHTTP, for example, routes to five distinct relationships: Original (2xx success), Response (2xx response body), No Retry (4xx client errors), Retry (5xx server errors), and Failure (socket-level errors). This means error handling isn’t an afterthought — it’s built into the flow topology. You decide at design time what happens when each failure mode occurs, rather than wrapping everything in try/catch blocks and hoping you covered every edge case.</p><h3>Dead-Letter Queues</h3><p>For records that fail processing — malformed JSON from an API, schema mismatches, or validation failures — route them to a dead-letter table in Snowflake using a separate PutSnowpipeStreaming processor. Include the original FlowFile content, the error message, the source processor name, and a timestamp. This gives you a queryable audit trail of every failure, enabling root-cause analysis without losing data.</p><p>Example dead-letter table schema:</p><p>CREATE TABLE raw_data.api_ingestion.dead_letter (<br> record_id STRING DEFAULT UUID_STRING(),<br> source_api STRING,<br> processor_name STRING,<br> error_message STRING,<br> original_content VARIANT,<br> flow_file_attributes VARIANT,<br> failed_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br> );</p><h3>Automatic Recovery</h3><p>Openflow runtimes persist FlowFile state to disk. If a runtime pod restarts (due to an OOM kill, a node failure, or a deployment update), the runtime recovers its in-flight FlowFiles and resumes processing from where it left off. For API ingestion, this means you don’t lose partially-processed API responses — they’re replayed automatically after recovery. Combined with Snowpipe Streaming’s exactly-once semantics, this provides end-to-end delivery guarantees that are difficult to achieve with custom scripts.</p><p>― ― ―</p><h3>Getting Started: Your First API Ingestion Pipeline in 30 Minutes</h3><p>Here’s a step-by-step walkthrough for getting your first API ingestion pipeline running. We’ll use the Snowflake Deployment (SPCS) model and the Google Ads connector as an example, but the process is similar for any connector.</p><p><strong>Step 1: Create an Openflow Deployment. </strong>In Snowsight, navigate to Data Integration &gt; Openflow. Click “Create Deployment” and select the Snowflake Deployment type. Choose your compute pool size based on expected throughput — start small and scale up as needed. The deployment provisions in a few minutes.</p><p><strong>Step 2: Create a Runtime. </strong>Within your deployment, create a runtime. A runtime is the execution environment where your data flows run. Name it descriptively (e.g., “marketing-ads-ingestion”) and set the maximum node count. For a single API connector, one node is sufficient.</p><p><strong>Step 3: Configure the Connector. </strong>From the Openflow canvas, add the Google Ads connector. Provide your Google Ads customer ID, configure OAuth authentication (either through a Snowflake Security Integration or by providing OAuth credentials directly), select the reports and metrics you want to extract, and specify the target Snowflake database, schema, and table.</p><p><strong>Step 4: Set Up the Target Table. </strong>Create the target table in Snowflake if it doesn’t already exist. The connector can auto-create tables in many cases, but defining the schema explicitly gives you control over data types, clustering keys, and access grants.</p><p>Example target table:</p><p>CREATE TABLE raw_data.marketing.google_ads_campaigns (<br> campaign_id NUMBER,<br> campaign_name STRING,<br> impressions NUMBER,<br> clicks NUMBER,<br> cost_micros NUMBER,<br> conversions FLOAT,<br> date DATE,<br> extracted_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br> );<br> <br> GRANT INSERT, SELECT ON TABLE raw_data.marketing.google_ads_campaigns<br> TO ROLE openflow_ingest_role;</p><p><strong>Step 5: Configure Monitoring. </strong>Verify that your event table is configured for the Openflow deployment. Run a quick query to confirm telemetry is flowing:</p><p>SELECT COUNT(*), MIN(TIMESTAMP), MAX(TIMESTAMP)<br> FROM my_event_table<br> WHERE RESOURCE_ATTRIBUTES:application::STRING = ‘openflow’<br> AND TIMESTAMP &gt; DATEADD(hour, -1, CURRENT_TIMESTAMP());</p><p><strong>Step 6: Start the Flow and Validate. </strong>Start the connector from the Openflow canvas. Within minutes, you should see records appearing in your target table. Query the event table to verify successful processing metrics and check for any error logs. Set up a MonitorActivity processor on the output connection to alert you if data flow stops.</p><p>― ― ―</p><h3>Openflow vs. Custom Scripts vs. Third-Party ETL: A Comparison</h3><p>To put Openflow’s API ingestion capabilities in context, here’s how it compares to the two most common alternatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*KjfmqcNe4NEJZWwlq_J9Pg.jpeg" /></figure><p>The key differentiator for Openflow is the combination of flexibility and governance. Custom scripts offer maximum flexibility but zero governance. Third-party ETL tools offer convenience but limited customization and opaque security. Openflow provides the visual flow designer and curated connectors of an ETL tool, the flexibility of custom HTTP processors, and the security and observability of Snowflake’s native platform.</p><p>― ― ―</p><h3>Scaling API Ingestion Pipelines</h3><p>As your API ingestion footprint grows from a handful of connectors to dozens, scaling becomes a practical concern. Openflow provides several mechanisms for handling increased throughput and connector count.</p><h3>Horizontal Scaling with Multi-Node Runtimes</h3><p>Each Openflow runtime can be configured with a maximum node count. When a single node can’t keep up with the volume of data from an API (common with high-frequency streaming sources or large bulk extractions), Openflow distributes processing across multiple pods. Connection load balancing metrics in the event table (connection.loadbalance.status.load_balance_active) let you verify that work is being distributed evenly across nodes.</p><h3>Runtime Isolation</h3><p>Rather than running all API connectors in a single runtime, use multiple runtimes to isolate workloads by criticality, team ownership, or data sensitivity. A marketing team’s ad platform connectors run in one runtime, while the finance team’s ERP API integration runs in another. This prevents a misbehaving connector from affecting unrelated pipelines, and allows independent scaling and upgrade cycles for each workload.</p><h3>Backpressure as a Scaling Signal</h3><p>Openflow’s connection backpressure metrics (connection.backpressure.threshold.bytes and connection.backpressure.threshold.objects) serve as leading indicators for scaling decisions. When connections consistently hit backpressure thresholds, it means downstream processors can’t keep up — a signal to add nodes, optimize processors, or split the workload across runtimes. Monitor these metrics in your event table dashboards to make data-driven scaling decisions rather than guessing at capacity.</p><h3>Cost Optimization</h3><p>API ingestion workloads are often bursty — high throughput during initial backfills, then lower steady-state volume for incremental syncs. Openflow’s compute model charges based on utilization, so you can right-size runtimes after the initial backfill completes. For SPCS deployments, the compute pool scales with demand. For BYOC deployments, you control the underlying infrastructure sizing directly. In both cases, running separate runtimes for batch (daily full extracts) and streaming (real-time CDC or webhook) workloads lets you optimize cost independently for each pattern.</p><p>― ― ―</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7tLhxtG-hyQWTfYcKca3Sg.jpeg" /></figure><h3>Conclusion</h3><p>API ingestion is no longer a niche requirement — it’s a core data engineering competency. The data that drives modern business decisions lives behind REST endpoints, OAuth-protected SaaS platforms, and webhook callbacks. Building and maintaining custom integration code for each source is expensive, fragile, and doesn’t scale.</p><p>Snowflake Openflow provides a managed, secure, and observable platform for connecting to any API. With curated connectors for major SaaS platforms — Salesforce, Dataverse, SharePoint, Workday, Jira, Slack, Veeva Vault, and all major ad platforms — plus general-purpose HTTP processors for custom APIs, Openflow covers the full spectrum of API integration needs. Its native integration with Snowflake’s security model (RBAC, PrivateLink, Tri-Secret Secure, Managed Token authentication) and observability infrastructure (event tables, OpenTelemetry metrics) means your API pipelines are enterprise-ready from day one.</p><p>For data engineers, the value proposition is clear: spend your time designing data models and building analytics, not maintaining OAuth token refresh scripts and custom API clients. Openflow handles the plumbing so you can focus on the engineering.</p><p>The shift from custom integration code to a managed platform isn’t just a technical upgrade — it’s an organizational one. When API ingestion is standardized on Openflow, new team members can understand pipeline logic through the visual canvas without reading code. Security teams can audit credential usage through Snowflake’s native access controls rather than hunting through script repositories for hardcoded secrets. Operations teams can monitor every pipeline through a single event table rather than piecing together logs from scattered services. And data engineers can add new API sources in hours instead of weeks, accelerating the organization’s ability to act on data from every corner of the business.</p><p>If you’re currently managing a fleet of custom API integration scripts, or if you’re evaluating how to bring your first SaaS data sources into Snowflake, Openflow deserves a serious look. Start with one curated connector, see how quickly you can get data flowing, and expand from there. The connectors, security model, and observability infrastructure are ready — your data is waiting.</p><p>― ― ―</p><h3>Further Reading</h3><p>· About Openflow — docs.snowflake.com/en/user-guide/data-integration/openflow/about</p><p>· Openflow Connectors — docs.snowflake.com/en/user-guide/data-integration/openflow/connectors/about-openflow-connectors</p><p>· Monitor Openflow — docs.snowflake.com/en/user-guide/data-integration/openflow/monitor</p><p>· InvokeHTTP Processor — docs.snowflake.com/en/user-guide/data-integration/openflow/processors/invokehttp</p><p>· CREATE SECURITY INTEGRATION (External API Auth) — docs.snowflake.com/en/sql-reference/sql/create-security-integration-api-auth</p><p>· Openflow Connector for Salesforce Bulk API — docs.snowflake.com/en/user-guide/data-integration/openflow/connectors/salesforce-bulk-api/about</p><p>Openflow Connector for Microsoft Dataverse — docs.snowflake.com/en/user-guide/data-integration/openflow/connectors/dataverse/about</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f36a4e622cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>