Spark & PySpark
PySpark Transformation Internals: Joins, Shuffles, and the Skew Problem That’s Already in Your…
DataForge Series: Databricks Data Engineer Associate - Part 6 of 16
PySpark Transformation Internals: Joins, Shuffles, and the Skew Problem That’s Already in Your Pipeline
DataForge Series: Databricks Data Engineer Associate - Part 6 of 16
The Spark UI shows 199 tasks completed in under 30 seconds each. One task has been running for 47 minutes.
You’re not out of memory. You’re not hitting a timeout. The job is running — just on one executor, processing one partition, while 199 other executors sit idle waiting for it to finish. The stage can’t complete until that last task does. The entire downstream pipeline is blocked.
This is data skew. It doesn’t crash your job. It doesn’t throw an error. It just makes one task arbitrarily slow while making your cluster arbitrarily expensive — because you’re paying for 200 executors and using 1.
Understanding why this happens, how to detect it in the Spark UI, and how to fix it requires understanding how Spark physically executes joins and shuffles. Not at the API level — at the execution level. What actually moves across the network. What determines partition size. Why some keys create bottlenecks that no amount of additional compute can solve.
Let’s go deep.
TL;DR
PySpark join performance is determined by the physical execution strategy Spark chooses — or that you force. Broadcast joins avoid shuffles entirely for small tables. Shuffle hash joins and sort-merge joins redistribute data across the network, creating bottlenecks when data is skewed. Understanding which strategy Spark uses and why is the difference between a 2-minute join and a 47-minute one.
By the end of this article you’ll be able to:
- Explain how each join strategy works physically — what moves across the network and what stays local
- Identify data skew from Spark UI stage metrics and trace it to a specific join key
- Apply the correct fix for skew — salting, broadcast, AQE skew handling — based on the root cause
- Reason through the exam’s performance scenario questions by eliminating wrong answers through execution model understanding
Exam relevance: PySpark transformation performance appears in ~5–7 questions. The exam presents Spark UI metrics and asks you to diagnose and fix the bottleneck. Sample Question 1 in the official exam guide is exactly this scenario — max shuffle read 5GB vs median 400MB, one slow task. The correct answer requires understanding skew, not just knowing that AQE exists.

The Problem: Spark’s Execution Model Is Not What the API Suggests
The PySpark API is deceptively clean.
result = orders.join(customers, on="customer_id", how="inner")One line. Looks like a database join. The physical execution underneath that line involves network transfers, partition redistribution, sort operations, and memory pressure that the API completely hides.
The gap between what the API looks like and what actually happens at execution time is where every PySpark performance problem lives.
To understand join performance, you need to understand three things: how partitioning works, what a shuffle actually does, and how join strategies differ in what they move across the network.
Partitioning: The Foundation Everything Else Builds On
Spark distributes data across executors by dividing it into partitions — chunks of rows that each executor processes independently. The number of partitions determines parallelism. The size of partitions determines whether that parallelism is balanced or broken.
# Check current partition count
print(df.rdd.getNumPartitions())
# Repartition - triggers a full shuffle
df_repartitioned = df.repartition(200, "customer_id")
# Coalesce - reduces partitions without full shuffle (narrow transformation)
df_coalesced = df.coalesce(50)The partition count tension:
Too few partitions → each partition is large → tasks take long → parallelism wasted. Too many partitions → each partition is tiny → task scheduling overhead dominates → throughput wasted.
The default spark.sql.shuffle.partitions = 200 is a historical default that made sense for clusters of a specific size in 2015. For a 4-node cluster processing 500MB of data, 200 shuffle partitions means 200 tasks processing 2.5MB each — overhead dominated. For a 20-node cluster processing 500GB, 200 shuffle partitions means 200 tasks processing 2.5GB each — memory pressure dominated.
The correct approach: set shuffle partitions based on data volume and cluster size, not the default.
# Rule of thumb: target 128MB-256MB per partition after shuffle
# For 100GB data on 20 executors: ~400-800 partitions
spark.conf.set("spark.sql.shuffle.partitions", "400")
# Or let AQE handle it dynamically (covered later)
spark.conf.set("spark.sql.adaptive.enabled", "true")The Shuffle: What Actually Happens Across the Network
A shuffle is Spark’s mechanism for redistributing data across executors when the computation requires rows with the same key to be on the same executor. Joins on a key, groupBy aggregations, and repartition operations all trigger shuffles.
Walk through what a shuffle physically does:
DataFrame A: 200 partitions, distributed across 20 executors
DataFrame B: 150 partitions, distributed across 20 executors
Join condition: A.customer_id = B.customer_id
For the join to work:
All rows with customer_id = "C001" must be on the SAME executor
All rows with customer_id = "C002" must be on the SAME executor
... for every customer_id value
Shuffle phase:
Step 1 — Map phase:
Each executor reads its partitions
Applies hash function to join key: hash("C001") % 200 = partition 47
Writes rows to local shuffle files, grouped by target partition
Step 2 — Transfer phase:
Each executor fetches its assigned partitions from ALL other executors
Network transfer: every executor talks to every other executor
Peak network load: O(executors²) connections
Step 3 — Reduce phase:
Each executor now has all rows for its assigned key range
Join can execute locally — no more network needed
Result: 200 new partitions, one per shuffle partition numberWhy shuffles are expensive:
The transfer phase moves data across the network. For a 100GB join, potentially 100GB of data crosses executor-to-executor connections. Network bandwidth is finite. At scale, shuffles are the primary bottleneck in most Spark jobs — not CPU, not memory, network.
The operational implication: every unnecessary shuffle is a tax on job performance. The goal of join optimization is to eliminate shuffles where possible and minimize data movement where shuffles are unavoidable.
Broadcast Join: Eliminating the Shuffle Entirely
When one side of a join is small enough to fit in executor memory, Spark can send a complete copy of it to every executor. Each executor then does the join locally against its partition of the large table — no shuffle required.
from pyspark.sql.functions import broadcast
# Force a broadcast join
result = large_orders.join(
broadcast(small_customers),
on="customer_id",
how="inner"
)How Broadcast Join Actually Works
Before broadcast join:
large_orders: 500GB, 2000 partitions across 20 executors
small_customers: 50MB, 10 partitions across 20 executors
Broadcast phase:
Step 1: Driver collects small_customers → 50MB in driver memory
Step 2: Driver broadcasts 50MB to ALL 20 executors
Step 3: Each executor stores 50MB copy in executor memory
Join phase:
Each executor joins its partition of large_orders
against its LOCAL copy of small_customers
No network transfer of large_orders data
No shuffle
Result: 2000 output partitions, zero shuffle overheadThe automatic threshold:
Spark automatically broadcasts tables below spark.sql.autoBroadcastJoinThreshold (default: 10MB) — but only if the optimizer has accurate size statistics. Tables below 10MB with current statistics get broadcast without any explicit hint.
# Raise threshold if you have tables in the 10-100MB range
# that benefit from broadcast
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", str(100 * 1024 * 1024)) # 100MB
# Disable automatic broadcast (useful for debugging)
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "-1")Where broadcast joins break:
The table being broadcast must fit in executor memory — not just driver memory. A 50MB table broadcast to 20 executors consumes 50MB × 20 = 1GB of aggregate memory. For a cluster with 8GB per executor and many concurrent jobs, this is usually fine. For very large broadcast tables (500MB+), executor OOM becomes a real risk.
The other failure mode: the driver must collect the broadcast table before distributing it. If the broadcast table is computed from a complex query, the driver collection step adds latency to every job — even if the broadcast itself is fast.
Sort-Merge Join: The Default for Large Table Joins
When both sides of a join are too large to broadcast, Spark defaults to a sort-merge join. This requires a full shuffle of both tables, followed by a sort on the join key, followed by a merge pass.
Sort-merge join execution:
Phase 1 — Shuffle both tables:
large_orders (500GB) → shuffled by customer_id hash → 200 partitions
large_customers (100GB) → shuffled by customer_id hash → 200 partitions
Network: 600GB of data crosses the network
Phase 2 — Sort within each partition:
Each executor sorts its assigned partition by customer_id
CPU + memory intensive: requires sortable data fit in executor memory
Phase 3 — Merge pass:
Each executor walks through its sorted partition of orders
and its sorted partition of customers simultaneously
Outputs matching rows — efficient linear scan
Result: 200 output partitions, correct join outputWhy sort-merge is the default: it’s reliable, memory-efficient (streaming merge doesn’t require holding entire partition in memory at once), and scales to arbitrarily large tables. It’s slow because of the double shuffle — but it’s correct at any scale.
The configuration that matters:
# spark.sql.shuffle.partitions controls output partition count
# for sort-merge join — this affects post-join data distribution
spark.conf.set("spark.sql.shuffle.partitions", "400")
# Enable sort-merge join explicitly (usually default)
spark.conf.set("spark.sql.join.preferSortMergeJoin", "true")Data Skew: Why One Task Takes 47 Minutes
Data skew is the condition where the hash function used to assign rows to shuffle partitions produces dramatically uneven partition sizes. One partition gets millions of rows. Others get thousands.
The cause is almost always a high-cardinality imbalance in the join key — a small number of key values that appear in a disproportionate fraction of the rows.
Customer join key distribution (skewed):
customer_id row_count % of total
──────────────────────────────────────
C_UNKNOWN 8,500,000 42% ← null/default value
C_001 1,200,000 6%
C_002 800,000 4%
C_003 750,000 3.7%
... (10,000 other customers, ~2M rows total, 1%)After shuffling by customer_id:
Partition 147 (hash of "C_UNKNOWN"): 8,500,000 rows → 45 min task
Partition 23 (hash of "C_001"): 1,200,000 rows → 6 min task
Partition 89 (hash of "C_002"): 800,000 rows → 4 min task
... (197 other partitions): ~10,000 rows each → 30 sec tasksThe stage doesn’t complete until partition 147 finishes. 199 executors wait.
Reading Skew in the Spark UI
The Spark UI’s stage detail view shows task-level metrics. Skew produces a specific pattern:
Stage 12 — Sort Merge Join
Tasks: 200
Duration: 47 min 23 sec
Task summary:
Metric Min 25th % Median 75th % Max
──────────────────────────────────────────────────────
Duration 0.3s 0.4s 0.5s 0.8s 47m 23s
Shuffle Read 18MB 22MB 400MB 420MB 5.1GB
Records Read 8,200 9,100 180,000 185,000 8,500,000The diagnostic pattern: median shuffle read is 400MB, max is 5.1GB. Median duration is 0.5 seconds, max is 47 minutes. This is the exact pattern from Sample Question 1 in the official exam guide. One partition is 12.75× larger than the median. That’s the skewed key.
Fixing Skew: Three Strategies
Strategy 1 — Adaptive Query Execution (AQE) Skew Handling
AQE is Spark’s runtime optimizer. With skew join handling enabled, AQE detects oversized partitions during execution and automatically splits them into smaller sub-partitions.
# Enable AQE with skew join handling
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")
# Tune detection thresholds
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "5")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes", "256MB")AQE splits any partition that is both:
- More than
skewedPartitionFactor× median partition size - Larger than
skewedPartitionThresholdInBytes
When a skewed partition is detected, AQE splits it into sub-partitions and duplicates the corresponding non-skewed side to match. The join executes on the sub-partitions in parallel.
What AQE handles well: moderate skew where the skewed partition is 5–20× the median. Automatic, no code changes required.
What AQE doesn’t solve: extreme skew where a single key value accounts for 40%+ of the data. AQE can split the partition but the sub-partitions are still larger than ideal. And AQE can’t fix skew caused by NULL keys — NULLs hash to the same partition and AQE doesn’t know they’re semantically meaningless.
Strategy 2 — Salting: Manual Skew Distribution
Salting artificially increases key cardinality by appending a random integer to the skewed key. The skewed partition gets split across N salt values — N tasks instead of 1.
from pyspark.sql.functions import col, concat, lit, floor, rand, explode, array
SALT_FACTOR = 10
# Salt the large (skewed) table
orders_salted = large_orders.withColumn(
"salted_key",
concat(col("customer_id"), lit("_"), (floor(rand() * SALT_FACTOR)).cast("string"))
)
# Explode the small table to match all salt values
customers_exploded = small_customers.withColumn(
"salt",
explode(array([lit(i) for i in range(SALT_FACTOR)]))
).withColumn(
"salted_key",
concat(col("customer_id"), lit("_"), col("salt").cast("string"))
)
# Join on salted key
result = orders_salted.join(
customers_exploded,
on="salted_key",
how="inner"
).drop("salted_key", "salt")What this does: customer C_UNKNOWN with 8.5M rows becomes C_UNKNOWN_0 through C_UNKNOWN_9 — 850,000 rows each across 10 partitions instead of 8.5M rows in one partition. The 47-minute task becomes ten 4.7-minute tasks running in parallel.
The cost: the small/lookup table is exploded 10×. If customers was 50MB, it becomes 500MB after exploding. This is still broadcastable for most cluster configurations — but it’s a real memory cost.
When to use salting vs AQE: use AQE first — it’s automatic and requires no code changes. Use salting when AQE’s automatic detection isn’t handling the skew effectively, when you know the skewed keys in advance, or when the skew is so extreme (40%+ in one key) that AQE’s sub-partition approach still leaves partitions too large.
Strategy 3 — Filter and Union: Isolating the Skewed Key
When the skewed key is known (NULL values, a specific default value, a known high-cardinality entity), handle it separately.
# Separate skewed key from normal keys
orders_normal = large_orders.filter(col("customer_id") != "C_UNKNOWN")
orders_skewed = large_orders.filter(col("customer_id") == "C_UNKNOWN")
# Normal join — AQE or sort-merge handles this cleanly
result_normal = orders_normal.join(customers, on="customer_id", how="inner")
# Skewed join — broadcast the customers side for the skewed key
# (customers for C_UNKNOWN is a single row — trivially broadcastable)
result_skewed = orders_skewed.join(
broadcast(customers.filter(col("customer_id") == "C_UNKNOWN")),
on="customer_id",
how="inner"
)
# Recombine
result = result_normal.union(result_skewed)This isolates the pathological case from the normal execution path. The skewed partition gets a broadcast join (zero shuffle). The normal partitions get a standard sort-merge join.
When to use this: when the skewed key is semantically distinct (NULL/unknown values that need different handling anyway), or when you want explicit control over the execution strategy for known problem keys.
Other Join Types: Cross Joins, Multiple Keys, Union
Cross Join
A cross join produces the Cartesian product — every row in table A joined with every row in table B. No join condition.
# Cross join — explicit, required keyword
result = table_a.crossJoin(table_b)
# SQL equivalent
spark.sql("SELECT * FROM table_a CROSS JOIN table_b")The scale explosion: 1,000 rows × 1,000 rows = 1,000,000 output rows. 1M rows × 1M rows = 1 trillion output rows. Cross joins are legitimate for generating combinations (test data, feature crosses) but catastrophic if accidentally triggered by a missing join condition. Spark requires explicit .crossJoin() syntax — a missing on condition doesn't silently produce a cross join, it throws an error.
Multiple Key Joins
# Join on multiple keys — all keys must match
result = orders.join(
customers,
on=["customer_id", "region_code"],
how="inner"
)
# Equivalent explicit condition
result = orders.join(
customers,
(orders.customer_id == customers.customer_id) &
(orders.region_code == customers.region_code),
how="inner"
)Multiple key joins reduce skew risk — the combined hash of two keys produces more even distribution than a single key. If customer_id is skewed but region_code is evenly distributed, the compound key (customer_id, region_code) may distribute more evenly.
Union vs Union All
# union() — removes duplicates (triggers a shuffle)
result = df1.union(df2).distinct()
# unionAll() / union() without distinct — keeps all rows (no shuffle)
result = df1.unionAll(df2)
# Note: in PySpark, union() and unionAll() both keep duplicates
# Use .distinct() explicitly if deduplication is neededunion in PySpark does NOT automatically deduplicate — it's equivalent to SQL UNION ALL. To get SQL UNION behavior (deduplication), call .distinct() after .union(). This is a common API misconception that produces duplicate rows in Silver tables without any error.
Deduplication Operations
Deduplication is a common Silver layer operation — removing exact duplicates from Bronze ingestion.
# Simple deduplication — remove exact duplicate rows
df_deduped = df.dropDuplicates()
# Deduplication on specific columns (keep first occurrence)
df_deduped = df.dropDuplicates(["event_id", "user_id"])
# Deduplication keeping latest record per key (window function approach)
from pyspark.sql.functions import row_number, desc
from pyspark.sql.window import Window
window = Window.partitionBy("event_id").orderBy(desc("event_ts"))
df_deduped = df \
.withColumn("rn", row_number().over(window)) \
.filter(col("rn") == 1) \
.drop("rn")The window function approach is the correct pattern when you need the latest record per key — not just any record. dropDuplicates() keeps an arbitrary row when duplicates exist. The window function guarantees you keep the most recent one.
The shuffle cost of deduplication: dropDuplicates() triggers a shuffle — all rows with the same key must be on the same executor to identify duplicates. For a 100GB Bronze table, deduplication may involve 100GB of shuffle. Partition the deduplication operation on the likely duplicate key to reduce shuffle data volume.
Aggregation Operations
from pyspark.sql.functions import count, approx_count_distinct, avg, mean, summary
# Standard aggregations
df.groupBy("event_type").agg(
count("*").alias("event_count"),
avg("duration_ms").alias("avg_duration"),
approx_count_distinct("user_id").alias("approx_unique_users")
)
# Summary statistics
df.select("duration_ms", "response_size").summary().show()
# Outputs: count, mean, stddev, min, 25%, 50%, 75%, maxapprox_count_distinct vs count(distinct):
count(distinct user_id) requires collecting all unique values to count them — expensive for high-cardinality columns, triggers a large shuffle.
approx_count_distinct("user_id") uses HyperLogLog — a probabilistic algorithm that produces a count within ~2% accuracy using a fraction of the memory. For analytics use cases where exact counts aren't required (dashboard metrics, trend analysis), approx_count_distinct is significantly cheaper and faster.
# Exact count — expensive, shuffles all values
df.agg(countDistinct("user_id"))
# Approximate count — fast, ~2% error
df.agg(approx_count_distinct("user_id", rsd=0.02))The exam tests this distinction directly — a scenario asking for a “distinct user count” where performance matters has approx_count_distinct as the answer when exact precision isn't specified.
Column and Row Manipulation
The Silver layer transformation pattern: read Bronze, clean, standardize, write Silver.
from pyspark.sql.functions import (
col, lit, when, coalesce, split, explode,
upper, lower, trim, regexp_replace,
to_timestamp, cast
)
# Add, rename, drop columns
df_silver = df_bronze \
.withColumn("event_date", to_timestamp(col("event_ts_str"), "yyyy-MM-dd HH:mm:ss")) \
.withColumnRenamed("usr_id", "user_id") \
.drop("_rescued_data", "raw_payload")
# Null handling
df_silver = df_silver \
.withColumn("region", coalesce(col("region"), lit("UNKNOWN"))) \
.filter(col("event_id").isNotNull())
# String standardization
df_silver = df_silver \
.withColumn("email", lower(trim(col("email")))) \
.withColumn("phone", regexp_replace(col("phone"), "[^0-9]", ""))
# Split a column into multiple columns
df_silver = df_silver \
.withColumn("parts", split(col("full_name"), " ")) \
.withColumn("first_name", col("parts")[0]) \
.withColumn("last_name", col("parts")[1]) \
.drop("parts")
# Explode arrays — one row per array element
df_exploded = df_silver \
.withColumn("tag", explode(col("tags"))) \
.drop("tags")
# Filter rows
df_silver = df_silver \
.filter(col("event_type").isin(["click", "view", "purchase"])) \
.filter(col("duration_ms") > 0)How Spark Executes Your Transformations: The Physical Plan
Every PySpark transformation produces a logical plan. Spark’s Catalyst optimizer converts it to a physical plan. Understanding the physical plan explains why some transformations are cheap and others are expensive.
# View the physical execution plan
df.join(other_df, on="key").groupBy("col").count().explain(mode="formatted")== Physical Plan ==
AdaptiveSparkPlan (1) ← AQE wrapper
+- HashAggregate (2) ← Final aggregation (reduce side)
+- Exchange (3) ← SHUFFLE — network transfer here
+- HashAggregate (4) ← Partial aggregation (map side)
+- SortMergeJoin (5) ← JOIN strategy chosen by optimizer
:- Exchange (6) ← SHUFFLE of left table
: +- Scan (7) ← Read left table from storage
+- Exchange (8) ← SHUFFLE of right table
+- Scan (9) ← Read right table from storageReading the plan: every Exchange node is a shuffle. Two Exchange nodes before a SortMergeJoin means both tables were shuffled. If the optimizer had chosen a broadcast join, one of those Exchange nodes would be replaced by a BroadcastExchange— which sends data to all executors rather than redistributing it.
The practical use: when a job is slow, run explain() before optimizing. Find the Exchange nodes. Determine if any of them can be eliminated (broadcast) or reduced (better partitioning). Don't optimize blindly — optimize what the physical plan tells you is expensive.
Architecture Flow: Bronze to Silver Transformation Pipeline
Bronze Delta Table (raw, append-only)
│
▼
┌──────────────────────────────────────────────────────┐
│ Silver Transformation Pipeline │
│ │
│ 1. Read Bronze │
│ spark.read.format("delta").load(bronze_path) │
│ │
│ 2. Clean and standardize │
│ ├── Null handling (coalesce, filter) │
│ ├── Type casting (to_timestamp, cast) │
│ ├── String normalization (trim, lower, regexp) │
│ └── Column rename/drop │
│ │
│ 3. Deduplicate │
│ └── dropDuplicates() or window function │
│ (triggers shuffle — partition on dup key) │
│ │
│ 4. Join enrichment tables │
│ ├── Small table → broadcast join (no shuffle) │
│ ├── Large table → sort-merge join (shuffle) │
│ └── Skewed key → AQE or salting │
│ │
│ 5. Aggregate (if Gold layer) │
│ └── groupBy → agg → approx_count_distinct │
│ (shuffle — set shuffle.partitions correctly) │
│ │
│ 6. Write Silver │
│ df.write.format("delta") │
│ .mode("overwrite" or "append") │
│ .partitionBy("event_date") │
│ .save(silver_path) │
└──────────────────────────────────────────────────────┘
│
▼
Silver Delta Table (cleaned, typed, deduplicated)Failure Modes You’ll See in Production
Skew causing single-task bottleneck. The 47-minute task scenario from the opening. Always check median vs max shuffle read in Spark UI stage metrics. If max is 5–10× the median, skew is the cause. AQE first, salting if AQE isn’t sufficient.
Accidental cross join from missing condition. A join with a malformed condition produces a cross join. In Spark, a missing join key doesn’t silently produce a Cartesian product — it raises an AnalysisException. But a condition that accidentally evaluates to always-true (a constant, a literal) can produce unexpected row multiplication. The symptom: output row count is orders of magnitude larger than expected.
union() without distinct() creating duplicate Silver records. Two Bronze DataFrames are unioned and written to Silver. The developer assumes union() deduplicates. It doesn't. Silver accumulates duplicates. Downstream Gold aggregations are wrong. No error anywhere in the pipeline.
Shuffle partition count mismatch with data volume. Default 200 shuffle partitions on a 10GB dataset → 50MB per partition, reasonable. Same 200 partitions on a 2TB dataset → 10GB per partition → executor OOM. The shuffle partition count isn’t wrong — it’s wrong for this data volume.
Window function deduplication causing OOM. A window function over a large unbounded partition requires holding the entire partition in executor memory for sorting. A partitionBy("customer_id") where one customer has 50M rows causes OOM on the executor handling that partition. This is skew in window functions — the same problem as join skew, manifesting in a different operator.
Broadcast join OOM on large broadcast table. A developer sets autoBroadcastJoinThreshold to 500MB. A table that's 400MB at query planning time grows to 1.2GB after filter pushdown fails to reduce it. 20 executors × 1.2GB = 24GB of broadcast memory. Cluster OOM. The fix is either reducing the threshold or verifying the actual broadcast table size at runtime.
Trade-offs: What Each Join Strategy Optimizes For
Broadcast join: Optimized for eliminating shuffle overhead when one table is small. Sacrifices executor memory (broadcast table replicated across all executors) and driver memory (broadcast table collected at driver). Inappropriate for tables above ~200MB depending on executor memory configuration.
Sort-merge join: Optimized for correctness and scalability at any table size. Sacrifices performance — two full shuffles, one sort per side. The reliable default when table sizes are unknown or large.
Shuffle hash join: An intermediate strategy — shuffles both tables but skips the sort step, using a hash table instead. Faster than sort-merge for smaller tables. Requires the smaller side to fit in executor memory as a hash table. Spark may choose this automatically when one side is small enough.
AQE skew handling: Optimized for automatic skew resolution without code changes. Sacrifices planning-time optimization — AQE operates at runtime, so skew detection adds execution overhead. Cannot fix extreme skew where a single key holds 40%+ of data.
Salting: Optimized for extreme skew scenarios where AQE is insufficient. Sacrifices code complexity (explicit salt logic, table explosion) and increases data volume on the lookup side.
Real-World Constraints
AQE and determinism: AQE changes the physical execution plan at runtime based on actual data statistics. The same query may produce different execution plans on different runs if the data distribution changes. For debugging, this can be confusing — a query that ran in 2 minutes yesterday takes 20 minutes today because AQE made a different broadcast vs sort-merge decision based on updated statistics. Disable AQE temporarily when debugging plan changes.
Shuffle spill to disk: When executor memory is insufficient to hold shuffle data in memory, Spark spills to disk. Disk spill is orders of magnitude slower than memory. In the Spark UI, look for “Shuffle Spill (Memory)” and “Shuffle Spill (Disk)” metrics in stage details. High disk spill means either executor memory is too small or shuffle partition count is too low (too-large partitions exceed memory).
Catalyst optimizer statistics: Spark’s optimizer makes join strategy decisions based on table statistics — row counts, data sizes, column cardinality. If statistics are stale (table was written without ANALYZE TABLE) or absent, the optimizer may make suboptimal choices — choosing sort-merge where broadcast would be correct, or vice versa.
-- Refresh table statistics for optimizer
ANALYZE TABLE prod.silver.events COMPUTE STATISTICS FOR ALL COLUMNS;What Databricks Expects You to Reason About
The PySpark performance questions on the exam always present a Spark UI metric scenario and ask you to identify the bottleneck and the correct fix. The reasoning pattern is consistent.
Read the task metric distribution, not just the max. Median shuffle read 400MB, max 5GB means skew — not that the data is too large. The fix is skew-specific (AQE, salting), not compute-scaling. Adding more executors does not fix skew — it gives the skewed partition more memory but doesn’t distribute the work.
The official exam question reasoning:
- Min/median shuffle read: 400MB → normal distribution range
- Max shuffle read: 5GB → one partition is 12.5× the median
- One task: 10+ minutes, others: 30 seconds
- Correct answer: AQE skew join handling (
spark.sql.adaptive.skewJoin.enabled = true) - Wrong answer A: “add more executors” — doesn’t fix skew, just costs more
- Wrong answer B: “reduce shuffle.partitions” — makes each partition larger, worsens skew
- Wrong answer C: “salt key manually” — correct technique, but AQE is the automatic solution the exam prefers as first-line response
- Wrong answer D: “increase executor memory” — doesn’t address the distribution problem
Broadcast threshold reasoning. A scenario describing a join between a 500GB fact table and a 5MB dimension table has broadcast as the answer — the 5MB table is below the default 10MB threshold and will be broadcast automatically. The wrong answers involve shuffle operations that are unnecessary for a 5MB table.
approx_count_distinct vs exact. When a scenario asks for distinct user counts in a pipeline where "approximate results are acceptable," approx_count_distinct is the answer — it's faster and cheaper. When exact counts are required (billing, compliance), countDistinct is correct despite the cost.
union() deduplication misconception. Any exam scenario describing unexpected duplicates in a table that was built by combining two DataFrames with .union() has the missing .distinct() call as the root cause — not a write mode issue, not a schema problem.
Summary: The Engineering Lesson
PySpark’s API abstracts execution. That abstraction is valuable — it lets you express complex transformations in readable code. The cost is that the API hides where the performance problems actually live: in the shuffles, in the partition distribution, in the join strategies.
Skew is not a data quality problem. It’s an execution model problem — a mismatch between how the hash function distributes keys and how Spark assumes keys are distributed. The fix is never “clean the data.” The fix is changing the execution strategy so the skewed key doesn’t become a single-executor bottleneck.
The Spark UI is not a debugging tool of last resort. It’s the first tool you open when a job is slow. Stage metrics tell you exactly what’s happening — shuffle read distribution, task duration distribution, spill metrics. The answers are in the numbers if you know what pattern to look for.
Reading those numbers is a skill. The exam tests it directly. Production demands it constantly.
🔥 Next in Series
Part 7 — Medallion Architecture: Bronze → Silver → Gold in Production Reality
The Medallion architecture looks clean on a whiteboard. In production, the edges blur. Bronze tables that should be append-only get overwritten. Silver tables that should be cleaned have quality rules that nobody enforces. Gold tables that should serve BI and ML simultaneously end up serving neither well.
We’ll go deep on data quality enforcement patterns, the difference between materialized views and tables for Gold layer objects, and how to design a Medallion pipeline that degrades gracefully when upstream data quality breaks — rather than silently propagating bad data through all three layers.
💬 Comment Below
What’s the worst skew-related performance problem you’ve debugged in production?
Was it a NULL key accounting for 40% of your join table and one executor processing the entire null partition alone for an hour? A groupBy on a customer ID that had one enterprise account with 10 million events while everyone else had under 100? A window function deduplication that OOM'd because one user_id had 50 million rows?
And — did you find it from the Spark UI task metrics, or did you spend two days adding more executors before someone looked at the partition distribution?
Tags
#pyspark #spark-joins #data-skew #broadcast-join #sort-merge-join #shuffle #aqe #adaptive-query-execution #salting #databricks-certification #dataforge