Physical Planning

Concepts covered: Catalyst Optimizer

The optimized logical plan still says nothing about partitions, tasks or shuffles. The planner supplies those. It runs a list of strategies, each able to turn certain logical operators into physical ones, and produces a tree that can run as tasks. A logical Aggregate becomes 2 HashAggregate operators: a partial one that sums inside each task, then a final one that merges those sums per key. That pair is the combine-before-shuffle pattern you already know, chosen here by the planner.

Logical operatorPhysical operatorWhat changes
RelationFileScanReads the pruned columns, 1 task per input partition
FilterFilterThe same test, run inside each task
AggregatePartial HashAggregate, then final HashAggregateSums per task, then sums per key
Sort from orderBySort with global set to trueRows ordered across every partition
Sort from sortWithinPartitionsSort with global set to falseRows ordered inside each partition only
Repartition on a columnExchange hashpartitioningThe shuffle you asked for, on your key

Where the Exchanges come from

The logical plan never contained a shuffle. Exchange, the physical operator that performs one, is added after the strategies run, by a rule named EnsureRequirements. Each physical operator declares the partitioning it needs from its child and the partitioning it outputs. A final HashAggregate on region needs every row of a region inside 1 partition, while a FileScan outputs partitions that know nothing about region. Wherever a need meets an output that fails it, EnsureRequirements inserts an Exchange, and wherever an operator needs sorted input it lacks, a Sort.

OperatorNeeds from its childInserted when the need is unmet
Final HashAggregate on regionEvery row of a region in 1 partitionExchange hashpartitioning(region, 200)
Global Sort on total DESCPartitions holding consecutive ranges of totalExchange rangepartitioning(total DESC, 200)
Sort from sortWithinPartitionsNothing across partitionsNo Exchange
Filter or ProjectNothingNo Exchange

The 200 is spark.sql.shuffle.partitions, the default number of shuffle partitions, and the run below uses 3 so every task fits on screen. Before you play it, predict the Exchanges: the final aggregate needs each region clustered, and the global sort needs ranges of totals. The range shuffle also needs boundaries, so Spark samples the totals in a short job of its own, which your action triggers before the job that returns your rows.

from pyspark.sql import functions as F

totals = orders.groupBy("region").agg(F.sum("profit").alias("total"))
ranked = totals.orderBy(F.desc("total"))
ranked.collect()
orders
order_idstatusregionprofit
1CompletedWest120
2CompletedEast80
3ReturnedNorth-20
4CompletedWest200
5PendingEast45
6CompletedNorth60
7CompletedWest90
8ReturnedWest-15
9CompletedEast150
10PendingNorth30
11CompletedWest75
12CompletedEast110

When a requirement is already met

EnsureRequirements adds an Exchange only where the child's partitioning fails the need. After repartition(8, "region"), the rows of each region already sit in 1 partition, so a following groupBy("region") adds no shuffle. The test is looser than it first looks. Hashing on region also satisfies groupBy("region", "status"), because rows that share both values share region. The reverse fails: hashing on both columns scatters a single region across many partitions.

Child partitioned byThen groupBy onNew Exchange?
hash(region)regionNo
hash(region)region, statusNo: equal pairs already share a region
hash(region, status)regionYes: a region spans many partitions
A file scanregionYes: input partitions ignore region

The planner's interface can return several candidate physical plans, but Spark takes the first. Choices between operators are made by checks inside each strategy, many of them comparing size estimates, the subject of the next section.

How many Exchange operators does the physical plan for this program contain?

by_status = orders.repartition(6, "status")
counts = by_status.groupBy("status", "region").count()
ranked = counts.orderBy("count")
rows = ranked.collect()

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.