PySpark Architecture
Section 5 • Catalyst Engine & DAG Execution Runtime

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
1. Application

Created when SparkSession.builder.getOrCreate() runs. Managed by a single Driver across its entire lifetime.

2. Job

Triggered only when an Action is called (e.g., .count(), .write, .collect()). Transformations are lazily queued!

3. Stage

A physical execution unit formed by pipelining Narrow transformations together. A new stage is created whenever a Shuffle Exchange occurs.

4. Task

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 speed

Narrow Transformations (Zero Shuffle)

Each input partition contributes to at most one output partition. Processed fully in-memory with zero network overhead.

.filter(), .map(), .select(), .withColumn(), .drop()
  • 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.

.groupBy(), .join(), .distinct(), .repartition(), .cube()
  • 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-time
Status: Ready (Waiting for Action trigger)
Active Job Job -
Active Stage Stage -
Running Tasks 0 / 8
Shuffle Write (Disk) 0.0 MB
Shuffle Read (Net) 0.0 MB
Stage 0 • 4 Tasks • WholeStageCodegen [1]
Step 1 • Source Read
spark.read.parquet("s3://logs")
Splits Parquet into 4 Partitions (128MB each)
Step 2 • Narrow Transformation
.filter(col("status") == 200)
Pipelined in-memory. Zero network shuffle.
Step 3 • Narrow Projection
.select("user_id", "country", "bytes")
Column pruning in same task thread.
SHUFFLE EXCHANGE BARRIER • HashPartitioner on 'country' • Local Disk Spilling
Stage 1 • 8 Tasks • Shuffle Read
Step 4 • Wide Transformation
.groupBy("country").agg(sum("bytes"))
Data pulled across network based on hash key.
Step 5 • Action (Job Execution)
.write.mode("overwrite").parquet(...)
Triggers physical DAG submission to Cluster Manager.

Shuffle 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.partitions to 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
python • dag_explain_plan_audit.py
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/")
)