๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Topic: Dynamic Tables, Streams & Tasks

Snowflake AdvancedStreaming & CDCโญ Premium

Snowflake Advanced ยท Interview Prep

Dynamic Tables, Streams & Tasks

Difficulty: Hard ยท Commonly asked at Amazon, Netflix, Meta

Interview Question

"Design a real-time CDC pipeline using Streams and Tasks. How do you handle late-arriving data, schema changes, and ensure exactly-once processing semantics?"

โ„น๏ธ

Companies Asking This: Amazon (L6 Data Engineer), Netflix (Staff Data Engineer), Meta (Data Platform Engineer), Google (Senior Data Engineer)


Dynamic Tables

Dynamic Tables are declarative, incrementally-refreshed tables that automatically keep query results up-to-date.

Dynamic tables replace the task graph you would otherwise hand-build: you declare the SQL and a target lag, and Snowflake's refresh service decides what to recompute, when, and on which warehouse. Two properties decide whether you pick one over a materialized view. Refresh can be incremental, where only changed base rows re-enter the pipeline, or full, chosen by the engine when a transformation cannot be incrementally maintained โ€” so a self-join or a non-deterministic function quietly pushes you into full refresh and its cost. And the lag target accepts time values or DOWNSTREAM, which ties a dynamic table's freshness to its parents rather than to a clock, giving correct ordering across a DAG with no scheduler attached. Credits accrue from whichever warehouse runs the refreshes, which means a five-minute lag on a table that changes every minute costs far more than the same target on a table that changes hourly.

Creating Dynamic Tables

-- Create a dynamic table for real-time aggregation
CREATE OR REPLACE DYNAMIC TABLE daily_sales_summary
    TARGET_LAG = '5 minutes'
    WAREHOUSE = analytics_wh
AS
SELECT 
    sale_date,
    region,
    product_category,
    COUNT(*) AS transaction_count,
    SUM(amount) AS total_revenue,
    AVG(amount) AS avg_transaction,
    COUNT(DISTINCT customer_id) AS unique_customers,
    CURRENT_TIMESTAMP() AS last_refreshed
FROM sales
WHERE sale_date >= DATEADD(day, -30, CURRENT_DATE())
GROUP BY 1, 2, 3;

-- Dynamic table with joins
CREATE OR REPLACE DYNAMIC TABLE customer_360
    TARGET_LAG = '10 minutes'
    WAREHOUSE = analytics_wh
AS
SELECT 
    c.customer_id,
    c.customer_name,
    c.segment,
    c.registration_date,
    COUNT(o.order_id) AS total_orders,
    SUM(o.amount) AS lifetime_value,
    MAX(o.order_date) AS last_order_date,
    DATEDIFF(day, MAX(o.order_date), CURRENT_DATE()) AS days_since_last_order
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY 1, 2, 3, 4;

-- Check dynamic table refresh status
SELECT 
    name,
    refresh_start_time,
    refresh_end_time,
    state,
    bytes_refreshed,
    data_metric_query_frequency
FROM information_schema.dynamic_table_refresh_history
WHERE name = 'DAILY_SALES_SUMMARY'
ORDER BY refresh_start_time DESC;

-- Monitor dynamic table lag
SELECT 
    name,
    CURRENT_LAG,
    TARGET_LAG,
    CASE 
        WHEN CURRENT_LAG > TARGET_LAG * 2 THEN 'CRITICAL'
        WHEN CURRENT_LAG > TARGET_LAG THEN 'WARNING'
        ELSE 'HEALTHY'
    END AS lag_status
FROM information_schema.dynamic_tables
WHERE name = 'DAILY_SALES_SUMMARY';

Streams (Change Data Capture)

Streams capture DML changes (INSERT, UPDATE, DELETE) on tables, providing a changelog for downstream processing.

The semantics candidates most often get wrong is consumption. A stream is not a queue you drain with SELECT โ€” it is an offset paired with the source table, and the only operation that advances the offset is DML executed against the stream in the same transaction as the writes to the target. Read the changes without writing and they remain available; write to the target from a separate session without touching the stream and you have either dropped the batch or double-counted it. That same rule is what delivers exactly-once processing: a MERGE that reads the stream and writes the target inside one transaction is atomic, so the offset advance and the target write succeed or fail together. Snowflake offers standard, append-only, and insert-only stream variants โ€” append-only is a real simplification when the source never deletes, because downstream logic stops needing to reason about remove events at all. Late arrival is a freshness question rather than a correctness question: events land when the producer lands them, so event-time fields belong in the target and consumers should recompute windows instead of trusting arrival order. The one operational limit to memorize is staleness โ€” a stream left unconsumed goes stale after 14 days and must be dropped and recreated, losing the backlog it held, which is why is_stale belongs on a monitoring dashboard rather than in a wiki.

Basic Stream Setup

-- Create a stream on a source table
CREATE OR REPLACE STREAM orders_stream
    ON TABLE orders
    SHOW_INITIAL_ROWS = FALSE
    APPEND_ONLY = FALSE
    INSERT_ONLY = FALSE
    OFFSET = NULL;

-- Check stream status
SELECT 
    stream_name,
    table_name,
    create_time,
    last_refreshed_time,
    is_stale,
    MODE
FROM information_schema.streams
WHERE stream_name = 'ORDERS_STREAM';

-- Query stream for changes
SELECT 
    METADATA$ACTION AS action,
    METADATA$ISUPDATE AS is_update,
    METADATA$ROW_ID AS row_id,
    order_id,
    customer_id,
    order_date,
    total_amount,
    status,
    CURRENT_TIMESTAMP() AS captured_at
FROM orders_stream;

-- Process stream and merge into target table
MERGE INTO orders_daily_summary t
USING (
    SELECT 
        DATE(order_date) AS sale_date,
        COUNT(*) AS new_orders,
        SUM(total_amount) AS new_revenue
    FROM orders_stream
    WHERE METADATA$ACTION = 'INSERT'
    GROUP BY 1
) s
ON t.sale_date = s.sale_date
WHEN MATCHED THEN
    UPDATE SET 
        order_count = t.order_count + s.new_orders,
        total_revenue = t.total_revenue + s.new_revenue,
        last_updated = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN
    INSERT (sale_date, order_count, total_revenue, last_updated)
    VALUES (s.sale_date, s.new_orders, s.new_revenue, CURRENT_TIMESTAMP());

Real-World Scenario: Amazon

Question: "Design a CDC pipeline that captures changes from a PostgreSQL database, loads them into Snowflake, and maintains a slowly changing dimension (SCD Type 2) table."

The SCD Type 2 logic below carries two sharp edges worth naming before you write any of it. A MERGE fails outright when the source contains two rows matching the same target row, so deduplicate the stream per key before the merge or the job dies on the first real data anomaly rather than on a test. And effective dates must be derived from the event timestamp, never from the load-time clock, or every backfill stamps rows with the moment the repair ran and the history stops meaning anything. Upstream, the landing pattern matters too: files from a change-data-capture outbox arrive in file order and roughly in commit order, but a Kafka-fed variant gives you offsets you can checkpoint, which is the difference between replayable and lossy when the pipeline restarts mid-batch.

Solution: End-to-End CDC Pipeline

-- 1. Create raw table for CDC events
CREATE TABLE raw_cdc_events (
    event_id VARCHAR(100),
    table_name VARCHAR(100),
    operation VARCHAR(10),  -- INSERT, UPDATE, DELETE
    before_data VARIANT,
    after_data VARIANT,
    lsn VARCHAR(100),  -- Log sequence number
    event_timestamp TIMESTAMP_NTZ,
    _ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);

-- 2. Create stream for CDC processing
CREATE OR REPLACE STREAM cdc_stream
    ON TABLE raw_cdc_events
    SHOW_INITIAL_ROWS = FALSE;

-- 3. Create SCD Type 2 target table
CREATE TABLE customers_scd (
    customer_id VARCHAR(100),
    customer_name VARCHAR(200),
    email VARCHAR(200),
    segment VARCHAR(50),
    effective_start_date TIMESTAMP_NTZ,
    effective_end_date TIMESTAMP_NTZ DEFAULT TO_TIMESTAMP_NTZ('9999-12-31'),
    is_current BOOLEAN DEFAULT TRUE,
    _ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);

-- 4. SCD Type 2 merge procedure
CREATE OR REPLACE PROCEDURE process_scd_type2()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    processed_count NUMBER DEFAULT 0;
BEGIN
    -- Process INSERT and UPDATE operations
    MERGE INTO customers_scd t
    USING (
        SELECT 
            after_data:customer_id::VARCHAR AS customer_id,
            after_data:customer_name::VARCHAR AS customer_name,
            after_data:email::VARCHAR AS email,
            after_data:segment::VARCHAR AS segment,
            event_timestamp
        FROM cdc_stream
        WHERE METADATA$ACTION = 'INSERT'
           OR (METADATA$ACTION = 'UPDATE' AND METADATA$ISUPDATE = TRUE)
    ) s
    ON t.customer_id = s.customer_id AND t.is_current = TRUE
    WHEN MATCHED AND (
        t.customer_name != s.customer_name OR
        t.email != s.email OR
        t.segment != s.segment
    ) THEN
        UPDATE SET 
            effective_end_date = s.event_timestamp,
            is_current = FALSE
    WHEN NOT MATCHED THEN
        INSERT (customer_id, customer_name, email, segment, effective_start_date)
        VALUES (s.customer_id, s.customer_name, s.email, s.segment, s.event_timestamp);

    -- Insert new current versions for updated records
    INSERT INTO customers_scd (customer_id, customer_name, email, segment, effective_start_date)
    SELECT 
        after_data:customer_id::VARCHAR,
        after_data:customer_name::VARCHAR,
        after_data:email::VARCHAR,
        after_data:segment::VARCHAR,
        event_timestamp
    FROM cdc_stream
    WHERE METADATA$ACTION = 'INSERT'
       OR (METADATA$ACTION = 'UPDATE' AND METADATA$ISUPDATE = TRUE)
    AND after_data:customer_id::VARCHAR IN (
        SELECT customer_id FROM customers_scd WHERE is_current = FALSE
    );

    -- Process DELETE operations
    UPDATE customers_scd
    SET is_current = FALSE,
        effective_end_date = CURRENT_TIMESTAMP()
    WHERE customer_id IN (
        SELECT before_data:customer_id::VARCHAR
        FROM cdc_stream
        WHERE METADATA$ACTION = 'DELETE'
    )
    AND is_current = TRUE;

    processed_count := SQLROWCOUNT;
    
    RETURN 'SCD Type 2 processing complete. Rows affected: ' || processed_count;
END;
$$;

-- 5. Schedule CDC processing
CREATE OR REPLACE TASK cdc_processing_task
    WAREHOUSE = etl_wh
    SCHEDULE = '1 MINUTE'
AS
    CALL process_scd_type2();

-- 6. Monitor CDC lag
SELECT 
    task_name,
    state,
    last_committed_on,
    scheduled_time
FROM information_schema.task_history
WHERE task_name = 'CDC_PROCESSING_TASK'
ORDER BY last_committed_on DESC;

Real-World Scenario: Netflix

Question: "How do you handle schema changes in a CDC pipeline? The source table adds a new column."

The answer below leans on the raw VARIANT envelope: because each CDC row is stored whole, a source-side column addition simply appears in the next event with no pipeline change, and the view layer above decides when to surface it to consumers. The companion monitoring query turns an upstream schema change into evidence โ€” distinct key sets over time with first-seen and last-seen timestamps โ€” which is how you answer the question "when did phone start appearing?" six months later without archaeology.

Schema Evolution in CDC

-- 1. Source table adds a new column
-- ALTER TABLE source.customers ADD COLUMN phone VARCHAR(20);

-- 2. Raw table stores all data as VARIANT
CREATE TABLE raw_cdc_events_v2 (
    event_id VARCHAR(100),
    table_name VARCHAR(100),
    operation VARCHAR(10),
    before_data VARIANT,
    after_data VARIANT,
    lsn VARCHAR(100),
    event_timestamp TIMESTAMP_NTZ,
    _ingestion_time TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);

-- 3. Stream automatically captures new columns in VARIANT
-- 4. Create view to extract known columns + handle new ones
CREATE OR REPLACE VIEW customers_extracted AS
SELECT 
    after_data:customer_id::VARCHAR AS customer_id,
    after_data:customer_name::VARCHAR AS customer_name,
    after_data:email::VARCHAR AS email,
    after_data:segment::VARCHAR AS segment,
    after_data:phone::VARCHAR AS phone,  -- New column
    after_data:address::VARCHAR AS address,  -- Potential future column
    METADATA$ACTION AS cdc_action,
    event_timestamp
FROM cdc_stream;

-- 5. Monitor for schema changes
SELECT 
    OBJECT_KEYS(after_data) AS columns_captured,
    COUNT(*) AS event_count,
    MIN(event_timestamp) AS first_seen,
    MAX(event_timestamp) AS last_seen
FROM raw_cdc_events
GROUP BY 1
ORDER BY 3 DESC;

Tasks & Scheduling

Tasks are where the pipeline meets time, and three details decide whether the schedule behaves. Cron expressions are evaluated in a named time zone, so a job written for 2 a.m. New York drifts relative to UTC and relative to an upstream load that runs on UTC โ€” pick one reference and document it. ALLOW_OVERLAPPING_EXECUTION decides whether a run that overruns its next scheduled time queues or waits; for anything touching the same tables you want it off, because two overlapping writers are how summary tables double-count. And a child task declaring its parent builds a DAG that commits in dependency order with no external orchestrator, which is the part most candidates forget exists. Failure handling is not optional: attach an error integration so a failed run raises an alert someone will see, and read task_history as the audit log that proves execution happened, not merely that a schedule was configured.

-- Create a task with complex scheduling
CREATE OR REPLACE TASK daily_etl_task
    WAREHOUSE = etl_wh
    SCHEDULE = 'USING CRON 0 2 * * * America/New_York'
    ALLOW_OVERLAPPING_EXECUTION = FALSE
    ERROR_INTEGRATION = 'SNOWFLAKE_ALERTS'
AS
BEGIN
    -- Step 1: Process CDC
    CALL process_cdc_events();
    
    -- Step 2: Update aggregations
    REFRESH DYNAMIC TABLE daily_sales_summary;
    
    -- Step 3: Run data quality checks
    CALL run_data_quality_checks('orders');
END;

-- Task dependencies
CREATE OR REPLACE TASK post_cdc_processing
    WAREHOUSE = analytics_wh
    AFTER daily_etl_task
AS
    CALL update_analytics_views();

-- Monitor task execution
SELECT 
    task_name,
    query_id,
    query_text,
    error_code,
    error_message,
    scheduled_time,
    completed_time,
    state
FROM information_schema.task_history
WHERE task_name IN ('DAILY_ETL_TASK', 'POST_CDC_PROCESSING')
  AND scheduled_time >= DATEADD(day, -1, CURRENT_TIMESTAMP())
ORDER BY scheduled_time DESC;

Best Practices

The table below is the checklist I would run before calling a CDC pipeline production-ready: freshness measured against a stated target, atomic consumption verified in the merge, raw events retained for replay, and every scheduled component alerting on failure rather than on hope.

PatternRecommendation
CDC frequencyUse 1-minute schedule for near-real-time, 5-minute for cost savings
SCD Type 2Use Streams + MERGE for incremental processing
Schema evolutionStore raw data as VARIANT, extract in views
Error handlingUse TRY/CATCH in stored procedures, alert on failures
MonitoringSet up alerts for task failures and lag exceeding thresholds
DeduplicationTrack LSN/offset to prevent duplicate processing

โš ๏ธ

Common Pitfalls:

  1. Stream staleness โ€” Streams become stale if not queried within 14 days
  2. Task overlap โ€” Use ALLOW_OVERLAPPING_EXECUTION = FALSE for sequential jobs
  3. Missing error handling โ€” Always handle errors in stored procedures
  4. Ignoring lag โ€” Monitor dynamic table lag and task execution times

Key Takeaways

  • A stream advances only when DML reads it and writes the target in one transaction โ€” that single rule is what makes CDC exactly-once instead of duplicate-or-lossy.
  • Dynamic tables declare SQL plus a target lag and let Snowflake plan refreshes; incremental versus full refresh is chosen by the engine, and DOWNSTREAM lag chains the DAG for you.
  • Keep raw CDC payloads as VARIANT so source-side schema additions arrive without pipeline changes, and monitor distinct key sets to detect when they do.
  • Streams go stale after 14 days unconsumed, tasks need an error integration and ALLOW_OVERLAPPING_EXECUTION off, and event timestamps โ€” not load clocks โ€” must date SCD versions.
๐Ÿ”’

Premium Content

Topic: Dynamic Tables, Streams & Tasks

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

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

Last reviewed: 2026-10-17

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement