What you will be able to do
- Classify common DataFrame operations as transformations or actions and predict whether a line of code submits a Spark job
- Explain why deferring execution lets the optimizer rewrite the whole plan before any data is read
- Identify which inserted line actually forces an intermediate DataFrame to be computed, and which only inspect the plan or schema
- Explain why every action re-runs the full lineage and why production pipelines end in a single write
- Distinguish lazy execution, which all Spark applies, from lazy analysis, which applies only under Spark Connect
Key concept
Lazy evaluation — Transformations only add steps to a logical plan and return a new DataFrame. No data is read or computed until an action asks for a concrete result, and then Spark optimizes and runs the whole plan at once.
1.Transformations build a plan, actions run it
Every Spark operation falls into one of two kinds. A transformation adds processing logic to a plan and returns a new DataFrame. An action asks for a result, whether that is printing rows, returning a value to the driver or writing to storage. Only actions make the cluster do any work. A reader who can tell the two apart can tell exactly when a notebook cell will start a Spark job and when it will finish in milliseconds having done nothing.
The transformation category is wider than most people expect. It includes reading data, joins, aggregations and type casting, as well as filter, select and sort. The cost or complexity of an operation doesn't change its kind. A groupBy(...).agg(...) that will eventually shuffle the whole dataset is still a transformation, and writing it down does not materialize its parent DataFrame. Reading is lazy too: spark.read...load(path) doesn't touch the files and only records where the data lives.
Actions are the operations that need a concrete answer. Some display output (show, display), some bring rows back (take(n), first, head, collect), some write to a data source (saveAsTable), and some are aggregations that return a number, such as count. That last group is the one to watch: df.groupBy(...).agg(...) is a transformation, but df.count() is an action and starts a job right away.
| Operation | Kind | What happens when the line runs |
|---|---|---|
| spark.read ... load(path), spark.table(name) | Transformation | A plan node pointing at the source is recorded; no data is loaded |
| filter, select, join, groupBy(...).agg(...), sort | Transformation | A new DataFrame with a longer plan is returned |
| repartition | Transformation | A redistribution step is added to the plan |
| show, display | Action | The plan executes and rows are printed |
| collect, take(n), first, head | Action | The plan executes and rows return to the driver |
| count | Action (aggregation) | The plan executes and a number returns to the driver |
| saveAsTable | Action (write) | The plan executes and results are written to the target |
df_chained = (
df_order.filter(col("o_orderstatus") == "F")
.groupBy(col("o_orderpriority"))
.agg(count(col("o_orderkey")).alias("n_orders"))
.sort(col("n_orders").desc())
)
display(df_chained)What Spark keeps between transformations is a set of instructions, not data. A DataFrame variable holds a logical query against a data source rather than an in-memory result, and that is the main difference from pandas, which executes each step eagerly. Spark doesn't run transformations in the background, cache their output or hold copies on the driver. If a cell contains only transformations, it submits no job and raises no execution error. The plan sits there until an action asks for it.
Checkpoint 1 of 8· Match them up
A notebook cell contains each of these lines. Match each line to what happens when it runs.
Tap a term, then the definition that fits it.
Reading data and aggregating with groupBy(...).agg(...) only add logic to the plan, however expensive they will be later. count returns a value and saveAsTable writes output, so both are actions that start a job right away.
“Transformations: add some processing logic to the plan. Examples include reading data, joins, aggregations, and type casting.”Source: docs.databricks.com
Checkpoint 2 of 8· Exam question
Which statement correctly describes why Apache Spark defers execution of .filter(), .select(), and other DataFrame transformations until an action such as .count() or .show() is called?
Correct answer: A — Spark builds a logical plan of the chain of transformations and only launches computation once an action requests a concrete result, letting the optimizer rewrite the plan first.
- A. This is correct: lazy evaluation means transformations only extend a logical plan, and the Catalyst optimizer can rewrite and combine that whole plan before any physical execution happens. Actual work only starts when an action forces a concrete result to be produced.
- B. This is incorrect because Spark does not eagerly run transformations against a sample to validate them. No computation happens at all until an action is called, so there is no early sample-run followed by a full rerun.
- C. This is incorrect because Spark does not make literal in-memory copies of a DataFrame for each transformation. Transformations only add nodes to a logical plan; no data is materialized or duplicated until an action executes it.
- D. This is incorrect because transformations are not submitted as background jobs at all. Only actions cause the driver to submit a job to the cluster; transformations merely extend the plan an action will later execute.
- E. This is incorrect because transformations are not compiled into executor bytecode or cached automatically as they are written. Nothing runs on executors until an action triggers a job for the accumulated plan.
Checkpoint 3 of 8· Exam question
A data engineer runs the following code in a Databricks notebook cell:
df = spark.read.parquet("/mnt/sales/transactions")
filtered = df.filter(df.amount > 1000)
grouped = filtered.groupBy("region").sum("amount")
No further code is executed in this cell. What happens when this cell finishes running?
Correct answer: A — No Spark job is submitted to the cluster; Spark only records filtered and grouped as logical plans built on top of df, since every call in the cell is a transformation.
- A. This is correct:
read,filter, andgroupBy/sumare all transformations, so the cell only builds up a logical plan referencingdf. No job is submitted to the cluster because no action was called. - B. This is incorrect because no action appears anywhere in the cell, so no job is submitted at all, let alone two separate ones. Filtering and grouping stay purely as plan-building steps until something forces execution.
- C. This is incorrect because being a wide transformation does not make
groupByeager. Wide transformations still only add to the logical plan and only cause a shuffle when a later action forces the plan to run. - D. This is incorrect because leaving a DataFrame unused by an action is not an error condition in Spark; the cell simply finishes with
groupedholding an unexecuted plan, and no exception is raised. - E. This is incorrect because Spark does not selectively execute some transformations eagerly based on file metadata. Every transformation in the chain, including the filter, remains unexecuted until an action is called.
2.Watching laziness line by line
The clearest way to see laziness is to follow a three-line program and ask, after each line, what the cluster has done. The program below uses an RDD (resilient distributed dataset), a collection spread across the cluster that supports the same two kinds of operation as a DataFrame: transformations such as map and actions such as reduce. An RDD is created through sc, the SparkContext, rather than through the spark session that DataFrames use. In this example the answer is nothing until the third line.
lines = sc.textFile("data.txt")
lineLengths = lines.map(lambda s: len(s))
totalLength = lineLengths.reduce(lambda a, b: a + b)After line one, lines is only a pointer to the file and nothing has been loaded. After line two, lineLengths is defined but not computed. Line three calls reduce, which is an action. Only then does Spark split the work into tasks on separate machines. Each machine runs its share of the map plus a local reduction, and only the small answers go back to the driver. DataFrames work the same way: filter, select and groupBy play the role of map, and count or a write plays the role of reduce.
DataFrames are also immutable, and that matters when you want to time or check an intermediate step. Each transformation leaves its input unchanged and returns a new DataFrame, which you assign to a variable. Reassigning a variable to cleaned.select("*") or cleaned.repartition(8) only makes a longer plan, and no job runs. To actually evaluate an intermediate step, call an action on it. For example, print(cleaned.count()) runs every transformation behind cleaned at that point, separately from anything defined afterwards.
Two kinds of calls look as if they do work, but they never execute the data pipeline. explain() only displays the logical or physical plans Spark would use, so it describes work without doing it. Schema inspection, such as df.schema or df.columns, needs the plan to be *analyzed*, meaning column names and types are resolved. It doesn't need the plan to be *executed*. In Spark Classic, the mode that runs without Spark Connect, that analysis happens eagerly as the plan is built, so asking for the schema reads metadata only and runs no job.
Checkpoint 4 of 8· Check yourself
You want to time only the cleaning steps behind cleaned in Spark Classic, before any later transformations are added. Which line actually runs those steps?
count is an action, so it runs every transformation behind cleaned at that point. explain() only displays the plan. repartition is another transformation that makes the plan longer. Schema access needs analysis, not execution, so it runs no job.
“If you want to evaluate an intermediate step of your transformation, call an action.”Source: docs.databricks.com
Checkpoint 5 of 8· Exam question
A developer wants to force Spark to materialize an intermediate DataFrame so its execution time can be measured separately from the rest of the pipeline, using the notebook cell below:
cleaned = raw_df.dropDuplicates().filter(col("status") == "active")
# ADD A LINE HERE to force execution and print row count
final = cleaned.join(other_df, "id")
Which line, inserted where indicated, forces Spark to execute the transformations that build cleaned at that point in the notebook, independent of the later join?
Correct answer: A — print(cleaned.count())
- A. This is correct:
count()is an action, so it forces Spark to executedropDuplicates()andfilter()immediately and return a row count the developer can use to measure timing at that point. - B. This is incorrect because
select("*")is a transformation. It only reassignscleanedto a new logical plan node and does not trigger any computation on the cluster. - C. This is incorrect because
explain()only prints the logical and physical query plan for inspection; it does not execute any of the plan's transformations or touch the underlying data. - D. This is incorrect because
repartition(8)is a transformation that adds a shuffle step to the plan. It does not force execution on its own and would not materializecleanedat that point. - E. This is incorrect because
printSchema()reads only the DataFrame's known schema metadata, which Spark can resolve without scanning any data, so it does not trigger a job.
3.Why waiting pays off: Catalyst optimizes the whole plan
Laziness exists so that the optimizer can see the whole query before deciding how to run it. Spark's query optimizer, Catalyst, plans each query. Because no transformation runs as soon as it is written, Catalyst gets the complete chain from source to action and can choose the most efficient physical plan for all of it, instead of running the steps one by one in the order they were typed.
The plan goes through several stages, and EXPLAIN EXTENDED (or df.explain()) shows each one:
- A parsed logical plan, which is unresolved and comes straight from the query.
- An analyzed logical plan, where unresolved column and table references become fully typed objects.
- An optimized logical plan, produced by applying a set of optimization rules.
- A physical plan, which describes how the work will actually run on the cluster.
Seeing the whole plan lets the optimizer change what work is done, not only the order of it. Predicate pushdown is the standard example: the engine pushes filter conditions down to the storage layer, so data that can't match is skipped instead of being read and then thrown away. A filter written after a join can only be applied at the scan because Spark hadn't read anything when the filter was declared. The RDD example shows the same benefit on a small scale: Spark knows the mapped dataset only feeds a reduce, so it returns just the reduced result to the driver and never the larger mapped dataset.
Every action marks the edge of what can be optimized together. The optimizer considers all transformations triggered by a given action at once, so an action in the middle of a pipeline splits it into separately optimized pieces. That is why stray show or count calls in production code cost more than the time they take to print.
Checkpoint 6 of 8· Check yourself
A production job reads orders, joins customers, calls show() on the joined DataFrame to preview it, then filters the result and writes it with saveAsTable. What does the show() call in the middle do to how Spark optimizes the job?
The optimizer considers all transformations triggered by a given action at once. That makes every action a boundary, so the show() in the middle splits the pipeline into pieces that are optimized separately. show() does not keep its result for the write to reuse, and pushing a filter down to the scan works only because nothing has been read when the filter is declared.
“These optimizations consider all transformations triggered by a given action at once and find the optimal plan based on the physical layout of the data.”Source: docs.databricks.com
4.Every action recomputes the plan
An action doesn't leave results behind for the next action. A DataFrame is a plan, so each action sends that whole plan back to the source: it reads the files again, joins again and aggregates again. In exploratory work that is usually fine. In a pipeline, a count() added for logging followed by a write runs the full computation twice.
When several actions really do need the same intermediate result, caching is the fix. Persisting a DataFrame keeps it on the cluster after it is first computed, so later actions start from it instead of the source. The mechanics are covered in cache(), persist() and storage levels. Caching has a cost, though. Like preview results, a manual cache in a production pipeline can interrupt whole-plan optimization and raise both cost and latency, so use it only where reuse actually happens.
The production rule follows from this: a pipeline should normally end in one action, the write. Every other action is either a duplicate computation or a break in optimization. Actions such as collect, take and toPandas are a separate case. Their results come back to the driver instead of going to storage, which is useful for inspection but is not how a pipeline should deliver its output. See Bringing rows to the driver (collect, take, toLocalIterator, toPandas).
Checkpoint 7 of 8· Check yourself
In a scheduled pipeline, daily is built from a read, a join and an aggregation. The code logs daily.count() and then writes daily with saveAsTable. Nothing is cached. What work does the cluster do?
An action keeps no results for the next action. count and saveAsTable each run the whole lineage of daily from the source, so the read, join and aggregation happen twice. Persisting daily, or dropping the logging count, avoids the second run.
“By default, each transformed RDD may be recomputed each time you run an action on it.”Source: spark.apache.org
5.Lazy execution everywhere, lazy analysis only under Spark Connect
DataFrame code runs in one of two deployments, and the difference decides when errors surface. Spark Connect is a gRPC-based protocol that specifies how a client application talks to a remote Spark server: the client builds the plan from your transformations and sends it, unresolved, to the server, which analyzes and runs it. Databricks uses Connect on serverless compute, with Databricks Connect, on standard compute for Python notebooks on Databricks Runtime 14.3 and above and Scala notebooks on 13.3 and above, and in Lakeflow pipelines with environment versions configured. Spark Classic is the mode that doesn't use Connect: DataFrame transformations are encoded in a logical plan, and analysis happens eagerly while that plan is built.
Lazy *execution* and lazy *analysis* are separate ideas, and only lazy execution applies to every Spark deployment. In Spark Classic and in Spark Connect, transformations and spark.sql("select ...") queries are lazy, while actions such as collect() and show() run straight away. SQL commands like spark.sql("insert ...") and spark.sql("create ...") are an exception to watch for: they execute eagerly under both.
Analysis timing is where the two differ. Spark Classic analyzes each plan eagerly as it is built and resolves every name immediately, so filtering on a column c that doesn't exist fails on that line, before any action. Spark Connect builds unresolved plans on the client and doesn't analyze them until something needs a resolved plan, such as schema access, explain, persisting or an action. Under Connect, the same bad filter only fails at df.columns or df.show(). The practical consequences are covered in Deferred analysis in Spark Connect.
| Aspect | Spark Classic | Spark Connect |
|---|---|---|
| Query execution | Lazy | Lazy |
| Schema analysis | Eager | Lazy |
| Actions: df.collect(), df.show() | Eager execution | Eager execution |
| SQL commands: spark.sql("insert …"), spark.sql("create …") | Eager execution | Eager execution |
Eager analysis in Classic doesn't mean any data is processed. Resolving column names checks the plan and runs no job, so even in Classic a misspelled column is caught without executing anything.
Checkpoint 8 of 8· Match them up
Match each line of code, and the deployment it runs on, to what happens when that line is reached.
Tap a term, then the definition that fits it.
Both deployments execute queries lazily and run SQL commands such as insert or create eagerly. They differ only in when analysis happens. Classic resolves names as the plan is built, so the bad column fails at once without running a job. Connect defers analysis until schema access, explain, persisting or an action needs a resolved plan.
“The key difference between Spark Connect and Spark Classic is that Spark Connect defers analysis and name resolution to execution time”Source: docs.databricks.com
Sources6
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/spark/faqOfficial docs
“Transformations: add some processing logic to the plan. Examples include reading data, joins, aggregations, and type casting.”
↩︎ Transformations build a plan, actions run it“none of the logic defined by a collection of operations are evaluated until an action is triggered”
↩︎ Transformations build a plan, actions run it“These optimizations consider all transformations triggered by a given action at once”
↩︎ Why waiting pays off: Catalyst optimizes the whole plan“Manually caching data or returning preview results in production pipelines can interrupt these optimizations and lead to increases in cost and latency.”
↩︎ Every action recomputes the plan“Transformations: add some processing logic to the plan. Examples include reading data, joins, aggregations, and type casting.”
↩︎ Exam trap 1“These optimizations consider all transformations triggered by a given action at once and find the optimal plan based on the physical layout of the data.”
↩︎ Checkpoint - 2.https://docs.databricks.com/aws/en/pyspark/basicsOfficial docs
“Because read is a transformation, Spark does not load data until you call an action such as display.”
↩︎ Transformations build a plan, actions run it“Some aggregations are actions, which means that they trigger computations.”
↩︎ Transformations build a plan, actions run it - 3.https://docs.databricks.com/aws/en/pysparkOfficial docs
“Lazy evaluation means that DataFrames store logical queries as a set of instructions against a data source rather than an in-memory result.”
↩︎ Transformations build a plan, actions run it“If you want to evaluate an intermediate step of your transformation, call an action.”
↩︎ Watching laziness line by line“Spark optimizes data processing by identifying the most efficient physical plan to evaluate logic specified by transformations.”
↩︎ Why waiting pays off: Catalyst optimizes the whole plan“In production data pipelines, writing data is typically the only action that should be present.”
↩︎ Every action recomputes the plan“All other actions interrupt query optimization and can lead to bottlenecks.”
↩︎ Every action recomputes the plan“Rather than evaluating each transformation in the exact order specified, Spark waits until an action triggers computation on all transformations.”
↩︎ Key concept - 4.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“RDDs support two types of operations: transformations, which create a new dataset from an existing one”
↩︎ Watching laziness line by line“This dataset is not loaded in memory or otherwise acted on: lines is merely a pointer to the file.”
↩︎ Watching laziness line by line“Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them.”
↩︎ Watching laziness line by line“return only the result of the reduce to the driver, rather than the larger mapped dataset”
↩︎ Why waiting pays off: Catalyst optimizes the whole plan“By default, each transformed RDD may be recomputed each time you run an action on it.”
↩︎ Every action recomputes the plan“By default, each transformed RDD may be recomputed each time you run an action on it.”
↩︎ Exam trap 3 - 5.
“Provides the logical or physical plans for an input statement.”
↩︎ Watching laziness line by line“The optimized logical plan transforms through a set of optimization rules, resulting in the physical plan.”
↩︎ Why waiting pays off: Catalyst optimizes the whole plan“Provides the logical or physical plans for an input statement.”
↩︎ Exam trap 2 - 6.
“Spark Classic performs analysis eagerly during logical plan construction.”
↩︎ Watching laziness line by line“Spark Connect is a gRPC-based protocol within Apache Spark that specifies how a client application can communicate with a remote Spark Server.”
↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect“Transformations are constructed on the client side and sent as unresolved plans to the server.”
↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect“Both Spark Classic and Spark Connect follow the same lazy execution model for query execution.”
↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect“Spark Connect defers analysis and name resolution to execution time”
↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect“spark.sql("select 1 as a, 2 as b").filter("c > 1") will not throw any error because the unresolved plan is client-side only”
↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect“The key difference between Spark Connect and Spark Classic is that Spark Connect defers analysis and name resolution to execution time”
↩︎ Checkpoint - 7.https://docs.databricks.com/aws/en/compute/photonOfficial docs
“The Apache Spark query optimizer (Catalyst) still plans your query”
↩︎ Why waiting pays off: Catalyst optimizes the whole plan - 8.
“Predicate pushdown is a performance optimization where the engine pushes your filter conditions to the storage layer.”
↩︎ Why waiting pays off: Catalyst optimizes the whole plan