Lazy work and the two ways to describe data
Spark offers two mental models for the same cluster, and choosing between them decides how much optimisation you get for free. An RDD is an immutable, distributed collection you transform with explicit functions; it is eager about partitioning, lazy about computation, and completely unintelligent about the data inside it. A DataFrame adds a schema and a logical plan, which lets Spark reason about columns, push filters down, and reorder work before a single byte moves.
Laziness is the shared property. Transformations record intent; nothing executes until an action â count, write, collect â forces a job. That separation is what makes optimisation possible: Spark can see the entire intent before choosing an order of execution. It is also a trap for newcomers, because a transformation chain with no action burns no cluster time and reveals no error, so mistakes stay invisible until the first write.
After this lesson you should be able to read a Spark UI stage list and explain why it looks that way, predict which of your transformations will shuffle, and decide when the typed API is worth its compile-time safety against the DataFrame's optimiser.
From DataFrame to physical plan
Catalyst is the query optimiser, and it works in four passes. It parses your DataFrame operations into an unresolved logical plan, resolves columns against the schema, applies rule-based rewrites, then runs a cost-based optimiser that uses table statistics to choose between join orders and strategies. Only then does it emit physical plans, pick one, and generate Java bytecode for each stage.
| Plan stage | What Spark knows | Example rewrite |
|---|---|---|
| Logical (unresolved) | Operation graph, no types | filter on a string column |
| Logical (resolved) | Types, columns, expressions | Predicate bound to schema |
| Optimised logical | Statistics applied | Predicate pushdown, constant folding |
| Physical | Candidate strategies with costs | Broadcast hash join over sort-merge |
| Codegen | Bytecode per stage | Whole-stage fused loops |
Two consequences are worth memorising. First, predicate and projection pushdown happen because Spark can see the plan, so rewriting a query into imperative row-by-row logic removes that visibility. Second, statistics drive join selection: without ANALYZE TABLE or explicit spark.sql.autoBroadcastJoinThreshold sizing, a plan that should broadcast a small dimension table may shuffle both sides instead, and the fix is statistics rather than code.
Narrow versus wide transformations
The boundary that governs cost is whether a transformation can run inside one task without exchanging data between executors. Narrow transformations â filter, map, select â chain into a single stage, so data flows through a pipeline of operators without leaving the executor. Wide transformations â join, groupBy, repartition, distinct â require a shuffle: every executor writes files, every other executor reads them, and that boundary is where spills, skew, and network saturation appear.
| Transformation | Type | Shuffle | Typical failure |
|---|---|---|---|
filter, select, withColumn | Narrow | No | Needless column materialisation |
map, flatMap | Narrow | No | UDFs defeating codegen |
union | Narrow | No | Partition count growth |
groupBy, distinct | Wide | Yes | Key skew, executor OOM |
join | Wide | Yes | Broadcast missed, cartesian blowup |
repartition | Wide | Yes | Deliberate but expensive |
coalesce | Narrow | No | Uneven partition sizes |
The practical reading of that table: count your shuffles before you count your lines of code. A ten-step pipeline with two shuffles behaves predictably; the same pipeline with six because each step re-keys differently will spend most of its wall clock moving bytes, and no amount of executor memory fixes that.
Repartitioning with intent
Repartitioning is a tool, not a habit. The legitimate reasons are controlling parallelism before an expensive stage, spreading a skewed key before a join, and matching partition counts so a join can be co-partitioned. The illegitimate reason is doing it "because the job felt slow" â each repartition writes a full copy of the dataset to disk and network.
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
spark = (
SparkSession.builder
.appName("orders-daily")
.config("spark.sql.shuffle.partitions", "200")
.config("spark.sql.adaptive.enabled", "true")
.getOrCreate()
)
orders = spark.read.parquet("s3://lake/raw/orders/")
customers = spark.read.parquet("s3://lake/raw/customers/")
# Filter early: this runs before the join, not after it.
recent = orders.filter(F.col("order_date") >= F.date_sub(F.lit("2026-01-01"), 90))
enriched = recent.join(
customers.select("customer_id", "segment", "region"),
on="customer_id",
how="left",
)
daily = (
enriched.groupBy("order_date", "region", "segment")
.agg(
F.countDistinct("order_id").alias("orders"),
F.sum("amount").alias("revenue"),
F.approx_count_distinct("customer_id").alias("buyers"),
)
.orderBy("order_date", "region")
)
daily.write.mode("overwrite").partitionBy("order_date").parquet(
"s3://lake/mart/daily_revenue/"
)
Read that pipeline as a cost plan rather than as code. The filter is narrow and pushes into the scan. The join is the first shuffle, and broadcast is possible only if the customer side is small â Spark decides from statistics. The aggregation is the second shuffle, and adaptive query execution will coalesce its output partitions at the end so the write does not create two hundred tiny files for a result that fits in eight.
Watching Catalyst do the work
You can see the optimiser rather than trust it. explain(True) prints the parsed, optimised, and physical plans, and the differences between them are the optimisations Spark actually applied to your query.
daily.explain(mode="true")
# A rewrite you can verify in the plan output:
optimised = (
enriched
.where(F.col("segment") == "enterprise")
.select("order_date", "region", "amount")
)
optimised.explain(mode="true")
Look for three signals in the output. A Relation ... pushed filters line in the scan means predicate pushdown worked, so the storage layer is skipping row groups. A BroadcastHashJoin instead of SortMergeJoin means statistics justified broadcasting. And WholeStageCodegen wrapping several operators means Spark fused them into a single loop, which is the difference between interpreting rows one at a time and iterating a compiled pipeline over columns.
If the plan surprises you, the usual culprits are missing statistics, a UDF wrapping a column and hiding its statistics, or a cast that prevents a predicate from being pushed. Materialising a UDF into a real column expression is often worth more than any executor tuning.
Where memory actually goes
Executor memory is divided into storage, execution, and user regions, and shuffles live in the execution region. When a stage's shuffle write exceeds what execution can hold, Spark spills to disk: the job still succeeds, but it now does disk I/O in the middle of a stage that was supposed to be CPU-bound. The lever is fewer partitions with more data each, or more parallelism if the cluster has room.
Skew is the other thief. If one key carries forty percent of the rows, one task does forty percent of the work while hundreds of tasks idle, and the stage duration is set entirely by that outlier. Adaptive skew join handling splits the offending partition automatically; when it does not trigger, salt the key with a random suffix for the join and regroup afterwards.
đĄRead the stage timeline, not the total
A job total hides the story. Open the stage list and compare task duration distributions: a stage where the slowest task is ten times the median is skewed or spilling, and neither is fixed by adding executors.
Common Mistakes
Calling repartition at the start of every job out of superstition
Fix: Let the shuffle partition config and adaptive execution decide; repartition only to fix measured skew
Filtering after a join instead of before it
Fix: Push predicates as close to the source scan as the semantics allow
Wrapping column logic in a Python UDF and losing all optimisation
Fix: Express it with built-in functions so Catalyst can still push, reorder, and codegen
Leaving shuffle partitions at the default 200 for a small dataset
Fix: Size partitions so each is roughly 128 MB and let adaptive coalescing clean up afterwards
Best Practices
- Persist only when a DataFrame is reused across actions, and pick a storage level that matches its size
- Collect statistics with ANALYZE or by writing statistics so join strategies are chosen on evidence
- Prefer parquet with partition pruning over text or CSV for analytical tables
- Check explain output in review the way you would check an index plan
- Cap retries and idempotent writes so a partial overwrite can be safely re-run
Interview Questions
Q1: Why are transformations lazy in Spark?
So the full operation graph can be optimised as one plan; computation begins only when an action forces a job.
Q2: What is the difference between narrow and wide transformations?
Narrow ones run within a task with no data exchange; wide ones require a shuffle across the cluster and therefore define stage boundaries.
Q3: What does Catalyst contribute?
It resolves, rewrites, and cost-optimises the logical plan into a physical plan, applying pushdown, constant folding, and join strategy selection.
Q4: How do you diagnose a slow stage?
Inspect task duration distribution and spill metrics: a long tail indicates skew, high spill indicates partitions too large for execution memory.
Key Takeaways
- DataFrames exist so Catalyst can reason about your query; imperative row logic forfeits that
- Stage boundaries are defined by shuffles, so cost analysis starts by counting wide transformations
- Statistics determine join strategy, which is why unstated statistics produce slow plans
- Predicate pushdown, broadcast joins, and codegen are visible in explain output and worth verifying
- Skew and spill are the two common causes of a slow stage, and neither is solved by adding executors