Lazy plans

Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 3:40 on Wednesday afternoon. You run a notebook cell with eight lines of PySpark: read, filter, join, add columns. It finishes in 0.3 seconds. The next cell is one line, df.count(), and it takes four minutes. Nora looks over: "Which of the two cells is broken?"

You'll learn to

  • Tell a transformation from an action
  • Read a physical plan from the bottom up
  • Check on the scan line whether a filter reached the file
  • Explain why every action runs the whole plan again

Learn

The first cell did nothing

Neither cell is broken. Look at what each one asks for. The first reads, filters, joins and adds columns. The second counts.

Every DataFrame method is one of two kinds. Most of them only describe a result: select, filter, withColumn, join, groupBy().agg(). Each returns a new DataFrame and runs nothing. Spark calls these transformations. All they do is add a step to a logical plan, Spark's description of the result you want.

A few methods need a real answer: count, collect, show, write. Spark calls these actions. An action runs a job: the whole plan, from the files to the result.

So your first cell wrote a recipe in 0.3 seconds. The count() cooked it, and the cooking took four minutes.

Which is which

Transformations (lazy: they write the plan)Actions (they run a job)
select, withColumn, dropcount()
filter or wherecollect(), first(), take(n)
join, unionshow(), and display() on Databricks
groupBy(...).agg(...), orderBywrite.parquet(path), saveAsTable
groupBy(...).count() (yes, still lazy)toPandas(), foreach

Watch minispark wait

import minispark as ms

def tag(row):
    print('  working on order', row['order_id'])
    return row['order_id']

placed = ms.read_csv('data/orders.csv', 2).filter(lambda r: r['status'] == 'placed')
ids = placed.map(tag)
print('plan built:', ids)

print('count:', ids.count())

Read the output in order. "plan built" comes first, and printing ids shows a plan, not data. The "working on order" lines appear only after count() is called: the read, the filter and the map were written into the plan and waited there.

Why waiting is clever

Spark waits on purpose. By the time anything runs, it has seen the whole plan, so it can rearrange it. The part of Spark that does this is its optimiser, called Catalyst.

  • It moves a filter as early as it can, ideally into the file reader, so rows you would throw away are never read. This is predicate pushdown (a predicate is a filter condition).
  • It reads only the columns the result uses. This is column pruning. In a Parquet file the other columns stay on disk.
  • It merges steps: two filters become one, and a chain of withColumn calls becomes one step.

You write the steps in the order that reads well. Catalyst runs them in the order that is fast. minispark has no optimiser, and neither does Spark's raw RDD API: there you filter early yourself.

What one action sets off

Six steps from DataFrame code to running tasks: the lazy plan, analysis, optimisation, physical planning, stages from the DAGScheduler, and tasks on executors.

Read it top to bottom. Everything above the first arrow happened in your 0.3 seconds. Everything below it happened inside the four-minute count(). The last two steps are Lesson 12.1.

Ask Spark to show its plan

You do not have to take any of this on trust. Every DataFrame has an explain() method that prints its plan, and explain(True) prints it four times, once per phase:

  1. Parsed: what you wrote.
  2. Analysed: the same, with every column name checked and given its type.
  3. Optimised: after Catalyst's rewrites.
  4. Physical: the plan that will run, made of real operators (Spark's word for one step of a plan).

Two reading rules. A plan prints as a tree with the result at the top and the file read at the bottom, so read it from the bottom up. And the physical plan is the one that counts: it is the best evidence you will ever get about a slow job.

Here is a small query on a real cluster: the delivered orders, two columns.

explain(True) on a real cluster

Runs on Databricks:

from pyspark.sql import functions as F

orders = spark.read.parquet("/Volumes/swiftkart/raw/orders")
delivered = (orders
    .filter(F.col("status") == "delivered")
    .select("order_id", "amount"))
delivered.explain(True)
== Parsed Logical Plan ==
'Project ['order_id, 'amount]
+- Filter (status#3 = delivered)
   +- Relation [order_id#0,customer_id#1,order_ts#2,status#3,currency#4,amount#5] parquet

== Analyzed Logical Plan ==
order_id: int, amount: double
Project [order_id#0, amount#5]
+- Filter (status#3 = delivered)
   +- Relation [order_id#0,customer_id#1,order_ts#2,status#3,currency#4,amount#5] parquet

== Optimized Logical Plan ==
Project [order_id#0, amount#5]
+- Filter (isnotnull(status#3) AND (status#3 = delivered))
   +- Relation [order_id#0,customer_id#1,order_ts#2,status#3,currency#4,amount#5] parquet

== Physical Plan ==
*(1) Project [order_id#0, amount#5]
+- *(1) Filter (isnotnull(status#3) AND (status#3 = delivered))
   +- *(1) ColumnarToRow
      +- FileScan parquet [order_id#0,status#3,amount#5] Batched: true, DataFilters: [isnotnull(status#3), (status#3 = delivered)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[/Volumes/swiftkart/raw/orders], PartitionFilters: [], PushedFilters: [IsNotNull(status), EqualTo(status,delivered)], ReadSchema: struct<order_id:int,status:string,amount:double>

Open-source Spark 3.5 output. The #0 and #3 numbers are ids Spark gives each column; they change between runs. With Photon on Databricks the operators are named PhotonScan, PhotonFilter and so on, and you read them the same way. In the browser, explain() prints DuckDB's plan instead, because DuckDB runs this course's PySpark. The next picture takes these four plans one at a time.

One query, four plans

The plan of the delivered-orders query as a tree in four phases: as written, with names checked, with a not-null check added by the optimiser, and as the physical plan whose scan reads three columns and takes the filter with it.

  1. Parsed: as you wrote it. Start at the bottom. Read all six columns of the orders files, keep the delivered rows, then keep two columns.

  2. Analysed: names checked. Every column name is looked up in the table's schema and gets a type. The shape of the plan has not changed.

  3. Optimised: a check you never wrote. A null status can never equal "delivered", so Catalyst adds isnotnull(status). A simple check like that is easy to hand to a file reader.

  4. Physical: the plan that runs. The scan now reads 3 of the 6 columns and takes the filter with it as PushedFilters. ColumnarToRow is new: Parquet is read in batches of columns, and this step turns them into rows.

Rows flow upwards: the bottom line runs first. *(1) marks operators that Spark fuses into one compiled function (whole-stage codegen, Lesson 12.7). The scan is outside it, because it hands over batches of columns, not rows.

The plan is not what you wrote

Compare the last step with your code. You wrote: filter, then select two columns.

The plan that runs reads 3 of the 6 columns. That is column pruning: status for the filter, the other two for the result. It checks isnotnull(status), which you never wrote. And it hands the filter to the Parquet reader under PushedFilters. That is predicate pushdown: the reader can now skip chunks of the file that hold no delivered orders.

None of this changed your result. It changed how much work the result costs.

Remember: transformations write the plan, an action runs it, and you read the physical plan from the bottom up.

The same plan as a numbered list

Runs on Databricks:

delivered.explain(mode="formatted")
== Physical Plan ==
* Project (4)
+- * Filter (3)
   +- * ColumnarToRow (2)
      +- Scan parquet  (1)


(1) Scan parquet
Output [3]: [order_id#0, status#3, amount#5]
Batched: true
Location: InMemoryFileIndex [/Volumes/swiftkart/raw/orders]
PushedFilters: [IsNotNull(status), EqualTo(status,delivered)]
ReadSchema: struct<order_id:int,status:string,amount:double>

(2) ColumnarToRow [codegen id : 1]
Input [3]: [order_id#0, status#3, amount#5]

(3) Filter [codegen id : 1]
Input [3]: [order_id#0, status#3, amount#5]
Condition : (isnotnull(status#3) AND (status#3 = delivered))

(4) Project [codegen id : 1]
Output [2]: [order_id#0, amount#5]
Input [3]: [order_id#0, status#3, amount#5]

explain(mode="formatted") prints a short outline, then one block per operator. The numbers in brackets follow the order the operators run in, so (1) is the scan. On a plan with three joins this is far easier to read than one long line per operator.

On Databricks every display(df) is an action, and so is each count() left behind while debugging. Teams strip them from production jobs. In the Spark UI, the SQL / DataFrame tab shows the same physical plan as a graph, with real row counts and times on each operator. That is where you confirm what explain() promised.

When a filter never reaches the file

Sometimes the plan does not get better, and a job reads a whole table to keep one day. The reason is always on the scan line at the bottom. Three lists there say what the reader was given:

  • DataFilters: every filter on the scanned rows.
  • PushedFilters: only the filters the file reader can check by itself.
  • PartitionFilters: filters on the column the folders are named after. Whole folders are skipped.

A filter that shows in DataFilters but not in PushedFilters was checked row by row, after everything had been read.

The reader understands one shape only: a plain column compared with a fixed value. Wrap the column in a function, such as to_date(order_ts), lower(country) or a Python UDF, and the reader cannot use the filter.

One wrapped column, and the rewrite

Runs on Databricks:

from pyspark.sql import functions as F

slow = orders.filter(F.to_date("order_ts") == "2025-06-01")
fast = orders.filter((F.col("order_ts") >= "2025-06-01") & (F.col("order_ts") < "2025-06-02"))
slow.explain()
fast.explain()
== Physical Plan ==
*(1) Filter (isnotnull(order_ts#2) AND (cast(order_ts#2 as date) = 2025-06-01))
+- *(1) ColumnarToRow
   +- FileScan parquet [order_id#0,customer_id#1,order_ts#2,status#3,currency#4,amount#5] ..., PushedFilters: [IsNotNull(order_ts)], ...

== Physical Plan ==
*(1) Filter ((isnotnull(order_ts#2) AND (order_ts#2 >= 2025-06-01 00:00:00)) AND (order_ts#2 < 2025-06-02 00:00:00))
+- *(1) ColumnarToRow
   +- FileScan parquet [order_id#0,customer_id#1,order_ts#2,status#3,currency#4,amount#5] ..., PushedFilters: [IsNotNull(order_ts), GreaterThanOrEqual(order_ts,2025-06-01 00:00:00.0), LessThan(order_ts,2025-06-02 00:00:00.0)], ...

Shortened Spark 3.5 output. Both return the same rows. Look at PushedFilters in each plan: the first holds only IsNotNull(order_ts), the second holds the whole date range. Only the second lets Parquet's min and max statistics skip the row groups of other days.

Skipping whole folders

Order files stored in one folder per day; setting a date filter shows which folders are skipped without a single file being opened.

This is what PartitionFilters buys. Set a date filter and watch: the folders of the other days are never opened, which is cheaper than any filter inside a file.

Every action starts from the beginning

One cost of being lazy catches every team once. A DataFrame is a plan, not data. Nothing is kept when an action finishes, so the next action runs the whole plan again from the files (until you cache it, which is Lesson 12.6).

A notebook that calls display(df), then df.count(), then df.write... reads the files and runs every join three times.

The plan itself can also grow too big. Each withColumn adds a step, and Spark walks the whole plan every time you make a new DataFrame. Three hundred withColumn calls in a loop make a plan so deep that checking it takes minutes, and the PySpark documentation warns it can end in a StackOverflowException. Build the columns in one select instead.

Three actions, three full runs

A timeline of one notebook: display, count and write each run the whole four-minute plan again, twelve minutes in all.

Made-up times: one run of this plan takes four minutes. Read it top to bottom: each action starts from the files, so three actions cost twelve minutes.

Two actions, two runs

import minispark as ms

parsed = []
def parse(row):
    parsed.append(row['order_id'])
    return (row['status'], 1)

pairs = ms.read_csv('data/orders.csv', 4).map(parse)
print('orders:', pairs.count(), '| rows parsed so far:', len(parsed))
print('first pair:', pairs.collect()[0], '| rows parsed so far:', len(parsed))

The file has 80 rows. After count(), 80 rows were parsed. After collect(), 160: the second action read and parsed the whole file again. minispark keeps nothing between actions, the same as Spark.

The trap: the error appears far from the bug. A bad cast or a division by zero inside a transformation fails only when an action forces the plan to run, so the stack trace points at count() or write, not at the line with the bug. On a classic cluster a misspelt column still fails at once, when the names are checked. With Spark Connect (serverless compute) even that waits until the plan is sent. When a long chain fails, run an action after each step on a small sample to find the step at fault.

Operators you will meet in the next lessons

OperatorWhat it doesWhat to check
FileScanReads filesReadSchema (columns read), PushedFilters, PartitionFilters
ColumnarToRowTurns column batches into rowsBatched: true means the vectorised reader ran
Filter, ProjectRow filter, column selectionConditions you did not write (isnotnull) are normal
HashAggregateGroup and aggregate with a hash tablepartial below an Exchange, final above
Exchange hashpartitioning(k, 200)A shuffle by key into 200 partitionsEvery Exchange is a stage boundary
Exchange SinglePartitionEverything to one taskA global sort, limit or window with no partitionBy
SortSorts each partitionBelow a SortMergeJoin, on both sides
SortMergeJoin, BroadcastHashJoinThe join strategyWas the small side broadcast (Lesson 12.4)?
AdaptiveSparkPlanAQE may still change the planisFinalPlan=true only after the job ran
BatchEvalPython, ArrowEvalPythonRows go to Python workers and backA Python UDF: slow, and blocks pushdown

Keep this as a lookup. Lessons 12.3 and 12.4 explain Exchange (a shuffle) and the join operators.

Numbers to remember

CallWhat it printsUse it when
explain() or explain(mode="simple")The physical plan onlyA quick look
explain(True) or mode="extended"The parsed, analysed and optimised logical plans, then the physical planYou want to see what Catalyst changed
mode="formatted"A numbered outline, then one block per operator with inputs, outputs, pushed filters and codegen idThe plan is long
mode="cost"The optimised logical plan with Statistics(sizeInBytes=..., rowCount=...) on each nodeYou want the size estimates the planner used to choose joins
mode="codegen"The Java that whole-stage code generation wrote for each stageYou are studying Lesson 12.7

The five modes exist in Spark 3.0 and later. In SQL they are EXPLAIN EXTENDED, EXPLAIN FORMATTED and so on.

What changed at SwiftKart

Neither cell was broken. The first wrote a plan. The second ran it.

You make two changes to the nightly notebook. You delete two leftover display() calls and a debugging count(): each one was a full run of the plan. And you rewrite a to_date(order_ts) filter as a date range, so the scan line now lists it under PushedFilters.

Nora's rule goes on the team page: "Explain first. Run second."

One line of that four-minute plan is still a mystery: Exchange hashpartitioning. It is where rows move between machines, and it is the most expensive thing Spark does. Lesson 12.3 is about that move.

In one line

Transformations only write a plan and an action runs it, so Spark can rewrite the whole plan first; read the physical plan from the bottom up and check the scan line to see what the reader skipped.

Interview corner

Why is Spark lazy?

Waiting until an action lets Spark see the whole plan and optimise it: Catalyst pushes filters into the scan, reads only the needed columns, collapses projections and picks join strategies. It also skips work nobody asked for. The cost is that each action recomputes the plan unless the DataFrame is cached, errors appear at the action, and very long plans (hundreds of chained withColumn calls) get slow to analyse.

What is the difference between the logical and the physical plan?

The logical plan says what to compute: filters, projections, joins and aggregations, first as written and then rewritten by Catalyst's rules. The physical plan says how: which scan with which pushed filters, which join algorithm, where an Exchange moves data between machines, and which operators are fused into one compiled stage. explain() prints the physical plan, explain(True) all four, and explain(mode="cost") the statistics behind the choices.

What is predicate pushdown, and how do you check that it happened?

Moving a filter as close to the data as possible, ideally into the file reader. With Parquet the reader uses row-group min and max statistics to skip data, and with partitioned folders it skips whole files. In the plan it shows as PushedFilters or PartitionFilters on the FileScan; a predicate only in DataFilters was evaluated after reading.

A filter is in the code, yet the job reads the whole table. How do you find out why?

Run explain(mode="formatted") and compare the scan's DataFilters with its PushedFilters and PartitionFilters. The usual causes are a function around the column (to_date, cast, lower), a Python UDF, or a filter on a derived column the reader cannot see. Rewrite it as a plain comparison on the raw column, for example a timestamp range instead of to_date(...) =, or filter on the partition column itself, and check that the scan's bytes read drop in the SQL tab.