Reading a Physical Plan
Concepts covered: Spark UI Diagnosis
explain() with no arguments prints the physical plan alone: the tree the executors will run. Read it from the bottom. The most indented line is where data enters, and each line above consumes the output of the line beneath it. A +- marks a child, and when an operator has 2 children, as a union does, the first hangs from :-.
from pyspark.sql import functions as F
txns = spark.table("transactions")
top_products = (
txns.filter(F.col("quantity") > 0)
.groupBy("product_id")
.agg(F.sum("total_amount").alias("revenue"))
.orderBy(F.desc("revenue"))
)
top_products.explain()On a recent Spark version it prints the tree below, shown with its lines numbered in reading order.
| Read | Line as printed | What it tells you |
|---|---|---|
| top | AdaptiveSparkPlan isFinalPlan=false | A wrapper for re-planning during the run, covered later; read the tree under it |
| 7 | +- Sort [revenue#30 DESC NULLS LAST], true, 0 | Sorts within each range; true marks a global sort |
| 6 | +- Exchange rangepartitioning(revenue#30 DESC NULLS LAST, 200), ENSURE_REQUIREMENTS, [plan_id=61] | Range shuffle for orderBy, a stage boundary |
| 5 | +- HashAggregate(keys=[product_id#22], functions=[sum(total_amount#24)]) | Final revenue per product |
| 4 | +- Exchange hashpartitioning(product_id#22, 200), ENSURE_REQUIREMENTS, [plan_id=58] | Hash shuffle the final aggregate needs, a stage boundary |
| 3 | +- HashAggregate(keys=[product_id#22], functions=[partial_sum(total_amount#24)]) | Partial revenue per product inside each task |
| 2 | +- Filter (isnotnull(quantity#23) AND (quantity#23 > 0)) | Your filter plus the inferred null test |
| 1 | +- FileScan parquet [product_id#22,quantity#23,total_amount#24] | Reads 3 columns; the full line goes on to list files and filters |
Make 3 checks in every reading. Count the Exchange lines: 2 here, so the main work runs as 3 stages. The range boundaries add a short sampling job of their own, which reads the final aggregate's output once it is ready and finishes before the range shuffle writes. Read the tag after each Exchange: ENSURE_REQUIREMENTS means the planner inserted it to meet an operator's need, while REPARTITION_BY_COL (you passed only columns) or REPARTITION_BY_NUM (you passed a count) means a repartition in your code put it there. Then look below the first Exchange: the filter and the partial sum both run before any byte crosses the network, the cheapest place in the job for work to happen.
Which call sorts by_product by total_amount and leaves the repartition's Exchange as the only one in the plan?
by_product = spark.table("transactions").repartition("product_id")- by_product.orderBy("total_amount"), since the rows are already hash-partitioned
- by_product.orderBy("total_amount"), once the optimizer drops the repartition
- by_product.sortWithinPartitions("total_amount"), sorting inside each partition
You will also meet plans whose operators carry a *(1) or *(2) prefix, such as the plan of a finished query. The number groups operators Spark compiles into 1 function, a topic for a later lesson, and it never marks a shuffle.
- FileScan transactions (source, 3 columns read)
- Filter quantity > 0 (transform, runs inside each task)
- Partial HashAggregate (transform, sum per task)
- Hash Exchange (queue, product_id); parallelism: 200 partitions
- Final HashAggregate (transform, sum per product)
- Range Exchange (queue, revenue DESC); parallelism: 200 partitions
- Global Sort (transform, sort each range)
- Driver (consumer, collects rows in range order)
- FileScan transactions -> Filter quantity > 0
- Filter quantity > 0 -> Partial HashAggregate
- Partial HashAggregate -> Hash Exchange
- Hash Exchange -> Final HashAggregate
- Final HashAggregate -> Range Exchange
- Range Exchange -> Global Sort
- Global Sort -> Driver
- Stage 0: FileScan transactions, Filter quantity > 0, Partial HashAggregate
- Shuffle 1: Hash Exchange
- Stage 1: Final HashAggregate
- Shuffle 2: Range Exchange
- Stage 2: Global Sort
- Result: Driver
A query you wrote with no repartition call prints a plan with 2 Exchange lines, both tagged ENSURE_REQUIREMENTS: a hashpartitioning lower down and a rangepartitioning above it. What does that plan tell you?
- 2 stages, 1 per Exchange; the hash shuffle serves an aggregate and the range shuffle a global sort
- 3 stages; the tags record repartition calls that Spark copied out of your code for you
- 1 stage; these Exchanges move rows within each executor, so no stage boundary forms
- 3 stages; the planner inserted both shuffles, most likely for an aggregate and then a global sort
From the plan to the Spark UI
The plan predicts the stages, and the Spark UI confirms them. In the Stages tab, each stage boundary should match an Exchange you counted. The tab also lists stages beyond those 3: the sampling job's, and some marked skipped because the run is split across several jobs, so match each stage to the shuffle it writes or reads. In the SQL tab, named SQL / DataFrame on recent versions, the same operator tree is drawn after the run with measured numbers on each box: output rows on the Filter, records and bytes written on each Exchange, rows out of each HashAggregate. When the query is slow, those numbers answer what the plan raised: did the filter cut as much as expected, did the partial aggregate shrink the rows before the shuffle, and how large was each shuffle.
This program draws on every phase of the lesson. Which description of its physical plan is right?
from pyspark.sql import functions as F
events = spark.table("user_events")
per_country = (
events.repartition("country")
.groupBy("country", "event_type")
.agg(F.count("*").alias("n"))
.filter(F.col("country") == "US")
)
per_country.explain()- 2 Exchanges: the repartition's, then another for the groupBy on 2 columns, with the filter applied last
- 1 Exchange tagged REPARTITION_BY_COL, with the country filter beneath it, so only US rows are shuffled
- 1 Exchange tagged REPARTITION_BY_COL, with the country filter above the final aggregate, as written
- 1 Exchange tagged ENSURE_REQUIREMENTS for the groupBy, after the optimizer drops the repartition
About this lesson
This section is part of the Catalyst Optimizer: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.