DataFrame Operations: Jobs, Stages, DAG & Tasks
Demystifying Apache Spark's lazy evaluation, narrow pipelining vs wide shuffle boundaries, Stage division, Task scheduling, and out-of-memory spill mechanics.
The Spark Execution Hierarchy: Application → Job → Stage → Task
How Code Translates to Hardware Work
Created when SparkSession.builder.getOrCreate() runs. Managed by a single Driver across its entire lifetime.
Triggered only when an Action is called (e.g., .count(), .write, .collect()). Transformations are lazily queued!
A physical execution unit formed by pipelining Narrow transformations together. A new stage is created whenever a Shuffle Exchange occurs.
The smallest indivisible unit of work. Exactly 1 Task per Partition executed on 1 CPU core inside an Executor JVM.
Narrow vs. Wide Transformations: The Network Shuffle Cost
The primary determinant of cluster speedNarrow Transformations (Zero Shuffle)
Each input partition contributes to at most one output partition. Processed fully in-memory with zero network overhead.
- Pipelined: Catalyst collapses all narrow ops into a single Java bytecode loop (Tungsten Whole-Stage Code Generation).
- Speed: Blazing fast; 100% CPU and memory bound.
Wide Transformations (Shuffle Boundary)
Input partitions contribute to multiple output partitions. Data must be hashed and transferred across the entire cluster network.
- Stage Boundary: Forces completion of Stage N before Stage N+1 can read shuffle files.
- Bottleneck: Disk I/O serialization + TCP network saturations + potential GC pauses.
Interactive Step-by-Step DAG & Shuffle Pipeline Simulator
Step through an actual PySpark ETL pipeline in real-timeShuffle Spill (Memory vs Disk) & Skew Remediation
Why PySpark jobs hang at 99%1. Spill (Memory) vs Spill (Disk)
When wide operations aggregate data that exceeds the Execution Memory pool, PySpark must serialize the records, compress them, and flush them to temporary node scratch disks.
- Spill (Memory): Uncompressed size of the data in JVM heap.
- Spill (Disk): Compressed size written to executor disk.
- Fix: Increase executor memory or increase
spark.sql.shuffle.partitionsto create smaller partition chunks.
2. Adaptive Query Execution (AQE)
In Spark 3.0+, AQE re-optimizes the DAG at runtime based on exact shuffle statistics gathered during Stage completion.
- Coalescing Partitions: Combines thousands of small post-shuffle partitions into fewer larger ones.
- Dynamic Join Conversion: Converts SortMergeJoin to BroadcastHashJoin if data post-filter is under 10MB.
- Skew Join Handling: Automatically splits giant skewed partitions into smaller slices.
Analyzing Physical Execution Plans with explain(extended=True)
How to inspect Parsed, Analyzed, Optimized & Physical Plans
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
# 1. SparkSession with AQE enabled
spark = (
SparkSession.builder
.appName("DAGExecutionMastery")
.config("spark.sql.adaptive.enabled", "true")
.config("spark.sql.adaptive.coalescePartitions.enabled", "true")
.config("spark.sql.adaptive.skewJoin.enabled", "true")
.config("spark.sql.shuffle.partitions", "200") # Default shuffle partitions
.getOrCreate()
)
# 2. Build Pipeline (Lazy - No computations executed yet!)
raw_df = spark.read.parquet("s3a://production-data/web_clickstream/")
# Narrow Transformation (Pipelined in Stage 0)
filtered_df = raw_df.filter(F.col("status_code") == 200).select("user_id", "country", "payload_size")
# Wide Transformation (Introduces Shuffle Exchange -> Stage 1)
aggregated_df = (
filtered_df
.groupBy("country")
.agg(
F.count("user_id").alias("total_visits"),
F.sum("payload_size").alias("total_bytes")
)
)
# 3. Inspect Catalyst Optimizer Plans (Parsed -> Analyzed -> Optimized -> Physical)
print("=== DETAILED PHYSICAL EXECUTION PLAN ===")
aggregated_df.explain(extended=True)
# 4. ACTION CALL - Triggers physical Job, DAG creation, Stage division & Tasks
(
aggregated_df.write
.mode("overwrite")
.parquet("s3a://production-data/aggregated_country_metrics/")
)