3: Data Engineering

    Data Loading and Unloading Solutions

    The architect's first ingestion decision is not which command to type; it is which envelope of latency, throughput, ordering guarantee, and cost a given source workload requires. The Snowflake AI Data Cloud exposes three first-class ingestion paths into native columnar storage plus a separate read-only path through External Tables and Iceberg Tables that does not move data at all.

    Picking among them shapes everything that follows: file sizing, stage choice, file-format object, monitoring view, RBAC grants, and the recovery posture of the data once it lands. Get the envelope wrong and the operational pain shows up as either runaway serverless cost on a low-latency tier that did not need it, or as latency spikes when a batch path is pushed into near-real-time service.

    Architects working on Snowflake ingestion at scale also have to think in terms of file shape, not just file count. The optimizer ingests files in parallel across warehouse threads or serverless workers, and the unit of parallelism is the file, not the row.

    A single ten-gigabyte file ingested by a Medium warehouse will saturate one thread and waste the other seven; a thousand ten-kilobyte files will burn the same Medium warehouse on per-file overhead and never see scan parallelism. The published guidance puts the practical sweet spot at one hundred to two hundred and fifty megabytes of compressed data per file, which lets COPY INTO and Snowpipe both pack micro-partitions efficiently while keeping the per-file overhead in proportion to the payload.

    For high-volume streaming sources, the Snowpipe Streaming SDK packs rows into Snowflake-managed micro-partitions itself, which is why the file-size guidance does not apply to it.

    The third architect-level dimension is error handling. Production pipelines have to choose between two contradictory virtues: fast-fail correctness and load-everything-you-can resilience.

    Snowflake exposes this trade-off through ON_ERROR, VALIDATION_MODE, RETURN_FAILED_ONLY, and the ABORT_STATEMENT versus CONTINUE versus SKIP_FILE family of policies on COPY INTO, and through Snowpipe's load-history view for asynchronous error inspection.

    Strict consistency in a regulated pipeline points to ON_ERROR = 'ABORT_STATEMENT' and a pre-load VALIDATION_MODE = 'RETURN_ERRORS'. An analytics pipeline ingesting partner feeds with known dirty rows points to ON_ERROR = 'CONTINUE' plus a quarantine pattern using LOAD_HISTORY and VALIDATE.

    How it works

    The fourth dimension is the staging surface.

    • Internal stages live on Snowflake-managed storage, are billed with the rest of Snowflake storage, and remove the need for a storage integration.
    • External stages point at customer-owned S3, Azure Blob, or GCS buckets, require a storage integration with IAM trust, and let other consumers see the same files without going through Snowflake.

    Architect choices here cascade into governance: external stages need their bucket policies audited, internal stages need the right READ/WRITE grants on stage objects, and named file format objects centralize parser settings so a hundred COPY INTO statements do not each carry their own field-delimiter spec that drifts over time.

    Bulk Loading with COPY INTO Compared to Continuous Loading with Snowpipe and Snowpipe Streaming

    COPY INTO is the foundational bulk-load path. It runs inside a user-supplied virtual warehouse, scales by warehouse size, and is best for periodic ingestion where files arrive in batches and a load window is acceptable.

    It is synchronous from the caller's point of view: the statement returns when every targeted file has either loaded or failed, the load history is updated, and the result set summarizes per-file outcomes. Bulk loading is the right answer for nightly extracts, partner feeds with a clear arrival cadence, large historical backfills, and recovery scenarios where the operator needs deterministic control over which file went where.

    Snowpipe is the serverless continuous-ingestion service. It listens on a cloud-provider event source (S3 Event Notification through SQS, Azure Event Grid, or GCS Pub/Sub), picks up newly arrived files within seconds, and loads them through a Snowflake-managed compute pool that is billed per second of pipe execution rather than per warehouse-hour.

    The latency envelope is single-digit minutes from file arrival to row visibility for steady-state workloads, with no warehouse sizing knob to tune. Snowpipe is the right answer when the source emits files continuously at modest throughput per file, the latency requirement is minute-level, and the operations team does not want to babysit a warehouse schedule.

    Snowpipe Streaming is the row-level streaming path. It bypasses the file-based model entirely: a producer using the Snowflake Ingest SDK opens a channel against a target table, sends row batches over a long-lived gRPC connection, and Snowflake commits those rows into micro-partitions through a serverless ingest service.

    Latency drops to sub-second for the offset commit and a few seconds end-to-end for downstream visibility. There is no file, no stage, and no per-file overhead.

    Snowpipe Streaming is the right answer for Kafka or Kinesis taps that emit high-frequency, small-payload rows where building intermediate files would push latency above acceptable limits and waste object-storage round-trips.

    -- Bulk path: deterministic, warehouse-scheduled, large batches.
    USE WAREHOUSE INGEST_WH;
    USE ROLE LOADER_RW;
    
    COPY INTO CORE.SALES.FACT_ORDERS
    FROM @CORE.SALES.STG_ORDERS_EXT/orders/
    FILE_FORMAT = (FORMAT_NAME = CORE.SALES.FF_PARQUET_ORDERS)
    PATTERN = '.*orders_[0-9]{8}_part_[0-9]+\.parquet'
    ON_ERROR = 'ABORT_STATEMENT'
    PURGE = FALSE
    MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE;
    
    -- Continuous path: serverless pipe attached to a stage.
    CREATE OR REPLACE PIPE CORE.SALES.PIPE_ORDERS
     AUTO_INGEST = TRUE
     ERROR_INTEGRATION = CORE.SALES.PIPE_ERROR_NOTIF
    AS
    COPY INTO CORE.SALES.FACT_ORDERS
    FROM @CORE.SALES.STG_ORDERS_EXT/orders/
    FILE_FORMAT = (FORMAT_NAME = CORE.SALES.FF_PARQUET_ORDERS)
    MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE;
    
    -- Inspect pipe health.
    SELECT SYSTEM$PIPE_STATUS('CORE.SALES.PIPE_ORDERS');
    
    # Snowpipe Streaming via the Snowflake Ingest SDK.
    from snowflake.ingest import SimpleIngestManager
    from snowflake.ingest.utils.uris import DEFAULT_SCHEME
    from snowflake.ingest.streaming import SnowflakeStreamingIngestClientFactory
    
    props = {
     "scheme": DEFAULT_SCHEME,
     "host": "analytics_prod.snowflakecomputing.com",
     "user": "STREAM_LOADER",
     "role": "LOADER_RW",
     "private_key": "...",
     "port": 443,
    }
    
    client = SnowflakeStreamingIngestClientFactory.builder("orders_client").set_properties(props).build()
    channel = client.open_channel(
     db_name="CORE",
     schema_name="SALES",
     table_name="FACT_ORDERS_STREAM",
     channel_name="kafka_partition_07",
    )
    
    for row in kafka_consumer:
     channel.insert_row(row.value, offset_token=str(row.offset))
    
    channel.close()
    

    💡 Exam Trap: Snowpipe is not faster than COPY INTO; it is more frequent. A single COPY INTO on a Medium warehouse can move more bytes per second than Snowpipe, because Snowpipe optimizes for low end-to-end latency per file, not for raw throughput per second. If the requirement is "process a billion rows by 06:00", a scheduled COPY INTO on a sized-up warehouse usually beats Snowpipe on cost and wall-clock both.

    ⚠️ Anti-Pattern: Wiring Snowpipe to a producer that emits one-kilobyte files every two seconds. The per-file overhead dwarfs the payload, and the serverless bill climbs faster than a row-rate Snowpipe Streaming channel would. The right reach is Snowpipe Streaming, not a faster Snowpipe.

    Appropriate File Formats, File Sizes, and Folder Structures for Ingestion

    File format choice drives both ingest throughput and downstream query economics.

    • Parquet and ORC are columnar formats that carry their own schema metadata, support column pruning during load, and let Snowflake skip whole row groups when the COPY targets a subset of columns; they are the recommended formats for analytics ingest at scale.
    • CSV remains the lingua franca for partner exchange but offers no schema enforcement and pays a parsing tax on every load.
    • JSON and Avro land in VARIANT columns, retain semi-structured shape, and let downstream queries shred the structure with FLATTEN or path notation.
    • XML is supported but rarely justified outside legacy interchange; convert at the edge whenever feasible.

    File size targets balance two pressures.

    • Files that are too small (under a few megabytes compressed) cause per-file overhead to dominate, hurting both COPY INTO throughput and Snowpipe billing.
    • Files that are too large (over a few gigabytes compressed) cap parallelism: a single thread will work that file, while the rest of the warehouse sits idle.
    • The published target is one hundred to two hundred and fifty megabytes of compressed data per file for both COPY INTO and Snowpipe, which keeps each warehouse thread busy for a meaningful span without becoming an outlier in the load fleet.

    Producers that emit small frequent files should batch them in their staging layer before invoking COPY INTO. Producers that emit gigantic files should split them upstream using their writer's row-group or part-file controls.

    Folder structure matters for two reasons: stage globbing efficiency and downstream cost attribution. A flat folder of ten million files makes LIST @stage slow and exposes Snowpipe to S3 listing latency.

    A folder tree partitioned by load date, source, and producer keeps individual directories under a sane object count, lets COPY INTO ... FROM @stage/source=foo/dt=YYYY-MM-DD/ target a subset, and aligns with downstream External Table or Iceberg partition layout for hybrid topologies. The recommended layout is <root>/<source>/<event_type>/<yyyy>/<mm>/<dd>/<hh>/... for hot streaming sources and <root>/<source>/<yyyy-mm-dd>/... for daily batches.

    s3://analytics-prod-raw/
     orders/
     yyyy=2032/mm=03/dd=14/
     orders_20320314_part_001.parquet (~180 MB)
     orders_20320314_part_002.parquet (~210 MB)
     orders_20320314_part_003.parquet (~145 MB)
     inventory/
     yyyy=2032/mm=03/dd=14/
     inventory_20320314_part_001.parquet
     click_events/
     yyyy=2032/mm=03/dd=14/hh=09/
     click_events_20320314_09_part_0001.parquet (~95 MB)
    

    📊 Limit: Snowpipe's load-history view (COPY_HISTORY) retains entries for 14 days. Auditing older loads requires the INFORMATION_SCHEMA.LOAD_HISTORY table function for the live window and the SNOWFLAKE.ACCOUNT_USAGE.COPY_HISTORY view (with up to 365 days retention and approximately 45 minutes of latency) for historical analysis.

    Error-Handling Strategies for Data Loading

    COPY INTO exposes four ON_ERROR policies and three validation modes that together cover most ingestion postures.

    • ON_ERROR = 'ABORT_STATEMENT' (the default) fails the entire COPY at the first malformed row; the load is atomic from the operator's point of view, and the loaded-files set rolls back.
    • ON_ERROR = 'CONTINUE' skips bad rows on a per-row basis and reports them in the result set and in load history; the load succeeds with partial data.
    • ON_ERROR = 'SKIP_FILE' and ON_ERROR = 'SKIP_FILE_<n>' (or SKIP_FILE_<n>%) skip whole files when the first error is encountered, when more than n errors occur, or when more than n% of rows fail; the load succeeds for the remaining files.

    VALIDATION_MODE lets the architect dry-run a load:

    • RETURN_ERRORS reports every error in the matched files without writing data.
    • RETURN_<n>_ROWS validates the first n rows and returns them.
    • RETURN_ALL_ERRORS returns every parsing failure across all matched files.

    The recommended pattern in a production pipeline is to run COPY INTO with VALIDATION_MODE = 'RETURN_ERRORS' first, write the result to a quarantine table, then run the real load with the chosen ON_ERROR policy. The VALIDATE table function provides a similar after-the-fact view of the most recent load.

    -- Dry run, then real load, then quarantine inspection.
    COPY INTO CORE.SALES.FACT_ORDERS
    FROM @CORE.SALES.STG_ORDERS_EXT/orders/
    FILE_FORMAT = (FORMAT_NAME = CORE.SALES.FF_PARQUET_ORDERS)
    VALIDATION_MODE = 'RETURN_ERRORS';
    
    COPY INTO CORE.SALES.FACT_ORDERS
    FROM @CORE.SALES.STG_ORDERS_EXT/orders/
    FILE_FORMAT = (FORMAT_NAME = CORE.SALES.FF_PARQUET_ORDERS)
    ON_ERROR = 'SKIP_FILE_5%'
    RETURN_FAILED_ONLY = TRUE;
    
    SELECT *
    FROM TABLE(VALIDATE(CORE.SALES.FACT_ORDERS, JOB_ID => '_last'))
    ORDER BY ROW_NUMBER;
    

    Snowpipe error handling runs on a different axis because the load is asynchronous.

    The architect attaches an error notification integration to the pipe so that file-level failures publish to SNS, Event Grid, or Pub/Sub for downstream alerting, and inspects SYSTEM$PIPE_STATUS() for queue depth and recent load timestamps.

    Row-level errors inside Snowpipe behave per the pipe's ON_ERROR setting, defaulting to CONTINUE, with details surfaced through COPY_HISTORY.

    Snowpipe Streaming exposes per-row commit failures through SDK callbacks and per-channel offset tokens; the architect's pattern is to checkpoint the offset token in the producer's state store so a restart can resume without duplicate ingest.

    🎯 Scenario: A retail data engineering team is loading partner feeds from twelve vendors into RAW.PARTNERS. One vendor occasionally ships rows with malformed date strings. The team wants the bad rows isolated without failing the whole batch and without forcing every load to wait for vendor fixes. The architect-tier answer is ON_ERROR = 'CONTINUE' plus a quarantine table populated from VALIDATE(..., JOB_ID => '_last'), plus an alert wired off COPY_HISTORY rejected-row counts; running the load with ON_ERROR = 'ABORT_STATEMENT' would stall every vendor on every bad row.

    💡 Exam Trap: ON_ERROR = 'CONTINUE' does not silently swallow errors. The bad rows are recorded in the COPY result set, in COPY_HISTORY, and remain visible through VALIDATE; the architect's downstream job has to pick them up actively. Treating CONTINUE as "fire and forget" is the trap; the right framing is "load what loads, then audit."

    External Stages, Internal Stages, and Named File Format Objects

    Internal stages live on Snowflake-managed storage and come in three flavors.

    • Named internal stages (CREATE STAGE my_stage) are first-class schema objects with their own grants and persistence; they suit shared loading where the file set has to be visible to multiple roles or pipes.
    • User stages (@~) are private to a single user and have no DDL; they suit ad hoc loading from a workstation through SnowSQL PUT.
    • Table stages (@%mytable) are scoped to a single table and have no DDL; they suit loaders that always target the same table and want zero stage management.

    Internal stages remove the need for a storage integration, sit inside Snowflake's encryption boundary, and bill as part of storage rather than via the cloud provider.

    External stages point at customer-owned S3, Azure Blob, or GCS prefixes through a storage integration that holds the cloud-IAM trust relationship.

    The architect's pattern is to create one storage integration per cloud-provider trust boundary (typically one per AWS account or per Azure tenant), grant USAGE on the integration to a small set of object-owner roles, and then create per-domain external stages on top.

    External stages let non-Snowflake consumers see and produce the same files; they also let Snowflake act on data that already lives in an existing data lake without copying.

    The trade-off is the bucket policy surface: every external bucket adds an IAM audit obligation. Named file format objects are the third pillar.

    A file format object centralizes parser settings (delimiter, header rows, null markers, compression, timestamp format, error tolerance) under a single named handle that COPY INTO statements, Snowpipe pipes, and External Tables can reference.

    The architect-tier reason to use named file formats over inline format clauses is governance, not convenience: a hundred inline format specs drift, a single named format does not.

    When a vendor changes their CSV quote character, the fix is one ALTER FILE FORMAT against the named object, not a hundred grep-and-replace operations across DAG code.

    -- One storage integration per cloud-IAM trust boundary.
    CREATE OR REPLACE STORAGE INTEGRATION SI_AWS_RAW
     TYPE = EXTERNAL_STAGE
     STORAGE_PROVIDER = 'S3'
     ENABLED = TRUE
     STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/snowflake-raw-loader'
     STORAGE_ALLOWED_LOCATIONS = ('s3://analytics-prod-raw/');
    
    -- Named file format reused across pipes and ad hoc loads.
    CREATE OR REPLACE FILE FORMAT CORE.SALES.FF_PARQUET_ORDERS
     TYPE = PARQUET
     COMPRESSION = SNAPPY
     USE_LOGICAL_TYPE = TRUE
     TRIM_SPACE = FALSE;
    
    -- External stage scoped to one folder under the bucket.
    CREATE OR REPLACE STAGE CORE.SALES.STG_ORDERS_EXT
     URL = 's3://analytics-prod-raw/orders/'
     STORAGE_INTEGRATION = SI_AWS_RAW
     FILE_FORMAT = CORE.SALES.FF_PARQUET_ORDERS
     DIRECTORY = (ENABLE = TRUE);
    

    ⚠️ Anti-Pattern: Granting USAGE on a storage integration broadly across business-function roles. The integration is the IAM trust handle; anyone with USAGE can create a stage that reads the bucket. Restrict USAGE on integrations to a small dedicated owner role and let that role create stages that other roles read.

    Strategy for Unloading Data to Cloud Storage

    Unloading is the reverse of loading and uses COPY INTO <location> with similar file-format options.

    The architect's decisions are:

    • file size
    • compression
    • partitioning
    • the choice between an internal stage and an external stage as the target.

    For onward delivery to a partner or to a data lake outside Snowflake, the target is an external stage whose underlying bucket the consumer can read directly.

    For internal handoff between pipelines (rare on Snowflake because most handoffs happen inside the platform), an internal stage suffices. Compression and file size targets mirror the ingest guidance:

    • aim for one hundred to two hundred and fifty megabytes per compressed Parquet part file
    • use MAX_FILE_SIZE to control the upper bound
    • use PARTITION BY to split output by date or business key.

    Adding HEADER = TRUE is appropriate for CSV consumers; Parquet output carries its own schema.

    Use SINGLE = TRUE only when the consumer absolutely requires one file, because it caps the unload to a single warehouse thread and inflates wall-clock time.

    -- Unload daily orders to a partitioned external prefix.
    COPY INTO @CORE.SALES.STG_ORDERS_OUT/orders/dt=2032-03-14/
    FROM (
     SELECT * FROM CORE.SALES.FACT_ORDERS WHERE LOAD_DATE = '2032-03-14'
    )
    FILE_FORMAT = (TYPE = PARQUET COMPRESSION = SNAPPY)
    PARTITION BY (CHANNEL)
    MAX_FILE_SIZE = 268435456
    HEADER = FALSE;
    

    Decision Anchor: Choose COPY INTO for periodic batch ingest where a scheduled warehouse and deterministic per-file outcomes matter. Choose Snowpipe when files arrive continuously at modest rates and minute-level latency is acceptable.

    Choose Snowpipe Streaming when the source emits rows continuously at high frequency and sub-second to few-second latency is required. Choose External Tables or Iceberg Tables when the data should remain in place under an existing data lake catalog and querying is read-only.

    💡 Exam Trap: External Tables and Iceberg Tables are not ingestion paths; they expose existing files to SQL without copying. If the requirement is to land data into Snowflake-managed columnar storage with Time Travel, Fail-safe, and full DML, the answer is COPY INTO, Snowpipe, Snowpipe Streaming, or Iceberg with the Snowflake-managed catalog mode, not an External Table.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Snowflake - SnowPro Advanced Architect learning hub.