Expedition. Free, on-demand.

Technical tracks for practitioners, outcomes for leaders.

Spark is great at what it was built for: one DataFrame API for batch ETL, written as real code you can test and review. The problem is everything underneath it. Running it in production also means tuning clusters to be fast, stable, and affordable, which is work on top of the pipeline logic itself. Here is a recipe for Spark pipelines on Snowflake. Using a real workload, customer identity resolution, we will run existing PySpark on Snowflake with minimal changes using Snowpark Connect for Apache SparkTM, store every table as open Apache Iceberg™, deploy from Git, and run the whole pipeline as a single scheduled job. On Snowflake, the job runs on a warehouse, so there is no overhead to set partition counts or executor sizes.

First, the problem every Spark engineer recognizes.

1,000 tasks. Two didn't finish.

Every Spark engineer has lived through this: 998 of 1,000 tasks finish in under a minute. Two run for 40 minutes, with no errors and a healthy-looking cluster. Adding workers barely helps.

Data skew is one possible cause of straggler tasks: one hot join key (a NULL customer ID, an "unknown" region, one huge account) lands in a single partition, and no extra hardware can split work already bound to one task. The fixes are all manual: salting keys, tuning spark.sql.shuffle.partitions and AQE skew thresholds, broadcast hints that break when the "small" table grows, and hand-placed repartition() calls. None of it is business logic. It's the engineer doing the engine's job.

What changes when the engine does this work

Snowpark Connect for Apache Spark keeps the PySpark DataFrame and Spark SQL API you already write, but the work is executed by the Snowflake engine on a virtual warehouse rather than by Spark tasks on a cluster you size. That changes which of the tuning tasks above you manage yourself:

Common Spark tuning taskHow it works on Snowflake
Shuffle partitions and dynamic allocation, salting skewed keysThe engine distributes work across the warehouse, so you don't set partition counts or executor sizes
Broadcast hints that age badlyThe optimizer chooses the join strategy, so you don't set broadcast hints or thresholds
Partition layout, small-file compaction to keep predicate pushdown workingMicro-partition metadata or Iceberg file statistics are used to skip data that can't match
Executors killed due to memoryMemory pressure spills to storage, so a large join can run slower instead of failing
Redesigning for scaleScaling is a warehouse setting: size, multi-cluster for concurrency, and query acceleration for outlier queries
Analyzing the executor logsQuery Profile and query insights show where time is spent, by operator

Keep the data in an open table format, next to the AI that uses it

Skew is one visible symptom of running Spark somewhere else. Another is architectural. When pipelines run on a Spark platform and the curated data that analysts and AI applications consume lives in another system, pipelines often end with a copy. AI use cases often need detailed history, consistent governance, and traceable lineage, which gets harder to maintain across copies.

In this example, the pipeline writes Snowflake-managed Apache Iceberg™ tables, with Snowflake as the Iceberg catalog (Snowflake Horizon Catalog), and the data and metadata files stored in your own cloud storage through an external volume. Access control and governance features apply to these tables inside Snowflake. Whether other engines can read them depends on catalog access, storage permissions, and the consumer engine, none of which this post tests.

Why Spark, and why Snowpark Connect

Architecture diagram: Spark pipelines on Snowflake, with sources, notebooks, Git repository, Code Bundle, scheduled task, and Spark UI feeding identity resolution steps on Snowflake compute, Horizon Catalog, and lakehouse storage

Figure 1 - Running Spark workloads using Snowpark Connect for Apache Spark™

Spark is still the most widely used way to write data pipelines in code. One DataFrame API covers batch ETL, data quality, feature engineering, and large joins. It's plain Python or Scala that can be version-controlled, tested, and reviewed, it handles business logic that is awkward in pure SQL, and most data engineers already know it. The pain has never been Spark the API. It has been Spark the infrastructure.

With Snowpark Connect for Apache Spark™, you can submit your existing Spark workloads directly to Snowflake and run them on the Snowflake compute engine. Snowpark Connect for Spark supports the Spark DataFrame API and Spark SQL on Snowflake. All workloads run on a Snowflake warehouse, so you can run your Spark code with all the benefits of the Snowflake engine.

To make this concrete, let's build something that is famously painful on a Spark cluster: customer identity resolution.

Typical managed-Spark stackSnowflake
Spark executionClusters you size, tune, and upgradeSnowpark Connect on a virtual warehouse
DevelopmentOften notebooks on a cluster, exported to a repoNotebooks in Workspaces, connected to Git
DeploymentOften a build server that packages and copies artifactsA Git repository object in Snowflake, plus a stage that you copy a tagged release onto
OrchestrationOften a separately hosted workflow orchestratorA Snowflake task running a Code Bundle, for this single-job pipeline
StorageOften object-store buckets plus a separate catalogSnowflake-managed Iceberg tables on an external volume in your bucket
MonitoringSpark history server plus a cloud logging serviceSpark Monitoring UI(public preview) and Query Profile

The problem: one customer, three systems

Customer data scattered across CRM, e-commerce, and loyalty platforms often creates duplicate and inconsistent profiles. Discrepancies in formatting, missing details, and typos make unifying these records a critical challenge. Here is how modern pipelines efficiently resolve identities across disparate systems.

Step 1: Connect Snowflake to Git

The code lives in Git. Snowflake connects to the repository through an API integration and keeps a clone of it inside your account; the secret is only needed for a private repository.

CREATE OR REPLACE SECRET IDR_SPARK_PIPELINE.FRAMEWORK.GIT_PAT
  TYPE = password USERNAME = 'my-github-user' PASSWORD = '<github_pat_...>';

CREATE OR REPLACE API INTEGRATION IDR_GIT_API
  API_PROVIDER = git_https_api
  API_ALLOWED_PREFIXES = ('https://github.com/my-org')
  ALLOWED_AUTHENTICATION_SECRETS = (IDR_SPARK_PIPELINE.FRAMEWORK.GIT_PAT)
  ENABLED = TRUE;

CREATE OR REPLACE GIT REPOSITORY IDR_SPARK_PIPELINE.FRAMEWORK.IDR_REPO
  API_INTEGRATION = IDR_GIT_API
  GIT_CREDENTIALS = IDR_SPARK_PIPELINE.FRAMEWORK.GIT_PAT
  ORIGIN = 'https://github.com/my-org/idr-spark-pipeline.git';

Developers can work on the same repository from Snowsight with Projects » Workspaces » From Git repository, using notebooks on a feature branch.

Step 2: Write the matching logic in PySpark

The job reads an --env argument that picks the target schema (DEV or PROD), starts a Snowpark Connect session, and points Iceberg writes at an external volume, so the files land in your bucket while Snowflake acts as the Iceberg catalog. From there, it's ordinary PySpark.

import argparse
from pyspark.sql import functions as F
from snowflake.snowpark_connect import init_spark_session

parser = argparse.ArgumentParser()
parser.add_argument("--env", required=True, choices=["dev", "prod"])
SCHEMA = parser.parse_args().env.upper()

spark = init_spark_session(app_name=f"idr_{SCHEMA.lower()}")
spark.conf.set("snowpark.connect.iceberg.external_volume", "MY_EXT_VOL")
spark.conf.set("spark.sql.extensions",
               "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions")

First, each source is mapped onto the same columns and stacked into one records DataFrame. Then each record is standardized: phones reduced to ten digits, emails trimmed and lower-cased, and a Soundex code computed for the last name.

DB = "IDR_SPARK_PIPELINE"
crm = spark.table(f"{DB}.RAW.CRM_CUSTOMERS").select(
    F.lit("CRM").alias("source"), F.col("crm_id").alias("source_id"),
    "first_name", "last_name", "email", "phone", "street", "postal_code",
    F.col("updated_at").cast("timestamp").alias("source_ts"))
ecom = spark.table(f"{DB}.RAW.ECOM_USERS").select(
    F.lit("ECOM").alias("source"), F.col("user_id").alias("source_id"),
    F.col("fname").alias("first_name"), F.col("lname").alias("last_name"),
    F.col("email_address").alias("email"), F.col("mobile").alias("phone"),
    F.lit(None).cast("string").alias("street"), F.lit(None).cast("string").alias("postal_code"),
    F.col("last_login").cast("timestamp").alias("source_ts"))
loy = spark.table(f"{DB}.RAW.LOYALTY_MEMBERS").select(
    F.lit("LOYALTY").alias("source"), F.col("member_id").alias("source_id"),
    F.split("full_name", " ").getItem(0).alias("first_name"),
    F.split("full_name", " ").getItem(1).alias("last_name"),
    "email", F.col("phone_number").alias("phone"),
    F.col("address_line").alias("street"), F.col("zip_code").alias("postal_code"),
    F.current_timestamp().alias("source_ts"))

records = crm.unionByName(ecom).unionByName(loy)

digits = F.regexp_replace("phone", "[^0-9]", "")
phone10 = F.when(F.length(digits) == 11, F.substring(digits, 2, 10)).otherwise(digits)
std = (records
       .withColumn("record_key", F.concat_ws(":", "source", "source_id"))
       .withColumn("email_norm", F.lower(F.trim("email")))
       .withColumn("phone_norm", F.when(F.length(phone10) == 10, phone10))
       .withColumn("first_norm", F.lower(F.trim("first_name")))
       .withColumn("last_norm", F.lower(F.trim("last_name")))
       .withColumn("first_initial", F.substring("first_norm", 1, 1))
       .withColumn("last_soundex", F.soundex("last_norm"))
       .withColumn("phone_last4", F.substring("phone_norm", 7, 4)))

The deterministic rules become match keys: every record that shares a key is linked.

det_edges = (
    std.where(F.col("email_norm").isNotNull())
       .select("record_key", F.concat(F.lit("EMAIL:"), "email_norm").alias("match_key"))
    .unionByName(
    std.where(F.col("phone_norm").isNotNull())
       .select("record_key", F.concat(F.lit("PHONE:"), "phone_norm", F.lit(":"), "first_initial").alias("match_key"))))

The fuzzy rule is a self-join on the blocking key, scored with Levenshtein distance:

cols = ["record_key", "first_norm", "last_norm", "first_initial", "last_soundex", "postal_code", "phone_last4"]
a = std.select(*[F.col(c).alias(f"a_{c}") for c in cols])
b = std.select(*[F.col(c).alias(f"b_{c}") for c in cols])

pairs = (a.join(b, (F.col("a_last_soundex") == F.col("b_last_soundex"))
                   & (F.col("a_first_initial") == F.col("b_first_initial"))
                   & (F.col("a_record_key") < F.col("b_record_key")))
          .withColumn("first_dist", F.levenshtein("a_first_norm", "b_first_norm"))
          .withColumn("last_dist", F.levenshtein("a_last_norm", "b_last_norm"))
          .withColumn("same_zip", F.col("a_postal_code") == F.col("b_postal_code"))
          .withColumn("same_last4", F.col("a_phone_last4") == F.col("b_phone_last4")))

fuzzy_pairs = pairs.where(
    (F.col("last_dist") <= 1)
    & ((F.col("first_dist") <= 2) | (F.length("a_first_norm") == 1) | (F.length("b_first_norm") == 1))
    & F.coalesce(F.col("same_zip"), F.lit(False))
    & (F.coalesce(F.col("same_last4"), F.lit(True)) | (F.col("first_dist") == 0)))

pair_key = F.concat(F.lit("FUZZY:"), F.col("a_record_key"), F.lit("|"), F.col("b_record_key"))
fuzzy_edges = (fuzzy_pairs.select(F.col("a_record_key").alias("record_key"), pair_key.alias("match_key"))
               .unionByName(fuzzy_pairs.select(F.col("b_record_key").alias("record_key"), pair_key.alias("match_key"))))

edges = det_edges.unionByName(fuzzy_edges)

Finally, connected components turn pairwise links into identities with iterative min-label propagation:

labels = std.select("record_key", F.col("record_key").alias("cluster_id"))
for _ in range(6):
    key_min = edges.join(labels, "record_key").groupBy("match_key").agg(F.min("cluster_id").alias("k"))
    rec_min = edges.join(key_min, "match_key").groupBy("record_key").agg(F.min("k").alias("cand"))
    labels = (labels.join(rec_min, "record_key", "left")
                    .select("record_key", F.least("cluster_id", F.coalesce("cand", "cluster_id")).alias("cluster_id")))

match_rules = (edges.withColumn("rule", F.split("match_key", ":").getItem(0))
                    .groupBy("record_key").agg(F.collect_set("rule").alias("matched_by")))

matched = (std.join(labels, "record_key")
              .join(match_rules, "record_key", "left")
              .withColumn("customer_uid", F.sha2("cluster_id", 256).substr(1, 16)))

Look at what that code does: a self-join on a Soundex code (Smith, Smyth, and Schmidt all land in the same block), a groupBy on match keys where popular emails and phones concentrate, and six rounds of repeated joins. On a Spark cluster, this is a pattern where you might need to salt keys and tune shuffle partitions. Here, you don't set those yourself: the Snowflake engine plans and distributes the joins and aggregations. The resolved customer record keeps the best value for each attribute (CRM first, then loyalty, then e-commerce), and is written as a partitioned Iceberg table using the DataFrameWriterV2 API (public preview), with a tag (public preview) on the snapshot:

ranked = matched.withColumn("src_rank", F.when(F.col("source") == "CRM", 1)
                                   .when(F.col("source") == "LOYALTY", 2).otherwise(3))
best = lambda c: F.min_by(F.col(c), F.when(F.col(c).isNotNull(), F.col("src_rank")).otherwise(99))

customer_360 = ranked.groupBy("customer_uid").agg(
    F.initcap(best("first_norm")).alias("first_name"),
    F.initcap(best("last_norm")).alias("last_name"),
    best("email_norm").alias("email"),
    best("phone_norm").alias("phone"),
    best("postal_code").alias("postal_code"),
    F.collect_set("source").alias("sources"),
).withColumn("resolved_at", F.current_timestamp())

(customer_360.writeTo(f"{DB}.{SCHEMA}.CUSTOMER_360")
    .using("iceberg")
    .tableProperty("comment", "Resolved customer 360 record")
    .partitionedBy(F.days("resolved_at"))
    .createOrReplace())

spark.sql(f"ALTER TABLE {DB}.{SCHEMA}.CUSTOMER_360 CREATE TAG baseline_run")

That tag is more useful than it looks. Before you change a matching rule, the tagged snapshot is your baseline, and you can read it back later to see exactly which customers merged or split:

before = spark.read.format("iceberg").option("tag", "baseline_run").load("IDR_SPARK_PIPELINE.DEV.CUSTOMER_360")

Step 3: Run it as one Code Bundle, on one task

The whole pipeline is one Spark job, run by one EXECUTE CODE BUNDLE statement in one scheduled task. Code Bundles run from a stage, so deployment is two separate steps that you run yourself: a release step that fetches the Git repository and copies a tagged version of the job onto an internal stage, and the task, which runs the staged code on warehouse compute. Snowflake does not sync the repository to the stage on its own, so re-run the release statements to promote a new tag.

CREATE STAGE IF NOT EXISTS IDR_SPARK_PIPELINE.FRAMEWORK.JOBS;

ALTER GIT REPOSITORY IDR_SPARK_PIPELINE.FRAMEWORK.IDR_REPO FETCH;
COPY FILES INTO @IDR_SPARK_PIPELINE.FRAMEWORK.JOBS/framework/
  FROM @IDR_SPARK_PIPELINE.FRAMEWORK.IDR_REPO/tags/v1.0.0/framework/;

CREATE OR REPLACE TASK IDR_SPARK_PIPELINE.FRAMEWORK.IDR_PIPELINE
  WAREHOUSE = COMPUTE_WH
  SCHEDULE = 'USING CRON 0 2 * * * UTC'
AS
  EXECUTE CODE BUNDLE FROM '@IDR_SPARK_PIPELINE.FRAMEWORK.JOBS/framework'
    ENTRYPOINT = 'idr_job.py'
    ARGUMENTS = ('--env', 'prod')
    WITH SPECIFICATION $$
bundle:
  type: spark
  compute_type: warehouse
  language: python
  compute_options: {}
  properties:
    python_dependencies:
      packages:
        - snowpark-connect-deps-iceberg
$$;

ALTER TASK IDR_SPARK_PIPELINE.FRAMEWORK.IDR_PIPELINE RESUME;

The snowpark-connect-deps-iceberg package is what enables Iceberg Spark SQL such as CREATE TAG inside a Code Bundle.

The fuzzy rule links profiles that lack exact identifiers. On the synthetic data in this example, the blocking key, edit-distance thresholds, and postal-code check produced no false merges; tune the thresholds against your own data.

Every run shows up in Snowsight under Monitoring » Spark » Batch Jobs, with the submitted SQL, the queries it issued, its logs, and an OpenTelemetry trace with one span per DataFrame action, each linked to its Query Profile.

The customer profile is ready for the downstream application

Identity resolution output is often exported: a file to the ML platform, a sync to the analytics tool, a copy for the AI team. Each copy can go stale, drift from the governance on the source, and add another pipeline to maintain.

In this example, the job writes CUSTOMER_360 as a Snowflake-managed Iceberg table. Once the task finishes, Snowflake users and Snowflake AI and ML features can query it in place, subject to their access privileges. Consumers outside Snowflake need separate catalog and storage access.

Conclusion

Hand-tuning around skew-driven stragglers is work the engine should be doing. Snowpark Connect keeps the PySpark you already write, including the self-joins, fuzzy matching, and iterative graph logic that identity resolution needs, and runs it on the Snowflake engine instead of a cluster size. Git integration, one Code Bundle on one task, and Iceberg tables in your own storage cover deployment and storage, so the data stays open and sits next to the AI that uses it.

References

Updated Nov 30, 2026

This content is provided as is, and is not maintained on an ongoing basis. It may be out of date with current Snowflake instances